@opengeni/db 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/chunk-ELMUCYZF.js +906 -0
  2. package/dist/chunk-ELMUCYZF.js.map +1 -0
  3. package/dist/chunk-N4WTE6SB.js +4033 -0
  4. package/dist/chunk-N4WTE6SB.js.map +1 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +3594 -2059
  7. package/dist/index.js.map +1 -1
  8. package/dist/provision-roles.d.ts +472 -43
  9. package/dist/provision-roles.js +1 -1
  10. package/dist/{schema-BejThLcd.d.ts → schema-Bh1Hr7xY.d.ts} +2507 -970
  11. package/dist/schema.d.ts +1 -1
  12. package/dist/schema.js +9 -1
  13. package/drizzle/0122_codex_capacity_same_turn.sql +59 -0
  14. package/drizzle/0123_session_tool_policy_version.sql +14 -0
  15. package/drizzle/0124_session_event_duplicate_lookup.sql +4 -0
  16. package/drizzle/0125_document_drops_visibility.sql +29 -0
  17. package/drizzle/0126_document_access_constraints.sql +138 -0
  18. package/drizzle/0127_document_default_base_index.sql +5 -0
  19. package/drizzle/0128_github_installation_authority.sql +69 -0
  20. package/drizzle/0129_retained_process_reconciliation.sql +356 -0
  21. package/drizzle/0130_workspace_instruction_policies.sql +330 -0
  22. package/drizzle/0131_slack_bot_install_and_post_idempotency.sql +133 -0
  23. package/package.json +4 -3
  24. package/src/event-payload-sanitizer.ts +167 -55
  25. package/src/index.ts +1850 -264
  26. package/src/new-session-drafts.ts +127 -6
  27. package/src/provision-roles.ts +184 -2
  28. package/src/runtime-posture-cli.ts +57 -0
  29. package/src/runtime-posture.ts +770 -0
  30. package/src/schema.ts +243 -3
  31. package/src/session-control.ts +1 -0
  32. package/src/workspace-instruction-policies-schema.ts +140 -0
  33. package/src/workspace-instruction-policies.ts +624 -0
  34. package/dist/chunk-BMFDXFPA.js +0 -155
  35. package/dist/chunk-BMFDXFPA.js.map +0 -1
  36. package/dist/chunk-VUKRIBO5.js +0 -3679
  37. package/dist/chunk-VUKRIBO5.js.map +0 -1
@@ -1,3679 +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
- // The manager session that spawned this one via session_create. Set only
733
- // when the creating grant carried a worker-signed sessionId claim (a session
734
- // spawning a worker); null for direct API creates and scheduled-task runs.
735
- // When set, this worker's terminal-for-now transitions wake the parent so a
736
- // manager can orchestrate workers without busy-polling. Self-referencing FK,
737
- // ON DELETE SET NULL so deleting a manager never cascades into its workers.
738
- parentSessionId: uuid("parent_session_id"),
739
- // Workspace-scoped CREATE idempotency key. NULL means the create carried no
740
- // key (each such create is independent). When set, the partial unique index
741
- // below collapses concurrent/retried creates with the same key in the same
742
- // workspace to a single session row — the dedup that closes the
743
- // double-submit/double-dispatch stuck-queued bug.
744
- createIdempotencyKey: text("create_idempotency_key"),
745
- // Immutable creation-time hierarchy and policy snapshot. These values are
746
- // populated by the database admission boundary and never re-derived from
747
- // a live workspace setting for an existing session.
748
- rootSessionId: uuid("root_session_id").notNull(),
749
- nestedAgentDepth: integer("nested_agent_depth").notNull(),
750
- maxNestedAgentDepthOverride: integer("max_nested_agent_depth_override"),
751
- effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(),
752
- nestedAgentDepthPolicySource: text("nested_agent_depth_policy_source").notNull(),
753
- nestedAgentDepthPolicySessionId: uuid("nested_agent_depth_policy_session_id"),
754
- temporalWorkflowId: text("temporal_workflow_id"),
755
- activeTurnId: uuid("active_turn_id"),
756
- // Actual input tokens reported for the last model call of the most recent
757
- // turn. The pre-turn portable compaction trigger reads this as its budget
758
- // signal (char/4 estimate is the same-turn fallback). Null until a turn with
759
- // usage has completed.
760
- lastInputTokens: integer("last_input_tokens"),
761
- // Operator /compact request flag. The API sets
762
- // it true; the worker honors it BEFORE the next turn's model call by forcing
763
- // a compaction, then clears it. A durable flag (not a transient signal) so
764
- // the trigger survives a worker restart and converges before the next turn.
765
- compactRequested: boolean("compact_requested").notNull().default(false),
766
- queueVersion: integer("queue_version").notNull().default(0),
767
- queueHeadPosition: bigint("queue_head_position", { mode: "number" }).notNull().default(0),
768
- queueTailPosition: bigint("queue_tail_position", { mode: "number" }).notNull().default(0),
769
- directControlState: text("direct_control_state").notNull().default("active"),
770
- directPauseRevision: bigint("direct_pause_revision", { mode: "number" }),
771
- subtreeRunOverrideRevision: bigint("subtree_run_override_revision", {
772
- mode: "number"
773
- }),
774
- controlVersion: bigint("control_version", { mode: "number" }).notNull().default(0),
775
- directControlReason: text("direct_control_reason"),
776
- directControlChangedBy: text("direct_control_changed_by"),
777
- directControlChangedAt: timestamp("direct_control_changed_at", {
778
- withTimezone: true
779
- }),
780
- lastSequence: integer("last_sequence").notNull().default(0),
781
- // The session's PINNED Codex account (manual override from the in-session
782
- // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
783
- // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
784
- // active", never dangles), same pattern as activeSandboxId.
785
- codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
786
- // The Codex account the session's most recent turn ACTUALLY ran on — drives
787
- // the "Running on:" indicator. Written by the worker at the turn boundary. FK
788
- // ON DELETE SET NULL (migration).
789
- codexLastCredentialId: uuid("codex_last_credential_id"),
790
- // The SOURCE of codex_pinned_credential_id (AM-2): 'manual' — the user's
791
- // in-session account switcher, which is SACRED and never moved by any policy —
792
- // or 'policy' — the sharded rotation strategy's deterministic per-session home
793
- // assignment, which MAY be re-sharded to another account when its own account
794
- // caps. NULL when there is no pin (and for every pre-existing row). CHECK
795
- // (manual|policy) lives in the migration; no FK (it describes the pin, not an
796
- // account).
797
- codexPinSource: text("codex_pin_source"),
798
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
799
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
800
- // Assigned by the database trigger whenever canonical updated_at activity
801
- // advances. Legacy rows remain zero until touched; raw delta-only writers
802
- // intentionally omit updated_at and therefore do not allocate revisions.
803
- activityRevision: bigint("activity_revision", { mode: "number" }).notNull().default(0)
804
- },
805
- (table) => ({
806
- workspaceIdentity: uniqueIndex("sessions_workspace_id_idx").on(table.workspaceId, table.id),
807
- workspaceCreated: index("sessions_workspace_created_idx").on(
808
- table.workspaceId,
809
- table.createdAt
810
- ),
811
- // Model-facing monitoring pages use exact (timestamp,id) keysets. Keep the
812
- // older prefix index during rolling deploys; these composites serve both
813
- // deterministic traversal and updatedAfter change scans.
814
- workspaceCreatedId: index("sessions_workspace_created_id_idx").on(
815
- table.workspaceId,
816
- table.createdAt.desc(),
817
- table.id.desc()
818
- ),
819
- workspaceUpdatedId: index("sessions_workspace_updated_id_idx").on(
820
- table.workspaceId,
821
- table.updatedAt.desc(),
822
- table.id.desc()
823
- ),
824
- workspaceActivityRevision: index("sessions_workspace_activity_revision_idx").on(
825
- table.workspaceId,
826
- table.activityRevision.desc(),
827
- table.updatedAt.desc(),
828
- table.id.desc()
829
- ),
830
- variableSet: index("sessions_variable_set_idx").on(table.workspaceId, table.variableSetId),
831
- parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
832
- // Routing index: resolve session_id -> sandbox_group_id at every lease entry
833
- // point and enumerate all sessions in a group for attribution/disclosure.
834
- sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
835
- // Partial unique index: one session per (workspace, create_idempotency_key)
836
- // when a key is present. The boundary trigger reserves the cross-outcome
837
- // winner before this source row commits; a losing source insert is
838
- // suppressed and the domain layer replays the durable winner.
839
- createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql`${table.createIdempotencyKey} is not null`),
840
- rootDepth: index("sessions_workspace_root_depth_idx").on(
841
- table.workspaceId,
842
- table.rootSessionId,
843
- table.nestedAgentDepth
844
- )
845
- })
846
- );
847
- var sessionSpawnDenials = pgTable(
848
- "session_spawn_denials",
849
- {
850
- id: uuid("id").primaryKey().defaultRandom(),
851
- accountId: uuid("account_id").notNull(),
852
- workspaceId: uuid("workspace_id").notNull(),
853
- parentSessionId: uuid("parent_session_id"),
854
- rootSessionId: uuid("root_session_id"),
855
- currentDepth: integer("current_depth").notNull(),
856
- attemptedDepth: bigint("attempted_depth", { mode: "number" }).notNull(),
857
- effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(),
858
- requestedMaxNestedAgentDepthOverride: integer("requested_max_nested_agent_depth_override"),
859
- policySource: text("policy_source").notNull(),
860
- policySessionId: uuid("policy_session_id"),
861
- subjectId: text("subject_id"),
862
- code: text("code").notNull(),
863
- idempotencyKey: text("idempotency_key"),
864
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
865
- },
866
- (table) => ({
867
- workspaceIdentity: uniqueIndex("session_spawn_denials_workspace_id_uq").on(
868
- table.workspaceId,
869
- table.id
870
- ),
871
- workspaceCreated: index("session_spawn_denials_workspace_created_idx").on(
872
- table.workspaceId,
873
- table.createdAt
874
- ),
875
- parent: index("session_spawn_denials_parent_idx").on(
876
- table.workspaceId,
877
- table.parentSessionId,
878
- table.createdAt
879
- ),
880
- idempotency: uniqueIndex("session_spawn_denials_workspace_idempotency_idx").on(table.workspaceId, table.idempotencyKey).where(sql`${table.idempotencyKey} is not null`),
881
- workspaceAccount: foreignKey({
882
- name: "session_spawn_denials_workspace_account_fk",
883
- columns: [table.workspaceId, table.accountId],
884
- foreignColumns: [workspaces.id, workspaces.accountId]
885
- }).onDelete("cascade")
886
- })
887
- );
888
- var sessionPins = pgTable(
889
- "session_pins",
890
- {
891
- id: uuid("id").primaryKey().defaultRandom(),
892
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
893
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
894
- subjectId: text("subject_id").notNull(),
895
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
896
- // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than
897
- // deleting it. That preserves a monotonic version and prevents an ABA race:
898
- // a stale client that saw pin version 1 cannot silently overwrite a later
899
- // unpin+re-pin that would otherwise recreate version 1.
900
- pinned: boolean("pinned").notNull().default(true),
901
- pinnedAt: timestamp("pinned_at", { withTimezone: true }).defaultNow(),
902
- version: integer("version").notNull().default(1)
903
- },
904
- (table) => ({
905
- subjectNonempty: check(
906
- "session_pins_subject_nonempty",
907
- sql`length(btrim(${table.subjectId})) > 0`
908
- ),
909
- versionPositive: check("session_pins_version_positive", sql`${table.version} >= 1`),
910
- stateConsistent: check(
911
- "session_pins_state_consistent",
912
- sql`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`
913
- ),
914
- workspaceAccount: foreignKey({
915
- name: "session_pins_workspace_account_fk",
916
- columns: [table.workspaceId, table.accountId],
917
- foreignColumns: [workspaces.id, workspaces.accountId]
918
- }).onDelete("cascade"),
919
- workspaceSession: foreignKey({
920
- name: "session_pins_workspace_session_fk",
921
- columns: [table.workspaceId, table.sessionId],
922
- foreignColumns: [sessions.workspaceId, sessions.id]
923
- }).onDelete("cascade"),
924
- subjectSession: uniqueIndex("session_pins_subject_workspace_session_idx").on(
925
- table.subjectId,
926
- table.workspaceId,
927
- table.sessionId
928
- ),
929
- subjectPinned: index("session_pins_workspace_subject_pinned_idx").on(
930
- table.workspaceId,
931
- table.subjectId,
932
- table.pinned,
933
- table.pinnedAt.desc(),
934
- table.sessionId.desc()
935
- )
936
- })
937
- );
938
- var sessionListSnapshots = pgTable(
939
- "session_list_snapshots",
940
- {
941
- id: uuid("id").primaryKey().defaultRandom(),
942
- accountId: uuid("account_id").notNull(),
943
- workspaceId: uuid("workspace_id").notNull(),
944
- subjectId: text("subject_id").notNull(),
945
- parentSessionFilter: text("parent_session_filter").notNull().default("all"),
946
- search: text("search"),
947
- ordinarySessionIds: uuid("ordinary_session_ids").array().notNull().default(sql`'{}'::uuid[]`),
948
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
949
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
950
- },
951
- (table) => ({
952
- workspaceAccount: foreignKey({
953
- name: "session_list_snapshots_workspace_account_fk",
954
- columns: [table.workspaceId, table.accountId],
955
- foreignColumns: [workspaces.id, workspaces.accountId]
956
- }).onDelete("cascade"),
957
- subjectNonempty: check(
958
- "session_list_snapshots_subject_nonempty",
959
- sql`length(btrim(${table.subjectId})) > 0`
960
- ),
961
- parentFilterValid: check(
962
- "session_list_snapshots_parent_filter_valid",
963
- sql`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`
964
- ),
965
- searchLength: check(
966
- "session_list_snapshots_search_length",
967
- sql`${table.search} is null or length(${table.search}) <= 200`
968
- ),
969
- workspaceExpiry: index("session_list_snapshots_workspace_expiry_idx").on(
970
- table.workspaceId,
971
- table.subjectId,
972
- table.expiresAt
973
- ),
974
- expiryReaper: index("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id)
975
- })
976
- );
977
- var sessionMcpServers = pgTable(
978
- "session_mcp_servers",
979
- {
980
- id: uuid("id").primaryKey().defaultRandom(),
981
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
982
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
983
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
984
- serverId: text("server_id").notNull(),
985
- name: text("name"),
986
- url: text("url").notNull(),
987
- allowedTools: jsonb("allowed_tools").$type(),
988
- timeoutMs: integer("timeout_ms"),
989
- cacheToolsList: boolean("cache_tools_list").notNull().default(false),
990
- // Human-approval policy: `true` = every tool requires approval, a string[] of
991
- // UNPREFIXED tool names = only those require it, null/absent = auto-run.
992
- requireApproval: jsonb("require_approval").$type(),
993
- // Non-secret pointer resolved at request time by the standalone broker or
994
- // an embedding host. Unlike headersEncrypted, this is safe to project.
995
- connectionRef: jsonb("connection_ref").$type(),
996
- // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
997
- // worker's run-preparation path and never returned by API helpers.
998
- headersEncrypted: jsonb("headers_encrypted").$type().notNull().default({}),
999
- credentialVersion: integer("credential_version").notNull().default(1),
1000
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1001
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1002
- },
1003
- (table) => ({
1004
- sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(
1005
- table.workspaceId,
1006
- table.sessionId,
1007
- table.serverId
1008
- ),
1009
- session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId)
1010
- })
1011
- );
1012
- var files = pgTable(
1013
- "files",
1014
- {
1015
- id: uuid("id").primaryKey().defaultRandom(),
1016
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1017
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1018
- status: text("status").notNull().default("pending_upload"),
1019
- filename: text("filename").notNull(),
1020
- safeFilename: text("safe_filename").notNull(),
1021
- contentType: text("content_type").notNull(),
1022
- sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
1023
- sha256: text("sha256"),
1024
- bucket: text("bucket").notNull(),
1025
- objectKey: text("object_key").notNull(),
1026
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1027
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1028
- },
1029
- (table) => ({
1030
- workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
1031
- objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
1032
- status: index("files_status_idx").on(table.status)
1033
- })
1034
- );
1035
- var fileUploads = pgTable(
1036
- "file_uploads",
1037
- {
1038
- id: uuid("id").primaryKey().defaultRandom(),
1039
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1040
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1041
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
1042
- status: text("status").notNull().default("pending"),
1043
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
1044
- completedAt: timestamp("completed_at", { withTimezone: true }),
1045
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1046
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1047
- },
1048
- (table) => ({
1049
- workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
1050
- fileId: index("file_uploads_file_id_idx").on(table.fileId),
1051
- status: index("file_uploads_status_idx").on(table.status)
1052
- })
1053
- );
1054
- var documentBases = pgTable(
1055
- "document_bases",
1056
- {
1057
- id: uuid("id").primaryKey().defaultRandom(),
1058
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1059
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1060
- name: text("name").notNull(),
1061
- description: text("description"),
1062
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1063
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1064
- },
1065
- (table) => ({
1066
- workspaceCreated: index("document_bases_workspace_created_idx").on(
1067
- table.workspaceId,
1068
- table.createdAt
1069
- )
1070
- })
1071
- );
1072
- var documents = pgTable(
1073
- "documents",
1074
- {
1075
- id: uuid("id").primaryKey().defaultRandom(),
1076
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1077
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1078
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1079
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1080
- status: text("status").notNull().default("queued"),
1081
- title: text("title").notNull(),
1082
- parser: text("parser").notNull().default("liteparse"),
1083
- chunkCount: integer("chunk_count").notNull().default(0),
1084
- error: text("error"),
1085
- sourceKind: text("source_kind").notNull().default("manual_upload"),
1086
- sourceUri: text("source_uri"),
1087
- sourceExternalId: text("source_external_id"),
1088
- sourceTitle: text("source_title"),
1089
- sourceAuthor: text("source_author"),
1090
- sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
1091
- sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
1092
- sourceVersion: text("source_version"),
1093
- aclTags: jsonb("acl_tags").$type().notNull().default([]),
1094
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1095
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1096
- },
1097
- (table) => ({
1098
- baseFile: uniqueIndex("documents_workspace_base_file_idx").on(
1099
- table.workspaceId,
1100
- table.baseId,
1101
- table.fileId
1102
- ),
1103
- baseStatus: index("documents_workspace_base_status_idx").on(
1104
- table.workspaceId,
1105
- table.baseId,
1106
- table.status
1107
- ),
1108
- sourceKind: index("documents_workspace_source_kind_idx").on(
1109
- table.workspaceId,
1110
- table.sourceKind
1111
- ),
1112
- sourceExternalId: index("documents_workspace_source_external_id_idx").on(
1113
- table.workspaceId,
1114
- table.sourceExternalId
1115
- )
1116
- })
1117
- );
1118
- var documentChunks = pgTable(
1119
- "document_chunks",
1120
- {
1121
- id: uuid("id").primaryKey().defaultRandom(),
1122
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1123
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1124
- documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
1125
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1126
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1127
- chunkIndex: integer("chunk_index").notNull(),
1128
- text: text("text").notNull(),
1129
- metadata: jsonb("metadata").$type().notNull().default({}),
1130
- embedding: vector("embedding").notNull(),
1131
- embeddingModel: text("embedding_model").notNull(),
1132
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1133
- },
1134
- (table) => ({
1135
- documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(
1136
- table.workspaceId,
1137
- table.documentId,
1138
- table.chunkIndex
1139
- ),
1140
- base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId)
1141
- })
1142
- );
1143
- var knowledgeMemories = pgTable(
1144
- "knowledge_memories",
1145
- {
1146
- id: uuid("id").primaryKey().defaultRandom(),
1147
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1148
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1149
- status: text("status").notNull().default("proposed"),
1150
- kind: text("kind").notNull().default("semantic"),
1151
- scope: text("scope").notNull().default("workspace"),
1152
- text: text("text").notNull(),
1153
- sourceRefs: jsonb("source_refs").$type().notNull().default([]),
1154
- confidence: integer("confidence").notNull().default(50),
1155
- metadata: jsonb("metadata").$type().notNull().default({}),
1156
- createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, {
1157
- onDelete: "set null"
1158
- }),
1159
- reviewedBy: text("reviewed_by"),
1160
- reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
1161
- // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes
1162
- // (embedder unavailable) persist keyword-searchable rows without a vector.
1163
- embedding: vector("embedding"),
1164
- embeddingModel: text("embedding_model"),
1165
- pinned: boolean("pinned").notNull().default(false),
1166
- usageCount: integer("usage_count").notNull().default(0),
1167
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
1168
- // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
1169
- // NULL); declared here as plain columns like the migration-only composite FK.
1170
- supersedesId: uuid("supersedes_id"),
1171
- supersededById: uuid("superseded_by_id"),
1172
- validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(),
1173
- validUntil: timestamp("valid_until", { withTimezone: true }),
1174
- // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
1175
- textHash: text("text_hash"),
1176
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1177
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1178
- },
1179
- (table) => ({
1180
- workspaceStatus: index("knowledge_memories_workspace_status_idx").on(
1181
- table.workspaceId,
1182
- table.status,
1183
- table.updatedAt
1184
- ),
1185
- workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
1186
- workspaceScope: index("knowledge_memories_workspace_scope_idx").on(
1187
- table.workspaceId,
1188
- table.scope
1189
- ),
1190
- createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(
1191
- table.workspaceId,
1192
- table.createdBySessionId
1193
- ),
1194
- // Working-set selection (partial index mirrors migration 0045).
1195
- workspaceVisible: index("knowledge_memories_workspace_visible_idx").on(table.workspaceId, table.pinned, table.updatedAt).where(sql`${table.status} in ('active', 'approved')`),
1196
- workspaceTextHash: index("knowledge_memories_workspace_text_hash_idx").on(
1197
- table.workspaceId,
1198
- table.textHash
1199
- ),
1200
- 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`)
1201
- })
1202
- );
1203
- var sessionTurns = pgTable(
1204
- "session_turns",
1205
- {
1206
- id: uuid("id").primaryKey().defaultRandom(),
1207
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1208
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1209
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1210
- triggerEventId: uuid("trigger_event_id").notNull(),
1211
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1212
- status: text("status").notNull(),
1213
- source: text("source").notNull().default("user"),
1214
- position: bigint("position", { mode: "number" }).notNull(),
1215
- prompt: text("prompt").notNull(),
1216
- // Host context for this exact turn. System-level at runtime and deliberately
1217
- // separate from the visible prompt/event payload.
1218
- turnInstructions: text("turn_instructions"),
1219
- resources: jsonb("resources").$type().notNull().default([]),
1220
- tools: jsonb("tools").$type().notNull().default([]),
1221
- // false = inherit the durable session policy; true = this turn explicitly
1222
- // replaces it with `tools` after the core subset fence.
1223
- toolsProvided: boolean("tools_provided").notNull().default(false),
1224
- model: text("model").notNull(),
1225
- reasoningEffort: text("reasoning_effort").notNull(),
1226
- sandboxBackend: text("sandbox_backend").notNull(),
1227
- // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
1228
- // constrained to the SandboxOs enum (or NULL) in migration 0018.
1229
- sandboxOs: text("sandbox_os"),
1230
- metadata: jsonb("metadata").$type().notNull().default({}),
1231
- version: integer("version").notNull().default(1),
1232
- executionGeneration: integer("execution_generation").notNull().default(0),
1233
- // Composite FK to session_turn_attempts is installed by migration 0063.
1234
- // It lives in SQL because attempts carry the reciprocal turn FK and because
1235
- // the claim transaction preallocates this ID before inserting the attempt;
1236
- // the SQL constraint is therefore DEFERRABLE INITIALLY DEFERRED.
1237
- activeAttemptId: uuid("active_attempt_id"),
1238
- lineage: jsonb("lineage").$type().notNull().default({}),
1239
- // Required immutable authority captured when the turn is accepted. These
1240
- // columns are deliberately outside mutable metadata/lineage.
1241
- initiatorKind: text("initiator_kind").notNull().default("service"),
1242
- initiatorSubjectId: text("initiator_subject_id").notNull().default("unattributed-legacy"),
1243
- initiatorContext: jsonb("initiator_context").$type().notNull().default({ backfill: true }),
1244
- cancelledBy: text("cancelled_by"),
1245
- cancelReason: text("cancel_reason"),
1246
- // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
1247
- // by a single conditional UPDATE at tools/call time; the row lock serializes
1248
- // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
1249
- toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
1250
- startedAt: timestamp("started_at", { withTimezone: true }),
1251
- finishedAt: timestamp("finished_at", { withTimezone: true }),
1252
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1253
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1254
- },
1255
- (table) => ({
1256
- workspaceIdentity: uniqueIndex("session_turns_workspace_id_idx").on(
1257
- table.workspaceId,
1258
- table.id
1259
- ),
1260
- queue: index("session_turns_workspace_queue_idx").on(
1261
- table.workspaceId,
1262
- table.sessionId,
1263
- table.status,
1264
- table.position
1265
- ),
1266
- oneCurrentInference: uniqueIndex("session_turns_one_current_inference_uq").on(table.workspaceId, table.sessionId).where(sql`${table.status} in ('running','requires_action','recovering','waiting_capacity')`)
1267
- })
1268
- );
1269
- var sessionTurnAttempts = pgTable(
1270
- "session_turn_attempts",
1271
- {
1272
- id: uuid("id").primaryKey(),
1273
- accountId: uuid("account_id").notNull(),
1274
- workspaceId: uuid("workspace_id").notNull(),
1275
- sessionId: uuid("session_id").notNull(),
1276
- turnId: uuid("turn_id").notNull(),
1277
- executionGeneration: integer("execution_generation").notNull(),
1278
- state: text("state").notNull().default("claimed"),
1279
- outcome: text("outcome"),
1280
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1281
- temporalWorkflowRunId: text("temporal_workflow_run_id").notNull(),
1282
- temporalActivityId: text("temporal_activity_id").notNull(),
1283
- workerId: text("worker_id"),
1284
- leaseId: text("lease_id"),
1285
- leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
1286
- verifiedControlRevision: bigint("verified_control_revision", {
1287
- mode: "number"
1288
- }).notNull(),
1289
- // Immutable policy snapshot captured under the session lock at claim.
1290
- mcpApprovalPolicies: jsonb("mcp_approval_policies").$type().notNull(),
1291
- startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(),
1292
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1293
- closedAt: timestamp("closed_at", { withTimezone: true }),
1294
- // The cancelled activity writes this after losing inference, user-visible
1295
- // output, and workspace-persistence authority. Fenced/idempotent cleanup
1296
- // and telemetry may still finish. Temporal activity cancellation or
1297
- // terminalization is transport state only; queue admission and clients use
1298
- // this durable receipt as the physical-quiescence authority.
1299
- quiescedAt: timestamp("quiesced_at", { withTimezone: true })
1300
- },
1301
- (table) => ({
1302
- workspaceAccount: foreignKey({
1303
- name: "session_turn_attempts_workspace_account_fk",
1304
- columns: [table.workspaceId, table.accountId],
1305
- foreignColumns: [workspaces.id, workspaces.accountId]
1306
- }).onDelete("cascade"),
1307
- workspaceSession: foreignKey({
1308
- name: "session_turn_attempts_workspace_session_fk",
1309
- columns: [table.workspaceId, table.sessionId],
1310
- foreignColumns: [sessions.workspaceId, sessions.id]
1311
- }).onDelete("restrict"),
1312
- workspaceTurn: foreignKey({
1313
- name: "session_turn_attempts_workspace_turn_fk",
1314
- columns: [table.workspaceId, table.turnId],
1315
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1316
- }).onDelete("restrict"),
1317
- workspaceIdentity: uniqueIndex("session_turn_attempts_workspace_id_uq").on(
1318
- table.workspaceId,
1319
- table.id
1320
- ),
1321
- ownershipIdentity: uniqueIndex("session_turn_attempts_human_input_owner_uq").on(
1322
- table.accountId,
1323
- table.workspaceId,
1324
- table.sessionId,
1325
- table.turnId,
1326
- table.id
1327
- ),
1328
- liveTurn: uniqueIndex("session_turn_attempts_live_turn_uq").on(table.workspaceId, table.turnId).where(sql`${table.state} in ('claimed', 'running')`),
1329
- liveSession: uniqueIndex("session_turn_attempts_live_session_uq").on(table.workspaceId, table.sessionId).where(sql`${table.state} in ('claimed', 'running')`),
1330
- latestSessionAttempt: index("session_turn_attempts_latest_session_idx").on(
1331
- table.workspaceId,
1332
- table.sessionId,
1333
- table.startedAt.desc(),
1334
- table.id.desc()
1335
- ),
1336
- dispatch: uniqueIndex("session_turn_attempts_dispatch_uq").on(
1337
- table.workspaceId,
1338
- table.temporalWorkflowRunId,
1339
- table.temporalActivityId
1340
- ),
1341
- leaseExpiry: index("session_turn_attempts_lease_expiry_idx").on(table.leaseExpiresAt, table.workspaceId, table.sessionId).where(sql`${table.state} in ('claimed', 'running')`),
1342
- stateValid: check(
1343
- "session_turn_attempts_state_check",
1344
- sql`${table.state} in ('claimed', 'running', 'closed')`
1345
- ),
1346
- outcomeValid: check(
1347
- "session_turn_attempts_outcome_check",
1348
- sql`${table.outcome} is null or ${table.outcome} in (
1349
- 'completed', 'failed', 'cancelled', 'superseded', 'requires_action',
1350
- 'interrupted_recoverable', 'lease_lost_recoverable', 'pre_cutover_closed'
1351
- )`
1352
- ),
1353
- closedConsistent: check(
1354
- "session_turn_attempts_closed_check",
1355
- sql`(${table.state} = 'closed' and ${table.outcome} is not null and ${table.closedAt} is not null)
1356
- or (${table.state} <> 'closed' and ${table.outcome} is null and ${table.closedAt} is null)`
1357
- )
1358
- })
1359
- );
1360
- var sessionCommandReceipts = pgTable(
1361
- "session_command_receipts",
1362
- {
1363
- id: uuid("id").primaryKey().defaultRandom(),
1364
- accountId: uuid("account_id").notNull(),
1365
- workspaceId: uuid("workspace_id").notNull(),
1366
- actorType: text("actor_type").notNull(),
1367
- actorSubjectId: text("actor_subject_id"),
1368
- actorAttemptId: uuid("actor_attempt_id"),
1369
- action: text("action").notNull(),
1370
- targetSessionId: uuid("target_session_id"),
1371
- targetTurnId: uuid("target_turn_id"),
1372
- operationKey: text("operation_key").notNull(),
1373
- canonicalRequestHash: text("canonical_request_hash").notNull(),
1374
- appliedControlRevision: bigint("applied_control_revision", {
1375
- mode: "number"
1376
- }),
1377
- appliedQueueVersion: integer("applied_queue_version"),
1378
- appliedTurnVersion: integer("applied_turn_version"),
1379
- appliedDraftRevision: bigint("applied_draft_revision", { mode: "number" }),
1380
- result: jsonb("result").$type().notNull().default({}),
1381
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1382
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1383
- },
1384
- (table) => ({
1385
- workspaceAccount: foreignKey({
1386
- name: "session_command_receipts_workspace_account_fk",
1387
- columns: [table.workspaceId, table.accountId],
1388
- foreignColumns: [workspaces.id, workspaces.accountId]
1389
- }).onDelete("cascade"),
1390
- actorAttempt: foreignKey({
1391
- name: "session_command_receipts_actor_attempt_fk",
1392
- columns: [table.workspaceId, table.actorAttemptId],
1393
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1394
- }).onDelete("restrict"),
1395
- targetSession: foreignKey({
1396
- name: "session_command_receipts_target_session_fk",
1397
- columns: [table.workspaceId, table.targetSessionId],
1398
- foreignColumns: [sessions.workspaceId, sessions.id]
1399
- }).onDelete("restrict"),
1400
- targetTurn: foreignKey({
1401
- name: "session_command_receipts_target_turn_fk",
1402
- columns: [table.workspaceId, table.targetTurnId],
1403
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1404
- }).onDelete("restrict"),
1405
- workspaceIdentity: uniqueIndex("session_command_receipts_workspace_id_uq").on(
1406
- table.workspaceId,
1407
- table.id
1408
- ),
1409
- targetCreated: index("session_command_receipts_target_created_idx").on(
1410
- table.workspaceId,
1411
- table.targetSessionId,
1412
- table.createdAt
1413
- ),
1414
- goalUpdateOperation: uniqueIndex("session_command_receipts_goal_update_operation_uq").on(table.workspaceId, table.action, table.targetSessionId, table.operationKey).where(sql`${table.action} = 'goal.update'`),
1415
- actorValid: check(
1416
- "session_command_receipts_actor_check",
1417
- sql`(
1418
- ${table.actorType} = 'agent_attempt'
1419
- and ${table.actorAttemptId} is not null
1420
- and ${table.actorSubjectId} is null
1421
- ) or (
1422
- ${table.actorType} in ('human', 'operator', 'service')
1423
- and ${table.actorSubjectId} is not null
1424
- and ${table.actorAttemptId} is null
1425
- )`
1426
- )
1427
- })
1428
- );
1429
- var workspaceControlEvents = pgTable(
1430
- "workspace_control_events",
1431
- {
1432
- id: uuid("id").primaryKey().defaultRandom(),
1433
- accountId: uuid("account_id").notNull(),
1434
- workspaceId: uuid("workspace_id").notNull(),
1435
- revision: bigint("revision", { mode: "number" }).notNull(),
1436
- scope: text("scope").notNull(),
1437
- rootSessionId: uuid("root_session_id"),
1438
- action: text("action").notNull(),
1439
- automatic: boolean("automatic").notNull().default(false),
1440
- reason: text("reason"),
1441
- reasonOriginalBytes: integer("reason_original_bytes"),
1442
- actor: text("actor").notNull(),
1443
- // Null is the rolling-upgrade shape for untouched, already-bounded legacy
1444
- // rows. New writes and rewritten poison rows carry exact source byte facts.
1445
- actorOriginalBytes: integer("actor_original_bytes"),
1446
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
1447
- },
1448
- (table) => ({
1449
- workspaceAccount: foreignKey({
1450
- name: "workspace_control_events_workspace_account_fk",
1451
- columns: [table.workspaceId, table.accountId],
1452
- foreignColumns: [workspaces.id, workspaces.accountId]
1453
- }).onDelete("cascade"),
1454
- rootSession: foreignKey({
1455
- name: "workspace_control_events_root_session_fk",
1456
- columns: [table.workspaceId, table.rootSessionId],
1457
- foreignColumns: [sessions.workspaceId, sessions.id]
1458
- }).onDelete("restrict"),
1459
- workspaceRevision: uniqueIndex("workspace_control_events_workspace_revision_uq").on(
1460
- table.workspaceId,
1461
- table.revision
1462
- ),
1463
- revisionValid: check("workspace_control_events_revision_check", sql`${table.revision} > 0`),
1464
- shapeValid: check(
1465
- "workspace_control_events_shape_check",
1466
- sql`(${table.scope} = 'workspace' and ${table.rootSessionId} is null)
1467
- or (${table.scope} = 'session' and ${table.rootSessionId} is not null)`
1468
- ),
1469
- actionValid: check(
1470
- "workspace_control_events_action_check",
1471
- sql`${table.action} in ('pause', 'resume')`
1472
- )
1473
- })
1474
- );
1475
- var sessionAttemptInterruptions = pgTable(
1476
- "session_attempt_interruptions",
1477
- {
1478
- id: uuid("id").primaryKey().defaultRandom(),
1479
- accountId: uuid("account_id").notNull(),
1480
- workspaceId: uuid("workspace_id").notNull(),
1481
- sessionId: uuid("session_id").notNull(),
1482
- operationId: uuid("operation_id").notNull(),
1483
- attemptId: uuid("attempt_id").notNull(),
1484
- kind: text("kind").notNull(),
1485
- controlRevision: bigint("control_revision", { mode: "number" }).notNull(),
1486
- state: text("state").notNull().default("pending"),
1487
- requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(),
1488
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1489
- acknowledgedAt: timestamp("acknowledged_at", { withTimezone: true }),
1490
- settledAt: timestamp("settled_at", { withTimezone: true })
1491
- },
1492
- (table) => ({
1493
- workspaceAccount: foreignKey({
1494
- name: "session_attempt_interruptions_workspace_account_fk",
1495
- columns: [table.workspaceId, table.accountId],
1496
- foreignColumns: [workspaces.id, workspaces.accountId]
1497
- }).onDelete("cascade"),
1498
- workspaceSession: foreignKey({
1499
- name: "session_attempt_interruptions_workspace_session_fk",
1500
- columns: [table.workspaceId, table.sessionId],
1501
- foreignColumns: [sessions.workspaceId, sessions.id]
1502
- }).onDelete("restrict"),
1503
- operation: foreignKey({
1504
- name: "session_attempt_interruptions_operation_fk",
1505
- columns: [table.workspaceId, table.operationId],
1506
- foreignColumns: [sessionCommandReceipts.workspaceId, sessionCommandReceipts.id]
1507
- }).onDelete("restrict"),
1508
- attempt: foreignKey({
1509
- name: "session_attempt_interruptions_attempt_fk",
1510
- columns: [table.workspaceId, table.attemptId],
1511
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1512
- }).onDelete("restrict"),
1513
- operationAttempt: uniqueIndex("session_attempt_interruptions_operation_attempt_uq").on(
1514
- table.operationId,
1515
- table.attemptId
1516
- ),
1517
- unsettled: index("session_attempt_interruptions_unsettled_idx").on(table.workspaceId, table.sessionId, table.requestedAt).where(sql`${table.state} in ('pending', 'delivered', 'acknowledged')`),
1518
- kindValid: check(
1519
- "session_attempt_interruptions_kind_check",
1520
- sql`${table.kind} in ('session_pause', 'workspace_pause', 'steer', 'maintenance')`
1521
- ),
1522
- stateValid: check(
1523
- "session_attempt_interruptions_state_check",
1524
- sql`${table.state} in ('pending', 'delivered', 'acknowledged', 'settled', 'rejected_stale')`
1525
- )
1526
- })
1527
- );
1528
- var composerDrafts = pgTable(
1529
- "composer_drafts",
1530
- {
1531
- id: uuid("id").primaryKey().defaultRandom(),
1532
- accountId: uuid("account_id").notNull(),
1533
- workspaceId: uuid("workspace_id").notNull(),
1534
- sessionId: uuid("session_id").notNull(),
1535
- subjectId: text("subject_id").notNull(),
1536
- revision: bigint("revision", { mode: "number" }).notNull().default(1),
1537
- text: text("text").notNull().default(""),
1538
- resources: jsonb("resources").$type().notNull().default([]),
1539
- tools: jsonb("tools").$type().notNull().default([]),
1540
- toolsProvided: boolean("tools_provided").notNull().default(false),
1541
- model: text("model").notNull(),
1542
- reasoningEffort: text("reasoning_effort").notNull(),
1543
- sourceTurnId: uuid("source_turn_id"),
1544
- sourceTurnVersion: integer("source_turn_version"),
1545
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1546
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1547
- },
1548
- (table) => ({
1549
- workspaceAccount: foreignKey({
1550
- name: "composer_drafts_workspace_account_fk",
1551
- columns: [table.workspaceId, table.accountId],
1552
- foreignColumns: [workspaces.id, workspaces.accountId]
1553
- }).onDelete("cascade"),
1554
- workspaceSession: foreignKey({
1555
- name: "composer_drafts_workspace_session_fk",
1556
- columns: [table.workspaceId, table.sessionId],
1557
- foreignColumns: [sessions.workspaceId, sessions.id]
1558
- }).onDelete("cascade"),
1559
- sourceTurn: foreignKey({
1560
- name: "composer_drafts_source_turn_fk",
1561
- columns: [table.workspaceId, table.sourceTurnId],
1562
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1563
- }).onDelete("restrict"),
1564
- subjectSession: uniqueIndex("composer_drafts_subject_session_uq").on(
1565
- table.workspaceId,
1566
- table.sessionId,
1567
- table.subjectId
1568
- ),
1569
- subjectValid: check(
1570
- "composer_drafts_subject_check",
1571
- sql`length(btrim(${table.subjectId})) > 0`
1572
- ),
1573
- revisionValid: check("composer_drafts_revision_check", sql`${table.revision} >= 1`)
1574
- })
1575
- );
1576
- var newSessionDrafts = pgTable(
1577
- "new_session_drafts",
1578
- {
1579
- id: uuid("id").primaryKey().defaultRandom(),
1580
- accountId: uuid("account_id").notNull(),
1581
- workspaceId: uuid("workspace_id").notNull(),
1582
- subjectId: text("subject_id").notNull(),
1583
- revision: bigint("revision", { mode: "number" }).notNull().default(1),
1584
- text: text("text").notNull().default(""),
1585
- resources: jsonb("resources").$type().notNull().default([]),
1586
- tools: jsonb("tools").$type().notNull().default([]),
1587
- model: text("model").notNull(),
1588
- reasoningEffort: text("reasoning_effort").notNull(),
1589
- sessionOptions: jsonb("session_options").$type().notNull().default({}),
1590
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1591
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1592
- },
1593
- (table) => ({
1594
- workspaceAccount: foreignKey({
1595
- name: "new_session_drafts_workspace_account_fk",
1596
- columns: [table.workspaceId, table.accountId],
1597
- foreignColumns: [workspaces.id, workspaces.accountId]
1598
- }).onDelete("cascade"),
1599
- subjectWorkspace: uniqueIndex("new_session_drafts_subject_workspace_uq").on(
1600
- table.workspaceId,
1601
- table.subjectId
1602
- ),
1603
- subjectValid: check(
1604
- "new_session_drafts_subject_check",
1605
- sql`length(btrim(${table.subjectId})) > 0`
1606
- ),
1607
- revisionValid: check("new_session_drafts_revision_check", sql`${table.revision} >= 1`)
1608
- })
1609
- );
1610
- var sessionSystemUpdates = pgTable(
1611
- "session_system_updates",
1612
- {
1613
- id: uuid("id").primaryKey().defaultRandom(),
1614
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1615
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1616
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1617
- kind: text("kind").notNull(),
1618
- classification: text("classification").notNull().default("info"),
1619
- sourceId: text("source_id").notNull(),
1620
- dedupeKey: text("dedupe_key").notNull(),
1621
- summary: text("summary").notNull(),
1622
- payload: jsonb("payload").$type().notNull().default({}),
1623
- lineage: jsonb("lineage").$type().notNull().default({}),
1624
- // pending: eligible to start/attach to an inference; deferred: preserved
1625
- // after a failed internal-only inference but dormant until a real prompt or
1626
- // a genuinely new pending update arrives; delivered/cancelled/failed are
1627
- // terminal for that delivery attempt.
1628
- state: text("state").notNull().default("pending"),
1629
- deliveredTurnId: uuid("delivered_turn_id").references(() => sessionTurns.id, {
1630
- onDelete: "set null"
1631
- }),
1632
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1633
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1634
- },
1635
- (table) => ({
1636
- kindValid: check(
1637
- "system_updates_kind_check",
1638
- sql`${table.kind} in ('scheduled_occurrence', 'goal_continuation', 'agent_message', 'agent_steer_instruction', 'child_terminal_result')`
1639
- ),
1640
- payloadKindValid: check(
1641
- "system_updates_payload_kind_check",
1642
- sql`${table.payload} ->> 'type' = ${table.kind}`
1643
- ),
1644
- stateValid: check(
1645
- "system_updates_state_check",
1646
- sql`${table.state} in ('pending', 'deferred', 'delivered', 'cancelled', 'superseded', 'failed')`
1647
- ),
1648
- dedupe: uniqueIndex("session_system_updates_dedupe_uq").on(
1649
- table.workspaceId,
1650
- table.sessionId,
1651
- table.dedupeKey
1652
- ),
1653
- pending: index("session_system_updates_pending_idx").on(
1654
- table.workspaceId,
1655
- table.sessionId,
1656
- table.state,
1657
- table.createdAt
1658
- )
1659
- })
1660
- );
1661
- var sessionSystemUpdateOutbox = pgTable(
1662
- "session_system_update_outbox",
1663
- {
1664
- id: uuid("id").primaryKey().defaultRandom(),
1665
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1666
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1667
- sourceSessionId: uuid("source_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1668
- targetSessionId: uuid("target_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1669
- dedupeKey: text("dedupe_key").notNull(),
1670
- kind: text("kind").notNull(),
1671
- classification: text("classification").notNull(),
1672
- sourceId: text("source_id").notNull(),
1673
- summary: text("summary").notNull(),
1674
- payload: jsonb("payload").$type().notNull().default({}),
1675
- lineage: jsonb("lineage").$type().notNull().default({}),
1676
- status: text("status").notNull().default("pending"),
1677
- attempts: integer("attempts").notNull().default(0),
1678
- updateId: uuid("update_id"),
1679
- lastError: text("last_error"),
1680
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1681
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1682
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1683
- },
1684
- (table) => ({
1685
- kindValid: check(
1686
- "system_update_outbox_kind_check",
1687
- sql`${table.kind} = 'child_terminal_result'`
1688
- ),
1689
- payloadKindValid: check(
1690
- "system_update_outbox_payload_kind_check",
1691
- sql`${table.payload} ->> 'type' = 'child_terminal_result'`
1692
- ),
1693
- dedupe: uniqueIndex("session_system_update_outbox_dedupe_uq").on(
1694
- table.workspaceId,
1695
- table.dedupeKey
1696
- ),
1697
- pending: index("session_system_update_outbox_pending_idx").on(table.status, table.createdAt)
1698
- })
1699
- );
1700
- var sessionWorkflowWakeOutbox = pgTable(
1701
- "session_workflow_wake_outbox",
1702
- {
1703
- sessionId: uuid("session_id").primaryKey(),
1704
- accountId: uuid("account_id").notNull(),
1705
- workspaceId: uuid("workspace_id").notNull(),
1706
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
1707
- wakeRevision: bigint("wake_revision", { mode: "number" }).notNull().default(1),
1708
- deliveredRevision: bigint("delivered_revision", { mode: "number" }).notNull().default(0),
1709
- reason: text("reason").notNull(),
1710
- attempts: integer("attempts").notNull().default(0),
1711
- nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
1712
- lastError: text("last_error"),
1713
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1714
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1715
- },
1716
- (table) => ({
1717
- revisionValid: check(
1718
- "session_workflow_wake_outbox_revision_check",
1719
- sql`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`
1720
- ),
1721
- revisionSafe: check(
1722
- "session_workflow_wake_outbox_revision_safe_check",
1723
- sql`${table.wakeRevision} <= 9007199254740991 and ${table.deliveredRevision} <= 9007199254740991`
1724
- ),
1725
- workspaceAccount: foreignKey({
1726
- name: "session_workflow_wake_outbox_workspace_account_fk",
1727
- columns: [table.workspaceId, table.accountId],
1728
- foreignColumns: [workspaces.id, workspaces.accountId]
1729
- }).onDelete("cascade"),
1730
- workspaceSessionFk: foreignKey({
1731
- name: "session_workflow_wake_outbox_workspace_session_fk",
1732
- columns: [table.workspaceId, table.sessionId],
1733
- foreignColumns: [sessions.workspaceId, sessions.id]
1734
- }).onDelete("cascade"),
1735
- workspaceSession: uniqueIndex("session_workflow_wake_outbox_workspace_session_uq").on(
1736
- table.workspaceId,
1737
- table.sessionId
1738
- ),
1739
- pending: index("session_workflow_wake_outbox_pending_idx").on(table.nextAttemptAt, table.updatedAt, table.sessionId).where(sql`${table.wakeRevision} > ${table.deliveredRevision}`)
1740
- })
1741
- );
1742
- var sessionGoals = pgTable(
1743
- "session_goals",
1744
- {
1745
- id: uuid("id").primaryKey().defaultRandom(),
1746
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1747
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1748
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1749
- status: text("status").notNull().default("active"),
1750
- // active | paused | completed
1751
- text: text("text").notNull(),
1752
- successCriteria: text("success_criteria"),
1753
- evidence: text("evidence"),
1754
- // set by goal_complete
1755
- rationale: text("rationale"),
1756
- // set by goal_pause
1757
- pausedReason: text("paused_reason"),
1758
- // agent | user_pause | api | no_progress | max_auto_continuations | limits
1759
- createdBy: text("created_by").notNull().default("api"),
1760
- // api | agent | scheduled_task
1761
- version: integer("version").notNull().default(1),
1762
- // bumped on every set/update; progress signal
1763
- autoContinuations: integer("auto_continuations").notNull().default(0),
1764
- noProgressStreak: integer("no_progress_streak").notNull().default(0),
1765
- maxAutoContinuations: integer("max_auto_continuations"),
1766
- // per-goal override; a configured settings cap (if any) remains the hard ceiling
1767
- lastContinuationTurnId: uuid("last_continuation_turn_id"),
1768
- versionAtLastContinuation: integer("version_at_last_continuation"),
1769
- // Postgres owns the continuation obligation. Terminal settlement advances
1770
- // wakeRevision in the same transaction that makes the session idle;
1771
- // materialization advances observedRevision only alongside the one typed
1772
- // update, timeline events, usage row, and workflow-wake outbox row.
1773
- // Temporal signals and workflow history are replaceable nudges over these
1774
- // monotonic revisions.
1775
- continuationWakeRevision: bigint("continuation_wake_revision", { mode: "number" }).notNull().default(0),
1776
- continuationObservedRevision: bigint("continuation_observed_revision", { mode: "number" }).notNull().default(0),
1777
- metadata: jsonb("metadata").$type().notNull().default({}),
1778
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1779
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1780
- },
1781
- (table) => ({
1782
- workspaceIdentity: uniqueIndex("session_goals_workspace_id_idx").on(
1783
- table.workspaceId,
1784
- table.id
1785
- ),
1786
- workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(
1787
- table.workspaceId,
1788
- table.sessionId
1789
- ),
1790
- status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status),
1791
- continuationRevisionValid: check(
1792
- "session_goals_continuation_revision_check",
1793
- sql`${table.continuationWakeRevision} >= 0 and ${table.continuationObservedRevision} >= 0 and ${table.continuationObservedRevision} <= ${table.continuationWakeRevision} and ${table.continuationWakeRevision} <= 9007199254740991 and ${table.continuationObservedRevision} <= 9007199254740991`
1794
- )
1795
- })
1796
- );
1797
- var codexCapacityWaiters = pgTable(
1798
- "codex_capacity_waiters",
1799
- {
1800
- id: uuid("id").primaryKey().defaultRandom(),
1801
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1802
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1803
- sessionId: uuid("session_id").notNull(),
1804
- goalId: uuid("goal_id").notNull(),
1805
- blockedTurnId: uuid("blocked_turn_id").notNull(),
1806
- workflowId: text("workflow_id").notNull(),
1807
- generation: integer("generation").notNull().default(1),
1808
- status: text("status").notNull().default("waiting"),
1809
- // waiting | resumed | superseded
1810
- goalVersion: integer("goal_version").notNull(),
1811
- policyHash: text("policy_hash"),
1812
- earliestResetAt: timestamp("earliest_reset_at", { withTimezone: true }),
1813
- nextCheckAt: timestamp("next_check_at", { withTimezone: true }).notNull(),
1814
- resetKind: text("reset_kind").notNull(),
1815
- // authoritative | bounded_refresh
1816
- refreshAttempt: integer("refresh_attempt").notNull().default(0),
1817
- // Coalescing outbox generation. Every eligibility-affecting mutation bumps
1818
- // wakeRevision. Duplicate/lost Temporal signals are harmless because only
1819
- // the row-locked evaluator moves observedWakeRevision and may enqueue work.
1820
- wakeRevision: integer("wake_revision").notNull().default(1),
1821
- observedWakeRevision: integer("observed_wake_revision").notNull().default(0),
1822
- lastWakeReason: text("last_wake_reason").notNull().default("capacity_wait_armed"),
1823
- resumedUpdateId: uuid("resumed_update_id"),
1824
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1825
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1826
- },
1827
- (table) => ({
1828
- workspaceSession: uniqueIndex("codex_capacity_waiters_workspace_session_idx").on(
1829
- table.workspaceId,
1830
- table.sessionId
1831
- ),
1832
- workspaceId: uniqueIndex("codex_capacity_waiters_workspace_id_idx").on(
1833
- table.workspaceId,
1834
- table.id
1835
- ),
1836
- pending: index("codex_capacity_waiters_pending_idx").on(
1837
- table.workspaceId,
1838
- table.status,
1839
- table.nextCheckAt
1840
- ),
1841
- wakeRepair: index("codex_capacity_waiters_wake_repair_idx").on(
1842
- table.status,
1843
- table.wakeRevision,
1844
- table.observedWakeRevision
1845
- )
1846
- })
1847
- );
1848
- var sessionEvents = pgTable(
1849
- "session_events",
1850
- {
1851
- id: uuid("id").primaryKey().defaultRandom(),
1852
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1853
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1854
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1855
- turnId: uuid("turn_id"),
1856
- turnGeneration: integer("turn_generation"),
1857
- turnAttemptId: uuid("turn_attempt_id"),
1858
- turnAssociation: text("turn_association"),
1859
- duplicateOfEventId: uuid("duplicate_of_event_id"),
1860
- duplicateReason: text("duplicate_reason"),
1861
- sequence: integer("sequence").notNull(),
1862
- type: text("type").notNull(),
1863
- payload: jsonb("payload").$type().notNull().default({}),
1864
- clientEventId: text("client_event_id"),
1865
- producerId: text("producer_id"),
1866
- producerSeq: integer("producer_seq"),
1867
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1868
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1869
- },
1870
- (table) => ({
1871
- workspaceAttempt: foreignKey({
1872
- name: "session_events_workspace_attempt_fk",
1873
- columns: [table.workspaceId, table.turnAttemptId],
1874
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1875
- }).onDelete("restrict"),
1876
- sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(
1877
- table.workspaceId,
1878
- table.sessionId,
1879
- table.sequence
1880
- ),
1881
- clientEvent: uniqueIndex("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql`${table.clientEventId} is not null`),
1882
- 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`),
1883
- sessionCreated: index("session_events_workspace_session_created_idx").on(
1884
- table.workspaceId,
1885
- table.sessionId,
1886
- table.createdAt
1887
- ),
1888
- sessionTypeSequence: index("session_events_workspace_session_type_sequence_idx").on(
1889
- table.workspaceId,
1890
- table.sessionId,
1891
- table.type,
1892
- table.sequence
1893
- ),
1894
- monitoringTail: index("session_events_workspace_session_monitoring_tail_idx").on(table.workspaceId, table.sessionId, table.sequence).where(
1895
- sql`${table.type} not in ('agent.message.delta', 'agent.reasoning.delta', 'sandbox.command.output.delta', 'terminal.pty.output.delta')`
1896
- ),
1897
- payloadBytes: check(
1898
- "session_events_payload_bytes_check",
1899
- sql`octet_length(${table.payload}::text) <= 65536`
1900
- ),
1901
- typeBytes: check(
1902
- "session_events_type_bytes_check",
1903
- sql`octet_length(${table.type}) <= 256 and position(E'\n' in ${table.type}) = 0 and position(E'\r' in ${table.type}) = 0`
1904
- ),
1905
- clientEventIdBytes: check(
1906
- "session_events_client_event_id_bytes_check",
1907
- sql`${table.clientEventId} is null or octet_length(${table.clientEventId}) <= 1024`
1908
- ),
1909
- producerIdBytes: check(
1910
- "session_events_producer_id_bytes_check",
1911
- sql`${table.producerId} is null or octet_length(${table.producerId}) <= 1024`
1912
- ),
1913
- turnAssociationBytes: check(
1914
- "session_events_turn_association_bytes_check",
1915
- sql`${table.turnAssociation} is null or octet_length(${table.turnAssociation}) <= 64`
1916
- ),
1917
- duplicateReasonBytes: check(
1918
- "session_events_duplicate_reason_bytes_check",
1919
- sql`${table.duplicateReason} is null or octet_length(${table.duplicateReason}) <= 4096`
1920
- )
1921
- })
1922
- );
1923
- var agentRunStates = pgTable("agent_run_states", {
1924
- id: uuid("id").primaryKey().defaultRandom(),
1925
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1926
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1927
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1928
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
1929
- onDelete: "set null"
1930
- }),
1931
- stateVersion: integer("state_version").notNull(),
1932
- serializedRunState: text("serialized_run_state").notNull(),
1933
- pendingApprovals: jsonb("pending_approvals").$type().notNull().default([]),
1934
- // The Codex account that FROZE this run state: the turn's resolved codex
1935
- // credential id (pin > workspace-active), or NULL when frozen on the
1936
- // non-codex / Azure path (or before this column existed). The serialized
1937
- // RunState blob round-trips `reasoning.encrypted_content` minted by the
1938
- // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
1939
- // foreign reasoning ids the Responses backend validates; but the blob carries
1940
- // NO per-item producer tag (those live only on session_history_items). So we
1941
- // stamp the freezing account here: on an approval resume whose codex account
1942
- // DIFFERS from this value,
1943
- // the replay path neutralizes every reasoning item's account-bound identity
1944
- // (encrypted_content + provider id) in the blob before it reaches the model.
1945
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
1946
- // stale-but-null tag still mismatches a live codex id, so the strip stays
1947
- // correct either way). NULL on both sides (non-codex freeze + non-codex
1948
- // resume) is a no-op, so single-account and non-codex sessions are unchanged.
1949
- frozenCodexCredentialId: uuid("frozen_codex_credential_id"),
1950
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1951
- });
1952
- var sessionHumanInputRequests = pgTable(
1953
- "session_human_input_requests",
1954
- {
1955
- id: uuid("id").primaryKey().defaultRandom(),
1956
- accountId: uuid("account_id").notNull(),
1957
- workspaceId: uuid("workspace_id").notNull(),
1958
- sessionId: uuid("session_id").notNull(),
1959
- turnId: uuid("turn_id").notNull(),
1960
- turnGeneration: integer("turn_generation").notNull(),
1961
- creationAttemptId: uuid("creation_attempt_id").notNull(),
1962
- toolCallId: text("tool_call_id").notNull(),
1963
- status: text("status").notNull().default("pending"),
1964
- questions: jsonb("questions").$type().notNull(),
1965
- allowSkip: boolean("allow_skip").notNull().default(false),
1966
- response: jsonb("response").$type(),
1967
- respondedBy: text("responded_by"),
1968
- respondedAt: timestamp("responded_at", { withTimezone: true }),
1969
- expiresAt: timestamp("expires_at", { withTimezone: true }),
1970
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1971
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1972
- },
1973
- (table) => ({
1974
- creationAttemptOwner: foreignKey({
1975
- name: "session_human_input_requests_creation_attempt_fk",
1976
- columns: [
1977
- table.accountId,
1978
- table.workspaceId,
1979
- table.sessionId,
1980
- table.turnId,
1981
- table.creationAttemptId
1982
- ],
1983
- foreignColumns: [
1984
- sessionTurnAttempts.accountId,
1985
- sessionTurnAttempts.workspaceId,
1986
- sessionTurnAttempts.sessionId,
1987
- sessionTurnAttempts.turnId,
1988
- sessionTurnAttempts.id
1989
- ]
1990
- }).onDelete("cascade"),
1991
- toolCall: uniqueIndex("session_human_input_requests_tool_call_uq").on(
1992
- table.workspaceId,
1993
- table.sessionId,
1994
- table.turnId,
1995
- table.toolCallId
1996
- ),
1997
- pendingSession: index("session_human_input_requests_pending_session_idx").on(table.workspaceId, table.sessionId, table.createdAt, table.id).where(sql`${table.status} = 'pending'`),
1998
- 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`),
1999
- status: check(
2000
- "session_human_input_requests_status_check",
2001
- sql`${table.status} in ('pending','answered','skipped','expired','cancelled')`
2002
- ),
2003
- generation: check(
2004
- "session_human_input_requests_generation_check",
2005
- sql`${table.turnGeneration} > 0`
2006
- ),
2007
- toolCallBytes: check(
2008
- "session_human_input_requests_tool_call_bytes_check",
2009
- sql`octet_length(${table.toolCallId}) between 1 and 1024`
2010
- ),
2011
- questionsBytes: check(
2012
- "session_human_input_requests_questions_bytes_check",
2013
- sql`octet_length(${table.questions}::text) <= 49152`
2014
- ),
2015
- responseBytes: check(
2016
- "session_human_input_requests_response_bytes_check",
2017
- sql`${table.response} is null or octet_length(${table.response}::text) <= 49152`
2018
- ),
2019
- actorBytes: check(
2020
- "session_human_input_requests_actor_bytes_check",
2021
- sql`${table.respondedBy} is null or octet_length(${table.respondedBy}) <= 1024`
2022
- )
2023
- })
2024
- );
2025
- var sessionHistoryItems = pgTable(
2026
- "session_history_items",
2027
- {
2028
- id: uuid("id").primaryKey().defaultRandom(),
2029
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2030
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2031
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2032
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2033
- onDelete: "set null"
2034
- }),
2035
- // Numeric (not integer) so the synthetic compaction-summary row can be
2036
- // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
2037
- // of the kept tail without colliding with — and thus overwriting — the real
2038
- // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
2039
- // positions; only the summary uses the half-step. `mode: "number"` maps the
2040
- // postgres.js string back to a JS number so every reader stays numeric.
2041
- position: numeric("position", { mode: "number" }).notNull(),
2042
- item: jsonb("item").$type().notNull(),
2043
- // Live-row flag for client-side context compaction. The read path selects
2044
- // only active rows; a compaction supersedes the summarized prefix (sets this
2045
- // false — never deletes, so the full transcript stays as an audit trail) and
2046
- // inserts ONE synthetic active summary row at the boundary. Defaults true so
2047
- // every existing and normally-appended row is live.
2048
- active: boolean("active").notNull().default(true),
2049
- // The Codex account that PRODUCED these items: the per-turn resolved codex
2050
- // credential id (pin > workspace-active), or NULL when produced on the
2051
- // non-codex / Azure path (or before this column existed). Used to strip
2052
- // cross-account `reasoning.encrypted_content` blobs — those are account/org-
2053
- // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
2054
- // into a turn running on account B 400s. The read path drops the encrypted
2055
- // reasoning of any item whose producer != the turn's current codex account.
2056
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
2057
- // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
2058
- // mismatches a live codex id so the strip stays correct either way).
2059
- producerCodexCredentialId: uuid("producer_codex_credential_id"),
2060
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2061
- },
2062
- (table) => ({
2063
- positionIdx: uniqueIndex("session_history_items_position_idx").on(
2064
- table.workspaceId,
2065
- table.sessionId,
2066
- table.position
2067
- )
2068
- })
2069
- );
2070
- var sessionPendingToolCalls = pgTable(
2071
- "session_pending_tool_calls",
2072
- {
2073
- id: uuid("id").primaryKey().defaultRandom(),
2074
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2075
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2076
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2077
- turnId: uuid("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
2078
- executionGeneration: integer("execution_generation").notNull(),
2079
- attemptId: uuid("attempt_id").notNull(),
2080
- callId: text("call_id").notNull(),
2081
- callType: text("call_type").notNull(),
2082
- callItem: jsonb("call_item").$type().notNull(),
2083
- modelToolOutputTruncationTokens: integer("model_tool_output_truncation_tokens"),
2084
- resultItem: jsonb("result_item").$type(),
2085
- resultRecordedAt: timestamp("result_recorded_at", { withTimezone: true }),
2086
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2087
- },
2088
- (table) => ({
2089
- workspaceAttempt: foreignKey({
2090
- name: "pending_tool_calls_workspace_attempt_fk",
2091
- columns: [table.workspaceId, table.attemptId],
2092
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2093
- }).onDelete("restrict"),
2094
- turnCall: uniqueIndex("session_pending_tool_calls_turn_call_idx").on(
2095
- table.workspaceId,
2096
- table.turnId,
2097
- table.callId
2098
- ),
2099
- sessionTurn: index("session_pending_tool_calls_session_turn_idx").on(
2100
- table.workspaceId,
2101
- table.sessionId,
2102
- table.turnId
2103
- )
2104
- })
2105
- );
2106
- var sandboxSessionEnvelopes = pgTable(
2107
- "sandbox_session_envelopes",
2108
- {
2109
- id: uuid("id").primaryKey().defaultRandom(),
2110
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2111
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2112
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2113
- envelope: jsonb("envelope").$type().notNull(),
2114
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2115
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2116
- },
2117
- (table) => ({
2118
- sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(
2119
- table.workspaceId,
2120
- table.sessionId
2121
- )
2122
- })
2123
- );
2124
- var sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"];
2125
- var sandboxLeases = pgTable(
2126
- "sandbox_leases",
2127
- {
2128
- id: uuid("id").primaryKey().defaultRandom(),
2129
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2130
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2131
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2132
- liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
2133
- refcount: integer("refcount").notNull().default(0),
2134
- turnHolders: integer("turn_holders").notNull().default(0),
2135
- viewerHolders: integer("viewer_holders").notNull().default(0),
2136
- instanceId: text("instance_id"),
2137
- backend: text("backend").notNull(),
2138
- os: text("os").notNull().default("linux"),
2139
- // The container IMAGE the group box runs (Modal image ref / docker image). A shared
2140
- // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
2141
- // same image. This column stamps the image the live box was created with; a resume
2142
- // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
2143
- // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
2144
- // legacy/cold row reads NULL = "image unknown", which never conflicts.
2145
- image: text("image"),
2146
- // The frozen rig version the live box was created under (M3). Like `image`,
2147
- // this is SHARED STATE: all the box's sessions run the same rig-baked setup,
2148
- // so a resume resolving a DIFFERENT rig_version_id conflicts (solo holder
2149
- // recreates cold on the new rig; N-holders throw SandboxRigConflictError).
2150
- // Nullable — a legacy/cold row or a rig-less session reads NULL = "rig
2151
- // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's
2152
- // bare-uuid rationale: this lease outlives no single rig_versions row's RLS).
2153
- rigVersionId: uuid("rig_version_id"),
2154
- dataPlaneUrl: text("data_plane_url"),
2155
- // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
2156
- // from the desktop noVNC (6080), so its resolved URL is cached independently.
2157
- // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
2158
- // null on every box re-key (warm-commit / fail / drain), symmetric with
2159
- // data_plane_url.
2160
- terminalDataPlaneUrl: text("terminal_data_plane_url"),
2161
- // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
2162
- // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
2163
- // was always-true → every turn fenced); int4 returns a JS number, the fix.
2164
- // Epochs never approach 2^31, so the narrower type loses nothing.
2165
- leaseEpoch: integer("lease_epoch").notNull().default(0),
2166
- // Monotonic mutation intent for the live workspace. Every acknowledged
2167
- // filesystem-writing operation advances this under the exact lease epoch +
2168
- // provider-instance fence BEFORE it reaches the provider. A verified
2169
- // archive fold copies the exact captured value into archive_generation in
2170
- // the same row update; equality is the only durable completeness proof.
2171
- workspaceGeneration: integer("workspace_generation").notNull().default(0),
2172
- archiveGeneration: integer("archive_generation"),
2173
- // The group box-envelope (the "envelope split" Critical): the small recovery
2174
- // descriptor to resume()-by-id the group's box without a per-session join.
2175
- resumeBackendId: text("resume_backend_id"),
2176
- resumeState: jsonb("resume_state").$type(),
2177
- // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
2178
- // idempotency tick (warm_seconds accrued idempotent on
2179
- // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
2180
- lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
2181
- lastMeterTick: integer("last_meter_tick").notNull().default(0),
2182
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
2183
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2184
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2185
- },
2186
- (table) => ({
2187
- groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
2188
- scopedId: uniqueIndex("sandbox_leases_scoped_id_uq").on(
2189
- table.accountId,
2190
- table.workspaceId,
2191
- table.sandboxGroupId,
2192
- table.id
2193
- ),
2194
- accountWorkspaceId: uniqueIndex("sandbox_leases_account_workspace_id_uq").on(
2195
- table.accountId,
2196
- table.workspaceId,
2197
- table.id
2198
- ),
2199
- reaperIdx: index("sandbox_leases_reaper_idx").on(table.expiresAt).where(sql`${table.liveness} in ('warming','warm','draining')`),
2200
- workspaceGenerationValid: check(
2201
- "sandbox_leases_workspace_generation_check",
2202
- sql`${table.workspaceGeneration} >= 0`
2203
- ),
2204
- archiveGenerationValid: check(
2205
- "sandbox_leases_archive_generation_check",
2206
- sql`${table.archiveGeneration} is null
2207
- or (${table.archiveGeneration} >= 0
2208
- and ${table.archiveGeneration} <= ${table.workspaceGeneration})`
2209
- )
2210
- })
2211
- );
2212
- var sandboxLeaseHolders = pgTable(
2213
- "sandbox_lease_holders",
2214
- {
2215
- id: uuid("id").primaryKey().defaultRandom(),
2216
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2217
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2218
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2219
- kind: text("kind", { enum: ["turn", "viewer", "direct", "process"] }).notNull(),
2220
- holderId: text("holder_id").notNull(),
2221
- // The attributing session within the (possibly shared) group.
2222
- subjectId: uuid("subject_id"),
2223
- lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
2224
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2225
- },
2226
- (table) => ({
2227
- leaseScope: foreignKey({
2228
- name: "sandbox_lease_holders_lease_scope_fk",
2229
- columns: [table.accountId, table.workspaceId, table.leaseId],
2230
- foreignColumns: [sandboxLeases.accountId, sandboxLeases.workspaceId, sandboxLeases.id]
2231
- }).onDelete("cascade"),
2232
- holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(
2233
- table.leaseId,
2234
- table.kind,
2235
- table.holderId
2236
- ),
2237
- staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
2238
- leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId)
2239
- })
2240
- );
2241
- var sandboxWorkspaceMutationActorKindValues = ["turn", "direct", "process"];
2242
- var sandboxWorkspaceMutationHolderKindValues = ["turn", "direct", "process"];
2243
- var sandboxWorkspaceMutationAdmissions = pgTable(
2244
- "sandbox_workspace_mutation_admissions",
2245
- {
2246
- id: uuid("id").primaryKey().defaultRandom(),
2247
- accountId: uuid("account_id").notNull(),
2248
- workspaceId: uuid("workspace_id").notNull(),
2249
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2250
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2251
- sessionId: uuid("session_id").notNull(),
2252
- actorKind: text("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues }).notNull(),
2253
- actorId: uuid("actor_id").notNull(),
2254
- // Exact turn authority is present only for actor_kind='turn'. Direct HTTP
2255
- // requests and retained processes never invent a turn or quiescence owner.
2256
- turnId: uuid("turn_id"),
2257
- attemptId: uuid("attempt_id"),
2258
- executionGeneration: integer("execution_generation"),
2259
- holderKind: text("holder_kind", {
2260
- enum: sandboxWorkspaceMutationHolderKindValues
2261
- }).notNull(),
2262
- holderId: text("holder_id").notNull(),
2263
- leaseEpoch: integer("lease_epoch").notNull(),
2264
- providerBackend: text("provider_backend").notNull(),
2265
- providerInstanceId: text("provider_instance_id").notNull(),
2266
- routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(),
2267
- // null route target means the persistable home/group provider. A non-null
2268
- // target is pinned together with the active pointer epoch observed when the
2269
- // operation was admitted.
2270
- routeTargetId: uuid("route_target_id"),
2271
- routeEpoch: integer("route_epoch").notNull(),
2272
- workspaceGeneration: integer("workspace_generation").notNull(),
2273
- operation: text("operation").notNull(),
2274
- providerOutcome: text("provider_outcome", {
2275
- enum: ["resolved", "rejected", "retained"]
2276
- }),
2277
- admittedAt: timestamp("admitted_at", { withTimezone: true }).notNull().defaultNow(),
2278
- settledAt: timestamp("settled_at", { withTimezone: true })
2279
- },
2280
- (table) => ({
2281
- workspaceAccount: foreignKey({
2282
- name: "sandbox_workspace_mutation_admissions_workspace_account_fk",
2283
- columns: [table.workspaceId, table.accountId],
2284
- foreignColumns: [workspaces.id, workspaces.accountId]
2285
- }).onDelete("cascade"),
2286
- workspaceSession: foreignKey({
2287
- name: "sandbox_workspace_mutation_admissions_workspace_session_fk",
2288
- columns: [table.workspaceId, table.sessionId],
2289
- foreignColumns: [sessions.workspaceId, sessions.id]
2290
- }).onDelete("restrict"),
2291
- workspaceTurn: foreignKey({
2292
- name: "sandbox_workspace_mutation_admissions_workspace_turn_fk",
2293
- columns: [table.workspaceId, table.turnId],
2294
- foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
2295
- }).onDelete("restrict"),
2296
- workspaceAttempt: foreignKey({
2297
- name: "sandbox_workspace_mutation_admissions_workspace_attempt_fk",
2298
- columns: [table.workspaceId, table.attemptId],
2299
- foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2300
- }).onDelete("restrict"),
2301
- leaseGeneration: uniqueIndex("sandbox_workspace_mutation_admissions_lease_generation_uq").on(
2302
- table.leaseId,
2303
- table.workspaceGeneration
2304
- ),
2305
- scopedId: uniqueIndex("sandbox_workspace_mutation_admissions_scoped_id_uq").on(
2306
- table.accountId,
2307
- table.workspaceId,
2308
- table.sessionId,
2309
- table.leaseId,
2310
- table.id
2311
- ),
2312
- blocking: index("sandbox_workspace_mutation_admissions_blocking_idx").on(table.leaseId, table.workspaceGeneration).where(sql`${table.settledAt} is null`),
2313
- attempt: index("sandbox_workspace_mutation_admissions_attempt_idx").on(
2314
- table.workspaceId,
2315
- table.attemptId
2316
- ),
2317
- actor: index("sandbox_workspace_mutation_admissions_actor_idx").on(
2318
- table.workspaceId,
2319
- table.actorKind,
2320
- table.actorId
2321
- ),
2322
- generationValid: check(
2323
- "sandbox_workspace_mutation_admissions_generation_check",
2324
- sql`${table.workspaceGeneration} > 0
2325
- and ${table.leaseEpoch} >= 0
2326
- and ${table.routeEpoch} >= 0
2327
- and (${table.executionGeneration} is null or ${table.executionGeneration} > 0)`
2328
- ),
2329
- actorValid: check(
2330
- "sandbox_workspace_mutation_admissions_actor_check",
2331
- sql`(
2332
- ${table.actorKind} = 'turn'
2333
- and ${table.actorId} = ${table.attemptId}
2334
- and ${table.turnId} is not null
2335
- and ${table.attemptId} is not null
2336
- and ${table.executionGeneration} is not null
2337
- and ${table.holderKind} = 'turn'
2338
- ) or (
2339
- ${table.actorKind} = 'direct'
2340
- and ${table.turnId} is null
2341
- and ${table.attemptId} is null
2342
- and ${table.executionGeneration} is null
2343
- and ${table.holderKind} = 'direct'
2344
- ) or (
2345
- ${table.actorKind} = 'process'
2346
- and ${table.turnId} is null
2347
- and ${table.attemptId} is null
2348
- and ${table.executionGeneration} is null
2349
- and ${table.holderKind} = 'process'
2350
- )`
2351
- ),
2352
- routeValid: check(
2353
- "sandbox_workspace_mutation_admissions_route_check",
2354
- sql`${table.actorKind} in ('turn', 'direct', 'process')
2355
- and ${table.holderKind} in ('turn', 'direct', 'process')
2356
- and octet_length(${table.holderId}) between 1 and 256
2357
- and octet_length(${table.providerBackend}) between 1 and 64
2358
- and octet_length(${table.providerInstanceId}) between 1 and 512
2359
- and ${table.routeKind} in ('home', 'active')
2360
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
2361
- ),
2362
- operationValid: check(
2363
- "sandbox_workspace_mutation_admissions_operation_check",
2364
- sql`octet_length(${table.operation}) between 1 and 128`
2365
- ),
2366
- outcomeValid: check(
2367
- "sandbox_workspace_mutation_admissions_outcome_check",
2368
- sql`${table.providerOutcome} is null or ${table.providerOutcome} in ('resolved', 'rejected', 'retained')`
2369
- ),
2370
- settlementConsistent: check(
2371
- "sandbox_workspace_mutation_admissions_settlement_check",
2372
- sql`(${table.providerOutcome} is null and ${table.settledAt} is null)
2373
- or (${table.providerOutcome} = 'retained' and ${table.settledAt} is null)
2374
- or (${table.providerOutcome} in ('resolved', 'rejected') and ${table.settledAt} is not null)`
2375
- )
2376
- })
2377
- );
2378
- var sandboxRetainedProcessStateValues = ["active", "exited", "lost"];
2379
- var sandboxRetainedProcesses = pgTable(
2380
- "sandbox_retained_processes",
2381
- {
2382
- id: uuid("id").primaryKey().defaultRandom(),
2383
- accountId: uuid("account_id").notNull(),
2384
- workspaceId: uuid("workspace_id").notNull(),
2385
- sessionId: uuid("session_id").notNull(),
2386
- leaseId: uuid("lease_id").notNull(),
2387
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
2388
- parentAdmissionId: uuid("parent_admission_id").notNull(),
2389
- holderId: text("holder_id").notNull(),
2390
- ownerActorKind: text("owner_actor_kind", { enum: ["turn", "direct"] }).notNull(),
2391
- ownerActorId: uuid("owner_actor_id").notNull(),
2392
- ownerTurnId: uuid("owner_turn_id"),
2393
- ownerAttemptId: uuid("owner_attempt_id"),
2394
- ownerExecutionGeneration: integer("owner_execution_generation"),
2395
- leaseEpoch: integer("lease_epoch").notNull(),
2396
- providerBackend: text("provider_backend").notNull(),
2397
- providerInstanceId: text("provider_instance_id").notNull(),
2398
- routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(),
2399
- routeTargetId: uuid("route_target_id"),
2400
- routeEpoch: integer("route_epoch").notNull(),
2401
- providerSessionId: integer("provider_session_id").notNull(),
2402
- state: text("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"),
2403
- exitCode: integer("exit_code"),
2404
- settlementReason: text("settlement_reason"),
2405
- startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(),
2406
- settledAt: timestamp("settled_at", { withTimezone: true })
2407
- },
2408
- (table) => ({
2409
- workspaceAccount: foreignKey({
2410
- name: "sandbox_retained_processes_workspace_account_fk",
2411
- columns: [table.workspaceId, table.accountId],
2412
- foreignColumns: [workspaces.id, workspaces.accountId]
2413
- }).onDelete("cascade"),
2414
- workspaceSession: foreignKey({
2415
- name: "sandbox_retained_processes_workspace_session_fk",
2416
- columns: [table.workspaceId, table.sessionId],
2417
- foreignColumns: [sessions.workspaceId, sessions.id]
2418
- }).onDelete("restrict"),
2419
- parentAdmissionScope: foreignKey({
2420
- name: "sandbox_retained_processes_parent_admission_scope_fk",
2421
- columns: [
2422
- table.accountId,
2423
- table.workspaceId,
2424
- table.sessionId,
2425
- table.leaseId,
2426
- table.parentAdmissionId
2427
- ],
2428
- foreignColumns: [
2429
- sandboxWorkspaceMutationAdmissions.accountId,
2430
- sandboxWorkspaceMutationAdmissions.workspaceId,
2431
- sandboxWorkspaceMutationAdmissions.sessionId,
2432
- sandboxWorkspaceMutationAdmissions.leaseId,
2433
- sandboxWorkspaceMutationAdmissions.id
2434
- ]
2435
- }).onDelete("restrict"),
2436
- scopedId: uniqueIndex("sandbox_retained_processes_scoped_id_uq").on(
2437
- table.accountId,
2438
- table.workspaceId,
2439
- table.sessionId,
2440
- table.leaseId,
2441
- table.id
2442
- ),
2443
- parentAdmission: uniqueIndex("sandbox_retained_processes_parent_admission_uq").on(
2444
- table.parentAdmissionId
2445
- ),
2446
- liveProviderSession: uniqueIndex("sandbox_retained_processes_live_provider_session_uq").on(
2447
- table.leaseId,
2448
- table.leaseEpoch,
2449
- table.providerInstanceId,
2450
- table.routeEpoch,
2451
- table.providerSessionId
2452
- ).where(sql`${table.state} = 'active'`),
2453
- holder: uniqueIndex("sandbox_retained_processes_holder_uq").on(table.leaseId, table.holderId),
2454
- active: index("sandbox_retained_processes_active_idx").on(table.workspaceId, table.sessionId, table.startedAt).where(sql`${table.state} = 'active'`),
2455
- identityValid: check(
2456
- "sandbox_retained_processes_identity_check",
2457
- sql`${table.leaseEpoch} >= 0
2458
- and ${table.routeEpoch} >= 0
2459
- and ${table.providerSessionId} > 0
2460
- and octet_length(${table.holderId}) between 1 and 256
2461
- and octet_length(${table.providerBackend}) between 1 and 64
2462
- and octet_length(${table.providerInstanceId}) between 1 and 512
2463
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
2464
- ),
2465
- ownerValid: check(
2466
- "sandbox_retained_processes_owner_check",
2467
- sql`(
2468
- ${table.ownerActorKind} = 'turn'
2469
- and ${table.ownerActorId} = ${table.ownerAttemptId}
2470
- and ${table.ownerTurnId} is not null
2471
- and ${table.ownerAttemptId} is not null
2472
- and ${table.ownerExecutionGeneration} > 0
2473
- ) or (
2474
- ${table.ownerActorKind} = 'direct'
2475
- and ${table.ownerTurnId} is null
2476
- and ${table.ownerAttemptId} is null
2477
- and ${table.ownerExecutionGeneration} is null
2478
- )`
2479
- ),
2480
- settlementValid: check(
2481
- "sandbox_retained_processes_settlement_check",
2482
- sql`(${table.state} = 'active' and ${table.settledAt} is null and ${table.exitCode} is null)
2483
- or (${table.state} = 'exited' and ${table.settledAt} is not null)
2484
- or (${table.state} = 'lost' and ${table.settledAt} is not null and ${table.exitCode} is null)`
2485
- ),
2486
- reasonValid: check(
2487
- "sandbox_retained_processes_reason_check",
2488
- sql`${table.settlementReason} is null
2489
- or octet_length(${table.settlementReason}) between 1 and 512`
2490
- )
2491
- })
2492
- );
2493
- var sessionRecordingStateValues = [
2494
- "recording",
2495
- "finalizing",
2496
- "available",
2497
- "failed"
2498
- ];
2499
- var sessionRecordingModeValues = ["manual", "on-turn", "on-verify"];
2500
- var sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"];
2501
- var sessionRecordings = pgTable(
2502
- "session_recordings",
2503
- {
2504
- id: uuid("id").primaryKey().defaultRandom(),
2505
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2506
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2507
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2508
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2509
- onDelete: "set null"
2510
- }),
2511
- state: text("state", { enum: sessionRecordingStateValues }).notNull(),
2512
- mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
2513
- codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
2514
- storageKey: text("storage_key"),
2515
- sizeBytes: bigint("size_bytes", { mode: "number" }),
2516
- durationSeconds: numeric("duration_seconds").$type(),
2517
- width: integer("width").notNull(),
2518
- height: integer("height").notNull(),
2519
- reason: text("reason"),
2520
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2521
- finalizedAt: timestamp("finalized_at", { withTimezone: true })
2522
- },
2523
- (table) => ({
2524
- sessionIdx: index("session_recordings_session_idx").on(
2525
- table.workspaceId,
2526
- table.sessionId,
2527
- table.createdAt
2528
- )
2529
- })
2530
- );
2531
- var workspaceCaptures = pgTable(
2532
- "workspace_captures",
2533
- {
2534
- id: uuid("id").primaryKey().defaultRandom(),
2535
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2536
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2537
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2538
- turnId: uuid("turn_id").references(() => sessionTurns.id, {
2539
- onDelete: "set null"
2540
- }),
2541
- revision: bigint("revision", { mode: "number" }).notNull(),
2542
- leaseEpoch: integer("lease_epoch").notNull(),
2543
- // 'available' on a committed capture. 'failed' reserved for a future two-phase
2544
- // write; the current synchronous capture only ever inserts 'available'.
2545
- state: text("state", { enum: ["available", "failed"] }).notNull().default("available"),
2546
- // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload.
2547
- manifestKey: text("manifest_key"),
2548
- // The fs tree index blob, kept separate from the manifest so the API can inline
2549
- // or sign it independently of the (usually small) manifest metadata.
2550
- treeIndexKey: text("tree_index_key"),
2551
- // Content-addressed after-image blob keys this revision references (GC input).
2552
- blobKeys: jsonb("blob_keys").$type().notNull().default([]),
2553
- sizeBytes: bigint("size_bytes", { mode: "number" }),
2554
- stats: jsonb("stats").$type().notNull().default({}),
2555
- capturedAt: timestamp("captured_at", { withTimezone: true }).notNull().defaultNow()
2556
- },
2557
- (table) => ({
2558
- sessionRevision: uniqueIndex("workspace_captures_session_revision_idx").on(
2559
- table.sessionId,
2560
- table.revision
2561
- ),
2562
- latest: index("workspace_captures_latest_idx").on(
2563
- table.workspaceId,
2564
- table.sessionId,
2565
- table.revision
2566
- )
2567
- })
2568
- );
2569
- var sandboxPtySessions = pgTable(
2570
- "sandbox_pty_sessions",
2571
- {
2572
- id: uuid("id").primaryKey().defaultRandom(),
2573
- // == ptyId on the wire
2574
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2575
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2576
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2577
- leaseId: uuid("lease_id"),
2578
- sandboxGroupId: uuid("sandbox_group_id"),
2579
- retainedProcessId: uuid("retained_process_id"),
2580
- openAdmissionId: uuid("open_admission_id"),
2581
- // Copied provider locator for the adopted retained process.
2582
- execSessionId: integer("exec_session_id"),
2583
- leaseEpoch: integer("lease_epoch").notNull(),
2584
- providerBackend: text("provider_backend"),
2585
- providerInstanceId: text("provider_instance_id"),
2586
- routeKind: text("route_kind", { enum: ["home", "active"] }),
2587
- routeTargetId: uuid("route_target_id"),
2588
- routeEpoch: integer("route_epoch"),
2589
- cols: integer("cols").notNull(),
2590
- rows: integer("rows").notNull(),
2591
- shell: text("shell").notNull(),
2592
- cwd: text("cwd").notNull(),
2593
- status: text("status").notNull().default("open"),
2594
- // 'open' | 'closed'
2595
- // The viewer grant/subject that opened it (free-text — access subjects are not
2596
- // always UUIDs, M5; so a text column, never a uuid NOT NULL).
2597
- openedBy: text("opened_by").notNull(),
2598
- lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
2599
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2600
- closedAt: timestamp("closed_at", { withTimezone: true })
2601
- },
2602
- (table) => ({
2603
- retainedProcessScope: foreignKey({
2604
- name: "sandbox_pty_sessions_retained_process_scope_fk",
2605
- columns: [
2606
- table.accountId,
2607
- table.workspaceId,
2608
- table.sessionId,
2609
- table.leaseId,
2610
- table.retainedProcessId
2611
- ],
2612
- foreignColumns: [
2613
- sandboxRetainedProcesses.accountId,
2614
- sandboxRetainedProcesses.workspaceId,
2615
- sandboxRetainedProcesses.sessionId,
2616
- sandboxRetainedProcesses.leaseId,
2617
- sandboxRetainedProcesses.id
2618
- ]
2619
- }).onDelete("restrict"),
2620
- openIdx: index("sandbox_pty_sessions_session_idx").on(table.workspaceId, table.sessionId).where(sql`${table.status} = 'open'`),
2621
- processIdx: uniqueIndex("sandbox_pty_sessions_open_process_uq").on(table.retainedProcessId).where(sql`${table.status} = 'open'`),
2622
- openIdentityValid: check(
2623
- "sandbox_pty_sessions_open_identity_check",
2624
- sql`${table.status} <> 'open' or (
2625
- ${table.leaseId} is not null
2626
- and ${table.sandboxGroupId} is not null
2627
- and ${table.retainedProcessId} is not null
2628
- and ${table.openAdmissionId} is not null
2629
- and ${table.execSessionId} > 0
2630
- and octet_length(${table.providerBackend}) between 1 and 64
2631
- and octet_length(${table.providerInstanceId}) between 1 and 512
2632
- and ${table.routeKind} in ('home', 'active')
2633
- and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)
2634
- and ${table.routeEpoch} is not null
2635
- and ${table.leaseEpoch} >= 0
2636
- and ${table.routeEpoch} >= 0
2637
- )`
2638
- )
2639
- })
2640
- );
2641
- var enrollmentExposureValues = ["whole-machine"];
2642
- var enrollmentStatusValues = ["active", "revoked"];
2643
- var enrollmentOsValues = ["linux", "macos", "windows"];
2644
- var sandboxKindValues = ["modal", "selfhosted"];
2645
- var enrollments = pgTable(
2646
- "enrollments",
2647
- {
2648
- id: uuid("id").primaryKey().defaultRandom(),
2649
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2650
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2651
- // The agent's ed25519 public key (the machine identity).
2652
- pubkey: text("pubkey").notNull(),
2653
- exposure: text("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
2654
- hasDisplay: boolean("has_display").notNull().default(false),
2655
- // Refreshed from every connect Hello (Capabilities.op_stream); false for
2656
- // agents predating the op-stream engine.
2657
- opStream: boolean("op_stream").notNull().default(false),
2658
- // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
2659
- // not granted), the agent reports has_display=false AND a human, actionable reason
2660
- // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
2661
- // permitted (has_display=true) or the machine is genuinely headless — the reason
2662
- // distinguishes "display present but capture not granted" from plain "no display"
2663
- // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
2664
- // from every connect Hello alongside has_display.
2665
- desktopUnavailableReason: text("desktop_unavailable_reason"),
2666
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
2667
- status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
2668
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
2669
- arch: text("arch").notNull().default("x86_64"),
2670
- // Heartbeat liveness cursor. Null until the first connect.
2671
- lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
2672
- // Clean going-offline marker (migration 0049). Set when the machine announces a
2673
- // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness
2674
- // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a
2675
- // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a
2676
- // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL
2677
- // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior.
2678
- wentOfflineAt: timestamp("went_offline_at", { withTimezone: true }),
2679
- wentOfflineReason: text("went_offline_reason"),
2680
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2681
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
2682
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2683
- },
2684
- (table) => ({
2685
- // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
2686
- workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(
2687
- table.workspaceId,
2688
- table.pubkey
2689
- ),
2690
- // List a workspace's ACTIVE machines without scanning revoked rows.
2691
- workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
2692
- })
2693
- );
2694
- var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
2695
- var deviceEnrollmentRequests = pgTable(
2696
- "device_enrollment_requests",
2697
- {
2698
- id: uuid("id").primaryKey().defaultRandom(),
2699
- // The opaque code the agent polls with (unguessable, single-use). Unique.
2700
- deviceCode: text("device_code").notNull(),
2701
- // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
2702
- // rows via a partial unique index so a recycled code never collides with a
2703
- // terminal row.
2704
- userCode: text("user_code").notNull(),
2705
- // The workspace this request was started for (resolved from the deployment-edge
2706
- // request context — the agent presents the access key, the flow binds to the
2707
- // single managed workspace OR a workspace hint). account_id rides along for RLS.
2708
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2709
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2710
- // The agent's ed25519 public key (the machine identity the enrollment binds to).
2711
- pubkey: text("pubkey").notNull(),
2712
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
2713
- arch: text("arch").notNull().default("x86_64"),
2714
- machineName: text("machine_name"),
2715
- // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
2716
- // approve). Mirrors the enrollment column domain.
2717
- requestedExposure: text("requested_exposure", {
2718
- enum: enrollmentExposureValues
2719
- }).notNull().default("whole-machine"),
2720
- // The agent CAN offer a display (a real screen / Xvfb is available) — gates
2721
- // whether screen-control consent is even meaningful. has_display on the
2722
- // resulting enrollment is derived from this.
2723
- canOfferDisplay: boolean("can_offer_display").notNull().default(false),
2724
- // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
2725
- // at approve is the AUTHORITATIVE consent; this is only the agent's request.
2726
- requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
2727
- status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
2728
- // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
2729
- approvedBySubjectId: text("approved_by_subject_id"),
2730
- approvedBySubjectLabel: text("approved_by_subject_label"),
2731
- // The user's screen-control consent decision (whole-machine is mandatory at
2732
- // approve; screen-control is opt-in per this flag).
2733
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
2734
- approvedAt: timestamp("approved_at", { withTimezone: true }),
2735
- // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
2736
- // row AND a sandbox row appear). Null until approved.
2737
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, {
2738
- onDelete: "set null"
2739
- }),
2740
- sandboxId: uuid("sandbox_id").references(() => sandboxes.id, {
2741
- onDelete: "set null"
2742
- }),
2743
- // The short-TTL expiry; a pending row past this is EXPIRED on poll.
2744
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
2745
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2746
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2747
- },
2748
- (table) => ({
2749
- // The device_code is the agent's poll key — globally unique + indexed.
2750
- deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
2751
- // The user_code must be unique among LIVE (pending) rows so the approve lookup
2752
- // is unambiguous; a terminal row's code may be recycled.
2753
- userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx").on(table.userCode).where(sql`${table.status} = 'pending'`),
2754
- workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(
2755
- table.workspaceId,
2756
- table.createdAt
2757
- ),
2758
- expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt)
2759
- })
2760
- );
2761
- var sandboxes = pgTable(
2762
- "sandboxes",
2763
- {
2764
- id: uuid("id").primaryKey().defaultRandom(),
2765
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2766
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2767
- kind: text("kind", { enum: sandboxKindValues }).notNull(),
2768
- name: text("name").notNull(),
2769
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, {
2770
- onDelete: "set null"
2771
- }),
2772
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2773
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2774
- },
2775
- (table) => ({
2776
- workspaceCreated: index("sandboxes_workspace_created_idx").on(
2777
- table.workspaceId,
2778
- table.createdAt
2779
- ),
2780
- enrollment: index("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql`${table.enrollmentId} is not null`)
2781
- })
2782
- );
2783
- var machineMetricsLatest = pgTable(
2784
- "machine_metrics_latest",
2785
- {
2786
- enrollmentId: uuid("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
2787
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2788
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2789
- cpuPercent: numeric("cpu_percent").$type(),
2790
- load1: numeric("load1").$type(),
2791
- load5: numeric("load5").$type(),
2792
- load15: numeric("load15").$type(),
2793
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2794
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2795
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2796
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2797
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
2798
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2799
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2800
- contention: numeric("contention").$type(),
2801
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2802
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2803
- },
2804
- (table) => ({
2805
- workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId)
2806
- })
2807
- );
2808
- var machineMetricsSeries = pgTable(
2809
- "machine_metrics_series",
2810
- {
2811
- id: uuid("id").primaryKey().defaultRandom(),
2812
- enrollmentId: uuid("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
2813
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2814
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2815
- cpuPercent: numeric("cpu_percent").$type(),
2816
- load1: numeric("load1").$type(),
2817
- load5: numeric("load5").$type(),
2818
- load15: numeric("load15").$type(),
2819
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2820
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2821
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2822
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2823
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
2824
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2825
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2826
- contention: numeric("contention").$type(),
2827
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2828
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2829
- },
2830
- (table) => ({
2831
- enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(
2832
- table.enrollmentId,
2833
- table.sampledAt
2834
- ),
2835
- sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt)
2836
- })
2837
- );
2838
- var scheduledTasks = pgTable(
2839
- "scheduled_tasks",
2840
- {
2841
- id: uuid("id").primaryKey().defaultRandom(),
2842
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2843
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2844
- name: text("name").notNull(),
2845
- status: text("status").notNull().default("active"),
2846
- schedule: jsonb("schedule").$type().notNull(),
2847
- temporalScheduleId: text("temporal_schedule_id").notNull(),
2848
- runMode: text("run_mode").notNull().default("new_session_per_run"),
2849
- overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
2850
- agentConfig: jsonb("agent_config").$type().notNull(),
2851
- reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, {
2852
- onDelete: "set null"
2853
- }),
2854
- variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
2855
- onDelete: "restrict"
2856
- }),
2857
- // The rig this task's runs ride; the active version is resolved per fire
2858
- // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
2859
- // in migration 0047 (forward-reference pattern). Consumed in M3.
2860
- rigId: uuid("rig_id"),
2861
- metadata: jsonb("metadata").$type().notNull().default({}),
2862
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2863
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2864
- },
2865
- (table) => ({
2866
- temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(
2867
- table.workspaceId,
2868
- table.temporalScheduleId
2869
- ),
2870
- status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
2871
- variableSet: index("scheduled_tasks_variable_set_idx").on(
2872
- table.workspaceId,
2873
- table.variableSetId
2874
- )
2875
- })
2876
- );
2877
- var scheduledTaskRuns = pgTable(
2878
- "scheduled_task_runs",
2879
- {
2880
- id: uuid("id").primaryKey().defaultRandom(),
2881
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2882
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2883
- taskId: uuid("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
2884
- status: text("status").notNull().default("queued"),
2885
- triggerType: text("trigger_type").notNull(),
2886
- scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
2887
- firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
2888
- sessionId: uuid("session_id").references(() => sessions.id, {
2889
- onDelete: "set null"
2890
- }),
2891
- triggerEventId: uuid("trigger_event_id"),
2892
- // Stable Temporal producer identity. Activity replay/re-dispatch returns
2893
- // the exact run instead of allocating a second schedule source row.
2894
- producerKey: text("producer_key"),
2895
- error: text("error"),
2896
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2897
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2898
- },
2899
- (table) => ({
2900
- taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(
2901
- table.workspaceId,
2902
- table.taskId,
2903
- table.createdAt
2904
- ),
2905
- session: index("scheduled_task_runs_workspace_session_idx").on(
2906
- table.workspaceId,
2907
- table.sessionId
2908
- ),
2909
- producer: uniqueIndex("scheduled_task_runs_producer_key_uq").on(table.workspaceId, table.producerKey).where(sql`${table.producerKey} is not null`)
2910
- })
2911
- );
2912
- var githubInstallations = pgTable(
2913
- "github_installations",
2914
- {
2915
- id: uuid("id").primaryKey().defaultRandom(),
2916
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2917
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2918
- installationId: integer("installation_id").notNull(),
2919
- accountLogin: text("account_login"),
2920
- accountType: text("account_type"),
2921
- repositoryScope: text("repository_scope").notNull().default("all"),
2922
- linkedBySubjectId: text("linked_by_subject_id"),
2923
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2924
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
2925
- },
2926
- (table) => ({
2927
- workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(
2928
- table.workspaceId,
2929
- table.installationId
2930
- ),
2931
- installation: index("github_installations_installation_idx").on(table.installationId),
2932
- workspace: index("github_installations_workspace_idx").on(table.workspaceId),
2933
- repositoryScopeCheck: check(
2934
- "github_installations_repository_scope_check",
2935
- sql`${table.repositoryScope} in ('all', 'selected')`
2936
- )
2937
- })
2938
- );
2939
- var githubInstallationRepositories = pgTable(
2940
- "github_installation_repositories",
2941
- {
2942
- id: uuid("id").primaryKey().defaultRandom(),
2943
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2944
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2945
- installationId: integer("installation_id").notNull(),
2946
- repositoryId: bigint("repository_id", { mode: "number" }).notNull(),
2947
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
2948
- },
2949
- (table) => ({
2950
- installationRepository: uniqueIndex("github_install_repo_workspace_installation_repo_idx").on(
2951
- table.workspaceId,
2952
- table.installationId,
2953
- table.repositoryId
2954
- ),
2955
- workspaceInstallation: index("github_install_repo_workspace_installation_idx").on(
2956
- table.workspaceId,
2957
- table.installationId
2958
- ),
2959
- workspaceAccount: foreignKey({
2960
- columns: [table.workspaceId, table.accountId],
2961
- foreignColumns: [workspaces.id, workspaces.accountId],
2962
- name: "github_installation_repositories_workspace_account_fk"
2963
- }).onDelete("cascade"),
2964
- installationBinding: foreignKey({
2965
- columns: [table.workspaceId, table.installationId],
2966
- foreignColumns: [githubInstallations.workspaceId, githubInstallations.installationId],
2967
- name: "github_installation_repositories_installation_fk"
2968
- }).onDelete("cascade")
2969
- })
2970
- );
2971
- var usageEvents = pgTable(
2972
- "usage_events",
2973
- {
2974
- id: uuid("id").primaryKey().defaultRandom(),
2975
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2976
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2977
- subjectId: text("subject_id"),
2978
- eventType: text("event_type").notNull(),
2979
- quantity: bigint("quantity", { mode: "number" }).notNull(),
2980
- unit: text("unit").notNull(),
2981
- sourceResourceType: text("source_resource_type"),
2982
- sourceResourceId: text("source_resource_id"),
2983
- // Exact execution source for host usage export. These are deliberately
2984
- // validated soft references rather than cascading foreign keys: usage is
2985
- // an immutable billing/audit fact and must retain its source identity after
2986
- // a session or turn is deleted.
2987
- sessionId: uuid("session_id"),
2988
- turnId: uuid("turn_id"),
2989
- turnAttemptId: uuid("turn_attempt_id"),
2990
- initiatorKind: text("initiator_kind"),
2991
- initiatorSubjectId: text("initiator_subject_id"),
2992
- initiatorContext: jsonb("initiator_context").$type().notNull().default({}),
2993
- origin: text("origin"),
2994
- idempotencyKey: text("idempotency_key").notNull(),
2995
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
2996
- recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
2997
- exportedToBillingAt: timestamp("exported_to_billing_at", {
2998
- withTimezone: true
2999
- }),
3000
- billingProviderEventId: text("billing_provider_event_id")
3001
- },
3002
- (table) => ({
3003
- idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
3004
- workspaceMetric: index("usage_events_workspace_metric_idx").on(
3005
- table.workspaceId,
3006
- table.eventType,
3007
- table.occurredAt
3008
- ),
3009
- accountMetric: index("usage_events_account_metric_idx").on(
3010
- table.accountId,
3011
- table.eventType,
3012
- table.occurredAt
3013
- ),
3014
- workspaceSession: index("usage_events_workspace_session_idx").on(
3015
- table.workspaceId,
3016
- table.sessionId,
3017
- table.occurredAt
3018
- ),
3019
- contextHierarchy: check(
3020
- "usage_events_context_hierarchy_check",
3021
- sql`(${table.turnId} is null or ${table.sessionId} is not null)
3022
- and (${table.turnAttemptId} is null or ${table.turnId} is not null)`
3023
- ),
3024
- initiatorConsistent: check(
3025
- "usage_events_initiator_check",
3026
- sql`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null)
3027
- or (${table.initiatorKind} in ('subject', 'service')
3028
- and ${table.initiatorSubjectId} is not null
3029
- and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`
3030
- ),
3031
- attributionContextBytes: check(
3032
- "usage_events_initiator_context_bytes_check",
3033
- sql`octet_length(${table.initiatorContext}::text) <= 4096`
3034
- ),
3035
- originValid: check(
3036
- "usage_events_origin_check",
3037
- sql`${table.origin} is null or ${table.origin} in (
3038
- 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
3039
- )`
3040
- )
3041
- })
3042
- );
3043
- var hostExportConfig = pgTable(
3044
- "host_export_config",
3045
- {
3046
- id: integer("id").primaryKey().default(1),
3047
- sessionEventsEnabled: boolean("session_events_enabled").notNull().default(false),
3048
- usageEventsEnabled: boolean("usage_events_enabled").notNull().default(false),
3049
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3050
- },
3051
- (table) => ({
3052
- singleton: check("host_export_config_singleton_check", sql`${table.id} = 1`)
3053
- })
3054
- );
3055
- var hostExportOutbox = pgTable(
3056
- "host_export_outbox",
3057
- {
3058
- id: uuid("id").primaryKey().defaultRandom(),
3059
- exportKind: text("export_kind").notNull(),
3060
- exportCursor: bigint("export_cursor", { mode: "bigint" }),
3061
- sourceId: uuid("source_id").notNull(),
3062
- accountId: uuid("account_id").notNull(),
3063
- workspaceId: uuid("workspace_id").notNull(),
3064
- sessionId: uuid("session_id"),
3065
- rootSessionId: uuid("root_session_id"),
3066
- turnId: uuid("turn_id"),
3067
- turnGeneration: integer("turn_generation"),
3068
- turnAttemptId: uuid("turn_attempt_id"),
3069
- sessionSequence: integer("session_sequence"),
3070
- clientEventId: text("client_event_id"),
3071
- turnAssociation: text("turn_association"),
3072
- duplicateOfEventId: uuid("duplicate_of_event_id"),
3073
- duplicateReason: text("duplicate_reason"),
3074
- eventType: text("event_type").notNull(),
3075
- idempotencyKey: text("idempotency_key").notNull(),
3076
- initiator: jsonb("initiator").$type(),
3077
- initiatorContext: jsonb("initiator_context").$type().notNull().default({}),
3078
- origin: text("origin"),
3079
- payload: jsonb("payload").$type().notNull(),
3080
- envelopeBytes: integer("envelope_bytes").notNull(),
3081
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
3082
- sourceRecordedAt: timestamp("source_recorded_at", { withTimezone: true }).notNull(),
3083
- enqueuedAt: timestamp("enqueued_at", { withTimezone: true }).notNull()
3084
- },
3085
- (table) => ({
3086
- kindValid: check(
3087
- "host_export_outbox_kind_check",
3088
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3089
- ),
3090
- rootSessionCaptured: check(
3091
- "host_export_outbox_root_session_check",
3092
- sql`${table.sessionId} is null or ${table.rootSessionId} is not null`
3093
- ),
3094
- sourceUnique: uniqueIndex("host_export_outbox_source_uq").on(table.exportKind, table.sourceId),
3095
- cursorUnique: uniqueIndex("host_export_outbox_cursor_uq").on(table.exportKind, table.exportCursor).where(sql`${table.exportCursor} is not null`),
3096
- unassigned: index("host_export_outbox_unassigned_idx").on(table.exportKind, table.enqueuedAt, table.id).where(sql`${table.exportCursor} is null`),
3097
- 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`),
3098
- contextBytes: check(
3099
- "host_export_outbox_context_bytes_check",
3100
- sql`octet_length(${table.initiatorContext}::text) <= 4096`
3101
- ),
3102
- originValid: check(
3103
- "host_export_outbox_origin_check",
3104
- sql`${table.origin} is null or ${table.origin} in (
3105
- 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
3106
- )`
3107
- )
3108
- })
3109
- );
3110
- var hostExportCursorState = pgTable(
3111
- "host_export_cursor_state",
3112
- {
3113
- exportKind: text("export_kind").primaryKey(),
3114
- nextCursor: bigint("next_cursor", { mode: "bigint" }).notNull().default(1n),
3115
- prunedThrough: bigint("pruned_through", { mode: "bigint" }).notNull().default(0n),
3116
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3117
- },
3118
- (table) => ({
3119
- kindValid: check(
3120
- "host_export_cursor_state_kind_check",
3121
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3122
- ),
3123
- cursorValid: check(
3124
- "host_export_cursor_state_next_check",
3125
- sql`${table.nextCursor} > 0 and ${table.prunedThrough} >= 0
3126
- and ${table.prunedThrough} < ${table.nextCursor}`
3127
- )
3128
- })
3129
- );
3130
- var hostExportConsumers = pgTable(
3131
- "host_export_consumers",
3132
- {
3133
- id: uuid("id").primaryKey().defaultRandom(),
3134
- consumerId: text("consumer_id").notNull(),
3135
- exportKind: text("export_kind").notNull(),
3136
- checkpoint: bigint("checkpoint", { mode: "bigint" }).notNull().default(0n),
3137
- enabled: boolean("enabled").notNull().default(true),
3138
- leaseToken: uuid("lease_token"),
3139
- leaseHolderId: text("lease_holder_id"),
3140
- leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
3141
- leaseFrom: bigint("lease_from", { mode: "bigint" }),
3142
- leaseThrough: bigint("lease_through", { mode: "bigint" }),
3143
- consecutiveFailures: integer("consecutive_failures").notNull().default(0),
3144
- nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
3145
- lastError: text("last_error"),
3146
- lastErrorAt: timestamp("last_error_at", { withTimezone: true }),
3147
- blockedAt: timestamp("blocked_at", { withTimezone: true }),
3148
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3149
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3150
- },
3151
- (table) => ({
3152
- consumerKind: uniqueIndex("host_export_consumers_kind_id_uq").on(
3153
- table.exportKind,
3154
- table.consumerId
3155
- ),
3156
- kindValid: check(
3157
- "host_export_consumers_kind_check",
3158
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3159
- ),
3160
- checkpointValid: check("host_export_consumers_checkpoint_check", sql`${table.checkpoint} >= 0`),
3161
- due: index("host_export_consumers_due_idx").on(
3162
- table.enabled,
3163
- table.blockedAt,
3164
- table.nextAttemptAt
3165
- )
3166
- })
3167
- );
3168
- var hostExportDeadLetters = pgTable(
3169
- "host_export_dead_letters",
3170
- {
3171
- id: uuid("id").primaryKey().defaultRandom(),
3172
- consumerId: text("consumer_id").notNull(),
3173
- exportKind: text("export_kind").notNull(),
3174
- exportCursor: bigint("export_cursor", { mode: "bigint" }).notNull(),
3175
- sourceId: uuid("source_id").notNull(),
3176
- reason: text("reason").notNull(),
3177
- envelope: jsonb("envelope").$type().notNull(),
3178
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3179
- },
3180
- (table) => ({
3181
- consumerCursor: uniqueIndex("host_export_dead_letters_consumer_cursor_uq").on(
3182
- table.exportKind,
3183
- table.consumerId,
3184
- table.exportCursor
3185
- ),
3186
- kindValid: check(
3187
- "host_export_dead_letters_kind_check",
3188
- sql`${table.exportKind} in ('session_event', 'usage_event')`
3189
- ),
3190
- reasonValid: check(
3191
- "host_export_dead_letters_reason_check",
3192
- sql`length(${table.reason}) between 1 and 500`
3193
- ),
3194
- envelopeBytes: check(
3195
- "host_export_dead_letters_envelope_bytes_check",
3196
- sql`pg_column_size(${table.envelope}) <= 114688`
3197
- )
3198
- })
3199
- );
3200
- var creditLedgerEntries = pgTable(
3201
- "credit_ledger_entries",
3202
- {
3203
- id: uuid("id").primaryKey().defaultRandom(),
3204
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3205
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3206
- onDelete: "set null"
3207
- }),
3208
- type: text("type").notNull(),
3209
- amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
3210
- currency: text("currency").notNull().default("usd"),
3211
- sourceType: text("source_type"),
3212
- sourceId: text("source_id"),
3213
- idempotencyKey: text("idempotency_key").notNull(),
3214
- metadata: jsonb("metadata").$type().notNull().default({}),
3215
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
3216
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3217
- },
3218
- (table) => ({
3219
- idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
3220
- accountCreated: index("credit_ledger_entries_account_created_idx").on(
3221
- table.accountId,
3222
- table.createdAt
3223
- )
3224
- })
3225
- );
3226
- var billingCustomers = pgTable(
3227
- "billing_customers",
3228
- {
3229
- id: uuid("id").primaryKey().defaultRandom(),
3230
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3231
- provider: text("provider").notNull().default("stripe"),
3232
- providerCustomerId: text("provider_customer_id").notNull(),
3233
- email: text("email"),
3234
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3235
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3236
- },
3237
- (table) => ({
3238
- accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(
3239
- table.accountId,
3240
- table.provider
3241
- ),
3242
- providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(
3243
- table.provider,
3244
- table.providerCustomerId
3245
- )
3246
- })
3247
- );
3248
- var stripeWebhookEvents = pgTable("stripe_webhook_events", {
3249
- id: text("id").primaryKey(),
3250
- type: text("type").notNull(),
3251
- livemode: text("livemode").notNull().default("false"),
3252
- payload: jsonb("payload").$type().notNull(),
3253
- processedAt: timestamp("processed_at", { withTimezone: true }),
3254
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3255
- });
3256
- var auditEvents = pgTable(
3257
- "audit_events",
3258
- {
3259
- id: uuid("id").primaryKey().defaultRandom(),
3260
- accountId: uuid("account_id").references(() => managedAccounts.id, {
3261
- onDelete: "set null"
3262
- }),
3263
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3264
- onDelete: "set null"
3265
- }),
3266
- subjectId: text("subject_id"),
3267
- action: text("action").notNull(),
3268
- targetType: text("target_type"),
3269
- targetId: text("target_id"),
3270
- metadata: jsonb("metadata").$type().notNull().default({}),
3271
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
3272
- },
3273
- (table) => ({
3274
- accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
3275
- workspaceCreated: index("audit_events_workspace_created_idx").on(
3276
- table.workspaceId,
3277
- table.occurredAt
3278
- )
3279
- })
3280
- );
3281
- var packInstallations = pgTable(
3282
- "pack_installations",
3283
- {
3284
- id: uuid("id").primaryKey().defaultRandom(),
3285
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3286
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3287
- packId: text("pack_id").notNull(),
3288
- status: text("status").notNull().default("active"),
3289
- metadata: jsonb("metadata").$type().notNull().default({}),
3290
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
3291
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3292
- },
3293
- (table) => ({
3294
- workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(
3295
- table.workspaceId,
3296
- table.packId
3297
- ),
3298
- status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status)
3299
- })
3300
- );
3301
- var workspacePacks = pgTable(
3302
- "workspace_packs",
3303
- {
3304
- id: uuid("id").primaryKey().defaultRandom(),
3305
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3306
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3307
- packId: text("pack_id").notNull(),
3308
- manifest: jsonb("manifest").$type().notNull(),
3309
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3310
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3311
- },
3312
- (table) => ({
3313
- workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(
3314
- table.workspaceId,
3315
- table.packId
3316
- )
3317
- })
3318
- );
3319
- var importBatches = pgTable(
3320
- "import_batches",
3321
- {
3322
- id: uuid("id").primaryKey().defaultRandom(),
3323
- source: text("source").notNull(),
3324
- snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
3325
- snapshotRef: text("snapshot_ref"),
3326
- attributionNote: text("attribution_note").notNull(),
3327
- importedCount: integer("imported_count").notNull().default(0),
3328
- skippedCount: integer("skipped_count").notNull().default(0),
3329
- quarantinedCount: integer("quarantined_count").notNull().default(0),
3330
- logoFailureCount: integer("logo_failure_count").notNull().default(0),
3331
- staleCount: integer("stale_count").notNull().default(0),
3332
- details: jsonb("details").$type().notNull().default({}),
3333
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3334
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3335
- },
3336
- (table) => ({
3337
- sourceSnapshot: index("import_batches_source_snapshot_idx").on(
3338
- table.source,
3339
- table.snapshotDate
3340
- ),
3341
- createdAt: index("import_batches_created_at_idx").on(table.createdAt)
3342
- })
3343
- );
3344
- var capabilityCatalogItems = pgTable(
3345
- "capability_catalog_items",
3346
- {
3347
- id: text("id").notNull(),
3348
- accountId: uuid("account_id").references(() => managedAccounts.id, {
3349
- onDelete: "cascade"
3350
- }),
3351
- workspaceId: uuid("workspace_id").references(() => workspaces.id, {
3352
- onDelete: "cascade"
3353
- }),
3354
- kind: text("kind").notNull(),
3355
- source: text("source").notNull().default("manual"),
3356
- name: text("name").notNull(),
3357
- description: text("description"),
3358
- category: text("category").notNull().default("custom"),
3359
- tags: jsonb("tags").$type().notNull().default([]),
3360
- homepageUrl: text("homepage_url"),
3361
- endpointUrl: text("endpoint_url"),
3362
- installUrl: text("install_url"),
3363
- authModel: text("auth_model"),
3364
- providerDomain: text("provider_domain"),
3365
- surfaceType: text("surface_type"),
3366
- transport: text("transport"),
3367
- mcpUrl: text("mcp_url"),
3368
- authKind: text("auth_kind"),
3369
- credentialFacts: jsonb("credential_facts").$type().notNull().default([]),
3370
- tier: text("tier"),
3371
- provenance: text("provenance"),
3372
- logoAssetPath: text("logo_asset_path"),
3373
- importBatchId: uuid("import_batch_id").references(() => importBatches.id, {
3374
- onDelete: "set null"
3375
- }),
3376
- stale: boolean("stale").notNull().default(false),
3377
- staleAt: timestamp("stale_at", { withTimezone: true }),
3378
- metadata: jsonb("metadata").$type().notNull().default({}),
3379
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3380
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3381
- },
3382
- (table) => ({
3383
- workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(
3384
- table.workspaceId,
3385
- table.id
3386
- ),
3387
- registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(
3388
- table.source,
3389
- table.providerDomain,
3390
- table.mcpUrl
3391
- ),
3392
- globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx").on(table.id).where(sql`${table.workspaceId} is null`),
3393
- kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
3394
- category: index("capability_catalog_items_workspace_category_idx").on(
3395
- table.workspaceId,
3396
- table.category
3397
- ),
3398
- source: index("capability_catalog_items_workspace_source_idx").on(
3399
- table.workspaceId,
3400
- table.source
3401
- ),
3402
- providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
3403
- importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
3404
- stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale)
3405
- })
3406
- );
3407
- var capabilityInstallations = pgTable(
3408
- "capability_installations",
3409
- {
3410
- id: uuid("id").primaryKey().defaultRandom(),
3411
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3412
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3413
- capabilityId: text("capability_id").notNull(),
3414
- kind: text("kind").notNull(),
3415
- status: text("status").notNull().default("active"),
3416
- config: jsonb("config").$type().notNull().default({}),
3417
- metadata: jsonb("metadata").$type().notNull().default({}),
3418
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
3419
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3420
- },
3421
- (table) => ({
3422
- workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(
3423
- table.workspaceId,
3424
- table.capabilityId
3425
- ),
3426
- kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
3427
- status: index("capability_installations_workspace_status_idx").on(
3428
- table.workspaceId,
3429
- table.status
3430
- )
3431
- })
3432
- );
3433
- var socialConnections = pgTable(
3434
- "social_connections",
3435
- {
3436
- id: uuid("id").primaryKey().defaultRandom(),
3437
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3438
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3439
- provider: text("provider").notNull(),
3440
- accountHandle: text("account_handle").notNull(),
3441
- accountName: text("account_name"),
3442
- externalAccountId: text("external_account_id"),
3443
- status: text("status").notNull().default("connected"),
3444
- scopes: jsonb("scopes").$type().notNull().default([]),
3445
- credentialRef: text("credential_ref"),
3446
- tokenMetadata: jsonb("token_metadata").$type().notNull().default({}),
3447
- metadata: jsonb("metadata").$type().notNull().default({}),
3448
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3449
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3450
- },
3451
- (table) => ({
3452
- workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(
3453
- table.workspaceId,
3454
- table.provider,
3455
- table.accountHandle
3456
- ),
3457
- providerStatus: index("social_connections_workspace_provider_status_idx").on(
3458
- table.workspaceId,
3459
- table.provider,
3460
- table.status
3461
- )
3462
- })
3463
- );
3464
- var socialPosts = pgTable(
3465
- "social_posts",
3466
- {
3467
- id: uuid("id").primaryKey().defaultRandom(),
3468
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3469
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3470
- connectionId: uuid("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
3471
- provider: text("provider").notNull(),
3472
- externalPostId: text("external_post_id"),
3473
- url: text("url"),
3474
- authorHandle: text("author_handle"),
3475
- text: text("text").notNull(),
3476
- publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
3477
- metrics: jsonb("metrics").$type().notNull().default({}),
3478
- raw: jsonb("raw").$type().notNull().default({}),
3479
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3480
- },
3481
- (table) => ({
3482
- connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(
3483
- table.workspaceId,
3484
- table.connectionId,
3485
- table.externalPostId
3486
- ),
3487
- connectionPublished: index("social_posts_workspace_connection_published_idx").on(
3488
- table.workspaceId,
3489
- table.connectionId,
3490
- table.publishedAt
3491
- ),
3492
- providerPublished: index("social_posts_workspace_provider_published_idx").on(
3493
- table.workspaceId,
3494
- table.provider,
3495
- table.publishedAt
3496
- )
3497
- })
3498
- );
3499
- var rigs = pgTable(
3500
- "rigs",
3501
- {
3502
- id: uuid("id").primaryKey().defaultRandom(),
3503
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3504
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3505
- name: text("name").notNull(),
3506
- description: text("description"),
3507
- // Attribution string: 'user:<subject>' | 'session:<id>' | 'system'.
3508
- createdBy: text("created_by"),
3509
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3510
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3511
- },
3512
- (table) => ({
3513
- workspaceName: uniqueIndex("rigs_workspace_name_idx").on(table.workspaceId, table.name),
3514
- workspaceCreated: index("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt)
3515
- })
3516
- );
3517
- var rigVersions = pgTable(
3518
- "rig_versions",
3519
- {
3520
- id: uuid("id").primaryKey().defaultRandom(),
3521
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3522
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3523
- rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
3524
- version: integer("version").notNull(),
3525
- image: text("image"),
3526
- setupScript: text("setup_script"),
3527
- // Self-declared health checks: [{ name, command }].
3528
- checks: jsonb("checks").$type().notNull().default([]),
3529
- // Registered credential-hook names (resolved to hook implementations in M3).
3530
- credentialHooks: jsonb("credential_hooks").$type().notNull().default([]),
3531
- // Variable-set ids layered below the session's variable set at run time (M3).
3532
- defaultVariableSetIds: jsonb("default_variable_set_ids").$type().notNull().default([]),
3533
- changelog: text("changelog"),
3534
- createdBy: text("created_by"),
3535
- active: boolean("active").notNull().default(false),
3536
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
3537
- },
3538
- (table) => ({
3539
- rigVersion: uniqueIndex("rig_versions_rig_version_idx").on(table.rigId, table.version),
3540
- // At most one active version per rig — the single-active invariant, in the DB.
3541
- rigActive: uniqueIndex("rig_versions_rig_active_idx").on(table.rigId).where(sql`${table.active}`),
3542
- workspaceRig: index("rig_versions_workspace_rig_idx").on(
3543
- table.workspaceId,
3544
- table.rigId,
3545
- table.version
3546
- )
3547
- })
3548
- );
3549
- var rigChanges = pgTable(
3550
- "rig_changes",
3551
- {
3552
- id: uuid("id").primaryKey().defaultRandom(),
3553
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3554
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3555
- rigId: uuid("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
3556
- baseVersionId: uuid("base_version_id").references(() => rigVersions.id, {
3557
- onDelete: "set null"
3558
- }),
3559
- // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
3560
- kind: text("kind").notNull(),
3561
- payload: jsonb("payload").$type().notNull(),
3562
- // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
3563
- status: text("status").notNull().default("proposed"),
3564
- proposedBy: text("proposed_by"),
3565
- verification: jsonb("verification").$type(),
3566
- resultVersionId: uuid("result_version_id").references(() => rigVersions.id, {
3567
- onDelete: "set null"
3568
- }),
3569
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
3570
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
3571
- },
3572
- (table) => ({
3573
- workspaceRig: index("rig_changes_workspace_rig_idx").on(
3574
- table.workspaceId,
3575
- table.rigId,
3576
- table.createdAt
3577
- ),
3578
- workspaceStatus: index("rig_changes_workspace_status_idx").on(table.workspaceId, table.status)
3579
- })
3580
- );
3581
-
3582
- export {
3583
- managedAccounts,
3584
- workspaces,
3585
- nestedAgentDepthConfiguration,
3586
- workspaceInferenceControls,
3587
- workspaceSessionActivityRevisions,
3588
- workspaceMemberships,
3589
- apiKeys,
3590
- workspaceVariableSets,
3591
- workspaceVariableSetVariables,
3592
- codexSubscriptionCredentials,
3593
- codexResetRedemptionAttempts,
3594
- connections,
3595
- integrationOauthClients,
3596
- integrationOauthStateNonces,
3597
- codexRotationSettings,
3598
- workspaceModelPolicies,
3599
- codexCredentialLeases,
3600
- sessions,
3601
- sessionSpawnDenials,
3602
- sessionPins,
3603
- sessionListSnapshots,
3604
- sessionMcpServers,
3605
- files,
3606
- fileUploads,
3607
- documentBases,
3608
- documents,
3609
- documentChunks,
3610
- knowledgeMemories,
3611
- sessionTurns,
3612
- sessionTurnAttempts,
3613
- sessionCommandReceipts,
3614
- workspaceControlEvents,
3615
- sessionAttemptInterruptions,
3616
- composerDrafts,
3617
- newSessionDrafts,
3618
- sessionSystemUpdates,
3619
- sessionSystemUpdateOutbox,
3620
- sessionWorkflowWakeOutbox,
3621
- sessionGoals,
3622
- codexCapacityWaiters,
3623
- sessionEvents,
3624
- agentRunStates,
3625
- sessionHumanInputRequests,
3626
- sessionHistoryItems,
3627
- sessionPendingToolCalls,
3628
- sandboxSessionEnvelopes,
3629
- sandboxLeaseLivenessValues,
3630
- sandboxLeases,
3631
- sandboxLeaseHolders,
3632
- sandboxWorkspaceMutationActorKindValues,
3633
- sandboxWorkspaceMutationHolderKindValues,
3634
- sandboxWorkspaceMutationAdmissions,
3635
- sandboxRetainedProcessStateValues,
3636
- sandboxRetainedProcesses,
3637
- sessionRecordingStateValues,
3638
- sessionRecordingModeValues,
3639
- sessionRecordingCodecValues,
3640
- sessionRecordings,
3641
- workspaceCaptures,
3642
- sandboxPtySessions,
3643
- enrollmentExposureValues,
3644
- enrollmentStatusValues,
3645
- enrollmentOsValues,
3646
- sandboxKindValues,
3647
- enrollments,
3648
- deviceEnrollmentStatusValues,
3649
- deviceEnrollmentRequests,
3650
- sandboxes,
3651
- machineMetricsLatest,
3652
- machineMetricsSeries,
3653
- scheduledTasks,
3654
- scheduledTaskRuns,
3655
- githubInstallations,
3656
- githubInstallationRepositories,
3657
- usageEvents,
3658
- hostExportConfig,
3659
- hostExportOutbox,
3660
- hostExportCursorState,
3661
- hostExportConsumers,
3662
- hostExportDeadLetters,
3663
- creditLedgerEntries,
3664
- billingCustomers,
3665
- stripeWebhookEvents,
3666
- auditEvents,
3667
- packInstallations,
3668
- workspacePacks,
3669
- importBatches,
3670
- capabilityCatalogItems,
3671
- capabilityInstallations,
3672
- socialConnections,
3673
- socialPosts,
3674
- rigs,
3675
- rigVersions,
3676
- rigChanges,
3677
- schema_exports
3678
- };
3679
- //# sourceMappingURL=chunk-VUKRIBO5.js.map