@opengeni/db 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{chunk-OGCE6O2X.js → chunk-7LDU7F5P.js} +31 -3
  2. package/dist/chunk-7LDU7F5P.js.map +1 -0
  3. package/dist/chunk-O3D7DABC.js +2314 -0
  4. package/dist/chunk-O3D7DABC.js.map +1 -0
  5. package/dist/{chunk-57MLICFR.js → chunk-YFQ7SGE4.js} +18 -6
  6. package/dist/chunk-YFQ7SGE4.js.map +1 -0
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +13129 -3496
  9. package/dist/index.js.map +1 -1
  10. package/dist/migrate.js +1 -1
  11. package/dist/provision-roles.d.ts +1836 -222
  12. package/dist/provision-roles.js +1 -1
  13. package/dist/{schema-Dsz6UHNv.d.ts → schema-Dp2MbBxx.d.ts} +7480 -3305
  14. package/dist/schema.d.ts +1 -1
  15. package/dist/schema.js +33 -5
  16. package/drizzle/0043_credit_balance_observability.sql +22 -0
  17. package/drizzle/0044_reap_dead_turn_holders.sql +104 -0
  18. package/drizzle/0045_workspace_captures.sql +83 -0
  19. package/drizzle/0045_workspace_memory_v1.sql +71 -0
  20. package/drizzle/0046_variable_sets_rename.sql +56 -0
  21. package/drizzle/0047_rigs.sql +151 -0
  22. package/drizzle/0048_rig_runtime.sql +9 -0
  23. package/drizzle/0049_enrollment_went_offline.sql +28 -0
  24. package/drizzle/0050_enrollment_op_stream.sql +1 -0
  25. package/drizzle/0051_codex_pin_source.sql +48 -0
  26. package/drizzle/0052_file_upload_cleanup.sql +91 -0
  27. package/drizzle/0053_codex_credential_leases.sql +230 -0
  28. package/drizzle/0054_session_pins.sql +85 -0
  29. package/drizzle/0055_session_list_snapshots.sql +73 -0
  30. package/drizzle/0056_workspace_model_policies.sql +48 -0
  31. package/drizzle/0057_durable_queue_control.sql +536 -0
  32. package/drizzle/0058_turn_admission_usage_enrollment.sql +158 -0
  33. package/drizzle/0059_workspace_pause_control_kind.sql +12 -0
  34. package/drizzle/0060_session_system_update_deferral.sql +10 -0
  35. package/drizzle/0061_session_workflow_wake_outbox.sql +157 -0
  36. package/drizzle/0062_session_list_snapshot_reaper.sql +48 -0
  37. package/package.json +17 -13
  38. package/src/codex-token-resolver.ts +58 -23
  39. package/src/connection-token-resolver.ts +146 -57
  40. package/src/environment-crypto.ts +5 -1
  41. package/src/event-payload-sanitizer.ts +29 -1
  42. package/src/index.ts +22460 -6492
  43. package/src/memory-domain.ts +218 -0
  44. package/src/migrate.ts +58 -3
  45. package/src/provision-roles.ts +46 -17
  46. package/src/schema.ts +2557 -1121
  47. package/src/session-control-cutover-audit.ts +1203 -0
  48. package/dist/chunk-57MLICFR.js.map +0 -1
  49. package/dist/chunk-OGCE6O2X.js.map +0 -1
  50. package/dist/chunk-ZIUCA2IO.js +0 -1268
  51. package/dist/chunk-ZIUCA2IO.js.map +0 -1
@@ -1,1268 +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
- codexRotationSettings: () => codexRotationSettings,
15
- codexSubscriptionCredentials: () => codexSubscriptionCredentials,
16
- connections: () => connections,
17
- creditLedgerEntries: () => creditLedgerEntries,
18
- deviceEnrollmentRequests: () => deviceEnrollmentRequests,
19
- deviceEnrollmentStatusValues: () => deviceEnrollmentStatusValues,
20
- documentBases: () => documentBases,
21
- documentChunks: () => documentChunks,
22
- documents: () => documents,
23
- enrollmentExposureValues: () => enrollmentExposureValues,
24
- enrollmentOsValues: () => enrollmentOsValues,
25
- enrollmentStatusValues: () => enrollmentStatusValues,
26
- enrollments: () => enrollments,
27
- fileUploads: () => fileUploads,
28
- files: () => files,
29
- githubInstallations: () => githubInstallations,
30
- importBatches: () => importBatches,
31
- integrationOauthClients: () => integrationOauthClients,
32
- integrationOauthStateNonces: () => integrationOauthStateNonces,
33
- knowledgeMemories: () => knowledgeMemories,
34
- machineMetricsLatest: () => machineMetricsLatest,
35
- machineMetricsSeries: () => machineMetricsSeries,
36
- managedAccounts: () => managedAccounts,
37
- packInstallations: () => packInstallations,
38
- sandboxKindValues: () => sandboxKindValues,
39
- sandboxLeaseHolders: () => sandboxLeaseHolders,
40
- sandboxLeaseLivenessValues: () => sandboxLeaseLivenessValues,
41
- sandboxLeases: () => sandboxLeases,
42
- sandboxPtySessions: () => sandboxPtySessions,
43
- sandboxSessionEnvelopes: () => sandboxSessionEnvelopes,
44
- sandboxes: () => sandboxes,
45
- scheduledTaskRuns: () => scheduledTaskRuns,
46
- scheduledTasks: () => scheduledTasks,
47
- sessionEvents: () => sessionEvents,
48
- sessionGoals: () => sessionGoals,
49
- sessionHistoryItems: () => sessionHistoryItems,
50
- sessionMcpServers: () => sessionMcpServers,
51
- sessionRecordingCodecValues: () => sessionRecordingCodecValues,
52
- sessionRecordingModeValues: () => sessionRecordingModeValues,
53
- sessionRecordingStateValues: () => sessionRecordingStateValues,
54
- sessionRecordings: () => sessionRecordings,
55
- sessionTurns: () => sessionTurns,
56
- sessions: () => sessions,
57
- socialConnections: () => socialConnections,
58
- socialPosts: () => socialPosts,
59
- stripeWebhookEvents: () => stripeWebhookEvents,
60
- usageEvents: () => usageEvents,
61
- workspaceEnvironmentVariables: () => workspaceEnvironmentVariables,
62
- workspaceEnvironments: () => workspaceEnvironments,
63
- workspaceMemberships: () => workspaceMemberships,
64
- workspacePacks: () => workspacePacks,
65
- workspaces: () => workspaces
66
- });
67
- import { sql } from "drizzle-orm";
68
- import { bigint, boolean, index, integer, jsonb, numeric, pgTable, text, timestamp, uniqueIndex, uuid, customType } from "drizzle-orm/pg-core";
69
- var vector = customType({
70
- dataType() {
71
- return "vector(3072)";
72
- },
73
- toDriver(value) {
74
- return `[${value.join(",")}]`;
75
- }
76
- });
77
- var managedAccounts = pgTable("managed_accounts", {
78
- id: uuid("id").primaryKey().defaultRandom(),
79
- name: text("name").notNull(),
80
- externalSource: text("external_source"),
81
- externalId: text("external_id"),
82
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
83
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
84
- }, (table) => ({
85
- external: uniqueIndex("managed_accounts_external_idx").on(table.externalSource, table.externalId)
86
- }));
87
- var workspaces = pgTable("workspaces", {
88
- id: uuid("id").primaryKey().defaultRandom(),
89
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
90
- name: text("name").notNull(),
91
- slug: text("slug"),
92
- externalSource: text("external_source"),
93
- externalId: text("external_id"),
94
- // White-label agent persona template override. NULL means the deployment
95
- // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
96
- agentInstructions: text("agent_instructions"),
97
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
98
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
99
- }, (table) => ({
100
- account: index("workspaces_account_idx").on(table.accountId),
101
- accountSlug: uniqueIndex("workspaces_account_slug_idx").on(table.accountId, table.slug).where(sql`${table.slug} is not null`),
102
- external: uniqueIndex("workspaces_external_idx").on(table.externalSource, table.externalId)
103
- }));
104
- var workspaceMemberships = pgTable("workspace_memberships", {
105
- id: uuid("id").primaryKey().defaultRandom(),
106
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
107
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
108
- subjectId: text("subject_id").notNull(),
109
- subjectLabel: text("subject_label"),
110
- role: text("role").notNull().default("member"),
111
- permissions: jsonb("permissions").$type().notNull().default([]),
112
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
113
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
114
- }, (table) => ({
115
- subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on(table.subjectId, table.workspaceId),
116
- subject: index("workspace_memberships_subject_idx").on(table.subjectId),
117
- account: index("workspace_memberships_account_idx").on(table.accountId)
118
- }));
119
- var apiKeys = pgTable("api_keys", {
120
- id: uuid("id").primaryKey().defaultRandom(),
121
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
122
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
123
- name: text("name").notNull(),
124
- prefix: text("prefix").notNull(),
125
- keyHash: text("key_hash").notNull(),
126
- permissions: jsonb("permissions").$type().notNull().default([]),
127
- expiresAt: timestamp("expires_at", { withTimezone: true }),
128
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
129
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
130
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
131
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
132
- }, (table) => ({
133
- prefix: index("api_keys_prefix_idx").on(table.prefix),
134
- hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash),
135
- account: index("api_keys_account_idx").on(table.accountId),
136
- workspace: index("api_keys_workspace_idx").on(table.workspaceId)
137
- }));
138
- var workspaceEnvironments = pgTable("workspace_environments", {
139
- id: uuid("id").primaryKey().defaultRandom(),
140
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
141
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
142
- name: text("name").notNull(),
143
- description: text("description"),
144
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
145
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
146
- }, (table) => ({
147
- workspaceName: uniqueIndex("workspace_environments_workspace_name_idx").on(table.workspaceId, table.name),
148
- workspaceCreated: index("workspace_environments_workspace_created_idx").on(table.workspaceId, table.createdAt)
149
- }));
150
- var workspaceEnvironmentVariables = pgTable("workspace_environment_variables", {
151
- id: uuid("id").primaryKey().defaultRandom(),
152
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
153
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
154
- environmentId: uuid("environment_id").notNull().references(() => workspaceEnvironments.id, { onDelete: "cascade" }),
155
- name: text("name").notNull(),
156
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
157
- valueEncrypted: text("value_encrypted").notNull(),
158
- version: integer("version").notNull().default(1),
159
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
160
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
161
- }, (table) => ({
162
- environmentName: uniqueIndex("workspace_environment_variables_env_name_idx").on(table.workspaceId, table.environmentId, table.name),
163
- environment: index("workspace_environment_variables_workspace_env_idx").on(table.workspaceId, table.environmentId)
164
- }));
165
- var codexSubscriptionCredentials = pgTable("codex_subscription_credentials", {
166
- id: uuid("id").primaryKey().defaultRandom(),
167
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
168
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
169
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
170
- credentialEncrypted: text("credential_encrypted").notNull(),
171
- chatgptAccountId: text("chatgpt_account_id"),
172
- // plaintext ChatGPT-Account-ID header value (non-secret)
173
- scopes: text("scopes"),
174
- // space-delimited, as granted
175
- planType: text("plan_type"),
176
- isFedramp: boolean("is_fedramp").notNull().default(false),
177
- expiresAt: timestamp("expires_at", { withTimezone: true }),
178
- // derived from access-token JWT exp
179
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
180
- status: text("status").notNull().default("active"),
181
- // active | needs_relogin | error
182
- lastError: text("last_error"),
183
- version: integer("version").notNull().default(1),
184
- label: text("label"),
185
- // user-chosen nickname; null ⇒ derive from email/plan/account
186
- accountEmail: text("account_email"),
187
- // email from the id_token (user's own email; non-secret)
188
- // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
189
- // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
190
- // (limit_window_seconds 18000), secondary = weekly (604800).
191
- primaryUsedPercent: integer("primary_used_percent"),
192
- primaryResetAt: timestamp("primary_reset_at", { withTimezone: true }),
193
- secondaryUsedPercent: integer("secondary_used_percent"),
194
- secondaryResetAt: timestamp("secondary_reset_at", { withTimezone: true }),
195
- usageCheckedAt: timestamp("usage_checked_at", { withTimezone: true }),
196
- // snapshot freshness → cache TTL clock
197
- // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
198
- // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
199
- // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
200
- exhaustedUntil: timestamp("exhausted_until", { withTimezone: true }),
201
- // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
202
- // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
203
- // exposes via codex_apps, captured from the per-turn tools/list. null ⇒ never
204
- // probed (the ranker treats it as unknown: never credited as covering, never
205
- // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
206
- // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
207
- connectorNamespaces: text("connector_namespaces").array(),
208
- connectorsCheckedAt: timestamp("connectors_checked_at", { withTimezone: true }),
209
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
210
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
211
- }, (table) => ({
212
- // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
213
- // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
214
- // so degenerate null-account rows can't collide; the device-grant connect path always
215
- // populates chatgpt_account_id.
216
- wsAccount: uniqueIndex("codex_subscription_credentials_ws_account_idx").on(table.workspaceId, table.chatgptAccountId).where(sql`${table.chatgptAccountId} is not null`),
217
- workspace: index("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId)
218
- }));
219
- var connections = pgTable("connections", {
220
- id: uuid("id").primaryKey().defaultRandom(),
221
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
222
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
223
- subjectId: text("subject_id"),
224
- providerDomain: text("provider_domain").notNull(),
225
- kind: text("kind").notNull(),
226
- status: text("status").notNull().default("active"),
227
- credentialEncrypted: text("credential_encrypted").notNull(),
228
- grantedScopes: jsonb("granted_scopes").$type().notNull().default([]),
229
- expiresAt: timestamp("expires_at", { withTimezone: true }),
230
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
231
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
232
- lastError: text("last_error"),
233
- version: integer("version").notNull().default(1),
234
- metadata: jsonb("metadata").$type().notNull().default({}),
235
- createdBySubjectId: text("created_by_subject_id"),
236
- updatedBySubjectId: text("updated_by_subject_id"),
237
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
238
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
239
- }, (table) => ({
240
- workspaceProviderStatus: index("connections_workspace_provider_status_idx").on(table.workspaceId, table.providerDomain, table.status),
241
- workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on(table.workspaceId, table.subjectId, table.providerDomain),
242
- workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
243
- workspaceExpires: index("connections_workspace_expires_idx").on(table.workspaceId, table.expiresAt)
244
- }));
245
- var integrationOauthClients = pgTable("integration_oauth_clients", {
246
- id: uuid("id").primaryKey().defaultRandom(),
247
- issuer: text("issuer").notNull(),
248
- authorizationServer: text("authorization_server").notNull(),
249
- clientId: text("client_id").notNull(),
250
- clientSecretEncrypted: text("client_secret_encrypted"),
251
- tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"),
252
- metadata: jsonb("metadata").$type().notNull().default({}),
253
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
254
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
255
- }, (table) => ({
256
- issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer),
257
- authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer)
258
- }));
259
- var integrationOauthStateNonces = pgTable("integration_oauth_state_nonces", {
260
- nonce: text("nonce").primaryKey(),
261
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
262
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
263
- subjectId: text("subject_id").notNull(),
264
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
265
- usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(),
266
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
267
- }, (table) => ({
268
- workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
269
- expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt)
270
- }));
271
- var codexRotationSettings = pgTable("codex_rotation_settings", {
272
- id: uuid("id").primaryKey().defaultRandom(),
273
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
274
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
275
- activeCredentialId: uuid("active_credential_id"),
276
- rotationEnabled: boolean("rotation_enabled").notNull().default(false),
277
- // P3, inert in P1
278
- rotationStrategy: text("rotation_strategy").notNull().default("most_remaining"),
279
- // P3, inert
280
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
281
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
282
- }, (table) => ({
283
- workspace: uniqueIndex("codex_rotation_settings_workspace_idx").on(table.workspaceId)
284
- }));
285
- var sessions = pgTable("sessions", {
286
- id: uuid("id").primaryKey().defaultRandom(),
287
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
288
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
289
- status: text("status").notNull().default("queued"),
290
- initialMessage: text("initial_message").notNull(),
291
- title: text("title"),
292
- titleSource: text("title_source"),
293
- // Per-session agent persona/system instructions supplied at create (the
294
- // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
295
- // carried none, so the composed agent instructions are byte-identical to a
296
- // workspace-only persona (no backfill, no behavior change for existing rows).
297
- // Composed system-level AFTER the workspace agentInstructions; never emitted
298
- // as a timeline event.
299
- instructions: text("instructions"),
300
- resources: jsonb("resources").$type().notNull().default([]),
301
- tools: jsonb("tools").$type().notNull().default([]),
302
- metadata: jsonb("metadata").$type().notNull().default({}),
303
- model: text("model").notNull(),
304
- sandboxBackend: text("sandbox_backend").notNull(),
305
- // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
306
- // every existing + new row is a behavior-preserving no-op). CHECK-constrained
307
- // to the SandboxOs enum (linux|macos|windows) in migration 0018.
308
- sandboxOs: text("sandbox_os").notNull().default("linux"),
309
- // The shared-sandbox group this session's box belongs to. Defaults to the
310
- // session's OWN id (a singleton group: group === session — today's 1:1
311
- // behavior). When spawned shared via session_create, set to the PARENT's
312
- // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
313
- // value is this row's id or an ancestor session's id in the same workspace;
314
- // the live lease row, not a sandbox_groups table, materializes the group).
315
- // The app generates the uuid and uses it for both id and sandbox_group_id in
316
- // one insert — it cannot SQL-default to id (id is defaultRandom()).
317
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
318
- // The first-class swappable-sandbox POINTER (bring-your-own-compute M2,
319
- // dossier §10.3). NULL == "use the session's own group sandbox" (the
320
- // backward-compat default — every existing/new row is a behavior-preserving
321
- // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
322
- // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
323
- // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
324
- // pointer to the group default, never dangles) lives in migration 0024, NOT a
325
- // Drizzle .references() — exactly like parentSessionId below, so the const
326
- // ordering imposes no forward-reference.
327
- activeSandboxId: uuid("active_sandbox_id"),
328
- // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
329
- // in-flight op fenced by a stale active_epoch retries against the new active
330
- // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
331
- // JS string and breaks the strict fence; int4 returns a number.
332
- activeEpoch: integer("active_epoch").notNull().default(0),
333
- // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
334
- // agent/terminal/file-dock operate under. A launch-workspace_root-relative
335
- // subdir or an absolute machine path; surfaced alongside the active-sandbox
336
- // pointer (readActiveSandbox) and written through the epoch-fenced
337
- // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
338
- // behavior exactly — the agent substitutes its workspace_root for an empty cwd,
339
- // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
340
- workingDir: text("working_dir"),
341
- environmentId: uuid("environment_id").references(() => workspaceEnvironments.id, { onDelete: "set null" }),
342
- // Non-default first-party MCP token permissions (manager-style sessions);
343
- // null means the fixed worker default set in @opengeni/runtime.
344
- firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type(),
345
- // The manager session that spawned this one via session_create. Set only
346
- // when the creating grant carried a worker-signed sessionId claim (a session
347
- // spawning a worker); null for direct API creates and scheduled-task runs.
348
- // When set, this worker's terminal-for-now transitions wake the parent so a
349
- // manager can orchestrate workers without busy-polling. Self-referencing FK,
350
- // ON DELETE SET NULL so deleting a manager never cascades into its workers.
351
- parentSessionId: uuid("parent_session_id"),
352
- // Workspace-scoped CREATE idempotency key. NULL means the create carried no
353
- // key (each such create is independent). When set, the partial unique index
354
- // below collapses concurrent/retried creates with the same key in the same
355
- // workspace to a single session row — the dedup that closes the
356
- // double-submit/double-dispatch stuck-queued bug.
357
- createIdempotencyKey: text("create_idempotency_key"),
358
- temporalWorkflowId: text("temporal_workflow_id"),
359
- activeTurnId: uuid("active_turn_id"),
360
- // Actual input tokens reported for the last model call of the most recent
361
- // turn. The pre-turn client-side compaction trigger reads this as its budget
362
- // signal (char/4 estimate is the same-turn fallback). Null until a turn with
363
- // usage has completed.
364
- lastInputTokens: integer("last_input_tokens"),
365
- // Operator /compact request flag (client-side compaction path). The API sets
366
- // it true; the worker honors it BEFORE the next turn's model call by forcing
367
- // a compaction, then clears it. A durable flag (not a transient signal) so
368
- // the trigger survives a worker restart and converges before the next turn.
369
- compactRequested: boolean("compact_requested").notNull().default(false),
370
- lastSequence: integer("last_sequence").notNull().default(0),
371
- // The session's PINNED Codex account (manual override from the in-session
372
- // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
373
- // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
374
- // active", never dangles), same pattern as activeSandboxId.
375
- codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
376
- // The Codex account the session's most recent turn ACTUALLY ran on — drives
377
- // the "Running on:" indicator. Written by the worker at the turn boundary. FK
378
- // ON DELETE SET NULL (migration).
379
- codexLastCredentialId: uuid("codex_last_credential_id"),
380
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
381
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
382
- }, (table) => ({
383
- workspaceCreated: index("sessions_workspace_created_idx").on(table.workspaceId, table.createdAt),
384
- environment: index("sessions_environment_idx").on(table.workspaceId, table.environmentId),
385
- parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
386
- // Routing index: resolve session_id -> sandbox_group_id at every lease entry
387
- // point and enumerate all sessions in a group for attribution/disclosure.
388
- sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
389
- // Partial unique index: one session per (workspace, create_idempotency_key)
390
- // when a key is present. Concurrent creates racing on the same key see a
391
- // unique violation on all but one; the domain layer catches it and returns
392
- // the winning row instead of erroring.
393
- createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql`${table.createIdempotencyKey} is not null`)
394
- }));
395
- var sessionMcpServers = pgTable("session_mcp_servers", {
396
- id: uuid("id").primaryKey().defaultRandom(),
397
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
398
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
399
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
400
- serverId: text("server_id").notNull(),
401
- name: text("name"),
402
- url: text("url").notNull(),
403
- allowedTools: jsonb("allowed_tools").$type(),
404
- timeoutMs: integer("timeout_ms"),
405
- cacheToolsList: boolean("cache_tools_list").notNull().default(false),
406
- // Human-approval policy: `true` = every tool requires approval, a string[] of
407
- // UNPREFIXED tool names = only those require it, null/absent = auto-run.
408
- requireApproval: jsonb("require_approval").$type(),
409
- // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
410
- // worker's run-preparation path and never returned by API helpers.
411
- headersEncrypted: jsonb("headers_encrypted").$type().notNull().default({}),
412
- credentialVersion: integer("credential_version").notNull().default(1),
413
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
414
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
415
- }, (table) => ({
416
- sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(table.workspaceId, table.sessionId, table.serverId),
417
- session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId)
418
- }));
419
- var files = pgTable("files", {
420
- id: uuid("id").primaryKey().defaultRandom(),
421
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
422
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
423
- status: text("status").notNull().default("pending_upload"),
424
- filename: text("filename").notNull(),
425
- safeFilename: text("safe_filename").notNull(),
426
- contentType: text("content_type").notNull(),
427
- sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
428
- sha256: text("sha256"),
429
- bucket: text("bucket").notNull(),
430
- objectKey: text("object_key").notNull(),
431
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
432
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
433
- }, (table) => ({
434
- workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
435
- objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
436
- status: index("files_status_idx").on(table.status)
437
- }));
438
- var fileUploads = pgTable("file_uploads", {
439
- id: uuid("id").primaryKey().defaultRandom(),
440
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
441
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
442
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
443
- status: text("status").notNull().default("pending"),
444
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
445
- completedAt: timestamp("completed_at", { withTimezone: true }),
446
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
447
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
448
- }, (table) => ({
449
- workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
450
- fileId: index("file_uploads_file_id_idx").on(table.fileId),
451
- status: index("file_uploads_status_idx").on(table.status)
452
- }));
453
- var documentBases = pgTable("document_bases", {
454
- id: uuid("id").primaryKey().defaultRandom(),
455
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
456
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
457
- name: text("name").notNull(),
458
- description: text("description"),
459
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
460
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
461
- }, (table) => ({
462
- workspaceCreated: index("document_bases_workspace_created_idx").on(table.workspaceId, table.createdAt)
463
- }));
464
- var documents = pgTable("documents", {
465
- id: uuid("id").primaryKey().defaultRandom(),
466
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
467
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
468
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
469
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
470
- status: text("status").notNull().default("queued"),
471
- title: text("title").notNull(),
472
- parser: text("parser").notNull().default("liteparse"),
473
- chunkCount: integer("chunk_count").notNull().default(0),
474
- error: text("error"),
475
- sourceKind: text("source_kind").notNull().default("manual_upload"),
476
- sourceUri: text("source_uri"),
477
- sourceExternalId: text("source_external_id"),
478
- sourceTitle: text("source_title"),
479
- sourceAuthor: text("source_author"),
480
- sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
481
- sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
482
- sourceVersion: text("source_version"),
483
- aclTags: jsonb("acl_tags").$type().notNull().default([]),
484
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
485
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
486
- }, (table) => ({
487
- baseFile: uniqueIndex("documents_workspace_base_file_idx").on(table.workspaceId, table.baseId, table.fileId),
488
- baseStatus: index("documents_workspace_base_status_idx").on(table.workspaceId, table.baseId, table.status),
489
- sourceKind: index("documents_workspace_source_kind_idx").on(table.workspaceId, table.sourceKind),
490
- sourceExternalId: index("documents_workspace_source_external_id_idx").on(table.workspaceId, table.sourceExternalId)
491
- }));
492
- var documentChunks = pgTable("document_chunks", {
493
- id: uuid("id").primaryKey().defaultRandom(),
494
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
495
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
496
- documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
497
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
498
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
499
- chunkIndex: integer("chunk_index").notNull(),
500
- text: text("text").notNull(),
501
- metadata: jsonb("metadata").$type().notNull().default({}),
502
- embedding: vector("embedding").notNull(),
503
- embeddingModel: text("embedding_model").notNull(),
504
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
505
- }, (table) => ({
506
- documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(table.workspaceId, table.documentId, table.chunkIndex),
507
- base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId)
508
- }));
509
- var knowledgeMemories = pgTable("knowledge_memories", {
510
- id: uuid("id").primaryKey().defaultRandom(),
511
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
512
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
513
- status: text("status").notNull().default("proposed"),
514
- kind: text("kind").notNull().default("semantic"),
515
- scope: text("scope").notNull().default("workspace"),
516
- text: text("text").notNull(),
517
- sourceRefs: jsonb("source_refs").$type().notNull().default([]),
518
- confidence: integer("confidence").notNull().default(50),
519
- metadata: jsonb("metadata").$type().notNull().default({}),
520
- createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, { onDelete: "set null" }),
521
- reviewedBy: text("reviewed_by"),
522
- reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
523
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
524
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
525
- }, (table) => ({
526
- workspaceStatus: index("knowledge_memories_workspace_status_idx").on(table.workspaceId, table.status, table.updatedAt),
527
- workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
528
- workspaceScope: index("knowledge_memories_workspace_scope_idx").on(table.workspaceId, table.scope),
529
- createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(table.workspaceId, table.createdBySessionId)
530
- }));
531
- var sessionTurns = pgTable("session_turns", {
532
- id: uuid("id").primaryKey().defaultRandom(),
533
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
534
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
535
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
536
- triggerEventId: uuid("trigger_event_id").notNull(),
537
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
538
- status: text("status").notNull(),
539
- source: text("source").notNull().default("user"),
540
- position: integer("position").notNull(),
541
- prompt: text("prompt").notNull(),
542
- resources: jsonb("resources").$type().notNull().default([]),
543
- tools: jsonb("tools").$type().notNull().default([]),
544
- model: text("model").notNull(),
545
- reasoningEffort: text("reasoning_effort").notNull(),
546
- sandboxBackend: text("sandbox_backend").notNull(),
547
- // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
548
- // constrained to the SandboxOs enum (or NULL) in migration 0018.
549
- sandboxOs: text("sandbox_os"),
550
- metadata: jsonb("metadata").$type().notNull().default({}),
551
- // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
552
- // by a single conditional UPDATE at tools/call time; the row lock serializes
553
- // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
554
- toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
555
- startedAt: timestamp("started_at", { withTimezone: true }),
556
- finishedAt: timestamp("finished_at", { withTimezone: true }),
557
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
558
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
559
- }, (table) => ({
560
- queue: index("session_turns_workspace_queue_idx").on(table.workspaceId, table.sessionId, table.status, table.position)
561
- }));
562
- var sessionGoals = pgTable("session_goals", {
563
- id: uuid("id").primaryKey().defaultRandom(),
564
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
565
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
566
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
567
- status: text("status").notNull().default("active"),
568
- // active | paused | completed
569
- text: text("text").notNull(),
570
- successCriteria: text("success_criteria"),
571
- evidence: text("evidence"),
572
- // set by goal_complete
573
- rationale: text("rationale"),
574
- // set by goal_pause
575
- pausedReason: text("paused_reason"),
576
- // agent | user_interrupt | api | no_progress | max_auto_continuations | limits
577
- createdBy: text("created_by").notNull().default("api"),
578
- // api | agent | scheduled_task
579
- version: integer("version").notNull().default(1),
580
- // bumped on every set/update; progress signal
581
- autoContinuations: integer("auto_continuations").notNull().default(0),
582
- noProgressStreak: integer("no_progress_streak").notNull().default(0),
583
- maxAutoContinuations: integer("max_auto_continuations"),
584
- // per-goal override; a configured settings cap (if any) remains the hard ceiling
585
- lastContinuationTurnId: uuid("last_continuation_turn_id"),
586
- versionAtLastContinuation: integer("version_at_last_continuation"),
587
- metadata: jsonb("metadata").$type().notNull().default({}),
588
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
589
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
590
- }, (table) => ({
591
- workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(table.workspaceId, table.sessionId),
592
- status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status)
593
- }));
594
- var sessionEvents = pgTable("session_events", {
595
- id: uuid("id").primaryKey().defaultRandom(),
596
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
597
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
598
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
599
- turnId: uuid("turn_id"),
600
- sequence: integer("sequence").notNull(),
601
- type: text("type").notNull(),
602
- payload: jsonb("payload").$type().notNull().default({}),
603
- clientEventId: text("client_event_id"),
604
- producerId: text("producer_id"),
605
- producerSeq: integer("producer_seq"),
606
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
607
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
608
- }, (table) => ({
609
- sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(table.workspaceId, table.sessionId, table.sequence),
610
- clientEvent: uniqueIndex("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql`${table.clientEventId} is not null`),
611
- 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`),
612
- sessionCreated: index("session_events_workspace_session_created_idx").on(table.workspaceId, table.sessionId, table.createdAt)
613
- }));
614
- var agentRunStates = pgTable("agent_run_states", {
615
- id: uuid("id").primaryKey().defaultRandom(),
616
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
617
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
618
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
619
- turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
620
- stateVersion: integer("state_version").notNull(),
621
- serializedRunState: text("serialized_run_state").notNull(),
622
- pendingApprovals: jsonb("pending_approvals").$type().notNull().default([]),
623
- // The Codex account that FROZE this run state: the turn's resolved codex
624
- // credential id (pin > workspace-active), or NULL when frozen on the
625
- // non-codex / Azure path (or before this column existed). The serialized
626
- // RunState blob round-trips `reasoning.encrypted_content` minted by the
627
- // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
628
- // foreign reasoning ids the Responses backend validates; but the blob carries
629
- // NO per-item producer tag (those live only on session_history_items). So we
630
- // stamp the freezing account here: on a resume (approval decision, or the
631
- // items-mode run-state fallback) whose codex account DIFFERS from this value,
632
- // the replay path neutralizes every reasoning item's account-bound identity
633
- // (encrypted_content + provider id) in the blob before it reaches the model.
634
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
635
- // stale-but-null tag still mismatches a live codex id, so the strip stays
636
- // correct either way). NULL on both sides (non-codex freeze + non-codex
637
- // resume) is a no-op, so single-account and non-codex sessions are unchanged.
638
- frozenCodexCredentialId: uuid("frozen_codex_credential_id"),
639
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
640
- });
641
- var sessionHistoryItems = pgTable("session_history_items", {
642
- id: uuid("id").primaryKey().defaultRandom(),
643
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
644
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
645
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
646
- turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
647
- // Numeric (not integer) so the synthetic compaction-summary row can be
648
- // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
649
- // of the kept tail without colliding with — and thus overwriting — the real
650
- // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
651
- // positions; only the summary uses the half-step. `mode: "number"` maps the
652
- // postgres.js string back to a JS number so every reader stays numeric.
653
- position: numeric("position", { mode: "number" }).notNull(),
654
- item: jsonb("item").$type().notNull(),
655
- // Live-row flag for client-side context compaction. The read path selects
656
- // only active rows; a compaction supersedes the summarized prefix (sets this
657
- // false — never deletes, so the full transcript stays as an audit trail) and
658
- // inserts ONE synthetic active summary row at the boundary. Defaults true so
659
- // every existing and normally-appended row is live.
660
- active: boolean("active").notNull().default(true),
661
- // The Codex account that PRODUCED these items: the per-turn resolved codex
662
- // credential id (pin > workspace-active), or NULL when produced on the
663
- // non-codex / Azure path (or before this column existed). Used to strip
664
- // cross-account `reasoning.encrypted_content` blobs — those are account/org-
665
- // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
666
- // into a turn running on account B 400s. The read path drops the encrypted
667
- // reasoning of any item whose producer != the turn's current codex account.
668
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
669
- // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
670
- // mismatches a live codex id so the strip stays correct either way).
671
- producerCodexCredentialId: uuid("producer_codex_credential_id"),
672
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
673
- }, (table) => ({
674
- positionIdx: uniqueIndex("session_history_items_position_idx").on(table.workspaceId, table.sessionId, table.position)
675
- }));
676
- var sandboxSessionEnvelopes = pgTable("sandbox_session_envelopes", {
677
- id: uuid("id").primaryKey().defaultRandom(),
678
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
679
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
680
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
681
- envelope: jsonb("envelope").$type().notNull(),
682
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
683
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
684
- }, (table) => ({
685
- sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(table.workspaceId, table.sessionId)
686
- }));
687
- var sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"];
688
- var sandboxLeases = pgTable("sandbox_leases", {
689
- id: uuid("id").primaryKey().defaultRandom(),
690
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
691
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
692
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
693
- liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
694
- refcount: integer("refcount").notNull().default(0),
695
- turnHolders: integer("turn_holders").notNull().default(0),
696
- viewerHolders: integer("viewer_holders").notNull().default(0),
697
- instanceId: text("instance_id"),
698
- backend: text("backend").notNull(),
699
- os: text("os").notNull().default("linux"),
700
- // The container IMAGE the group box runs (Modal image ref / docker image). A shared
701
- // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
702
- // same image. This column stamps the image the live box was created with; a resume
703
- // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
704
- // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
705
- // legacy/cold row reads NULL = "image unknown", which never conflicts.
706
- image: text("image"),
707
- dataPlaneUrl: text("data_plane_url"),
708
- // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
709
- // from the desktop noVNC (6080), so its resolved URL is cached independently.
710
- // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
711
- // null on every box re-key (warm-commit / fail / drain), symmetric with
712
- // data_plane_url.
713
- terminalDataPlaneUrl: text("terminal_data_plane_url"),
714
- // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
715
- // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
716
- // was always-true → every turn fenced); int4 returns a JS number, the fix.
717
- // Epochs never approach 2^31, so the narrower type loses nothing.
718
- leaseEpoch: integer("lease_epoch").notNull().default(0),
719
- // The group box-envelope (the "envelope split" Critical): the small recovery
720
- // descriptor to resume()-by-id the group's box without a per-session join.
721
- resumeBackendId: text("resume_backend_id"),
722
- resumeState: jsonb("resume_state").$type(),
723
- // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
724
- // idempotency tick (warm_seconds accrued idempotent on
725
- // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
726
- lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
727
- lastMeterTick: integer("last_meter_tick").notNull().default(0),
728
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
729
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
730
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
731
- }, (table) => ({
732
- groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
733
- reaperIdx: index("sandbox_leases_reaper_idx").on(table.expiresAt).where(sql`${table.liveness} in ('warming','warm','draining')`)
734
- }));
735
- var sandboxLeaseHolders = pgTable("sandbox_lease_holders", {
736
- id: uuid("id").primaryKey().defaultRandom(),
737
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
738
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
739
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
740
- kind: text("kind", { enum: ["turn", "viewer"] }).notNull(),
741
- holderId: text("holder_id").notNull(),
742
- // The attributing session within the (possibly shared) group.
743
- subjectId: uuid("subject_id"),
744
- lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
745
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
746
- }, (table) => ({
747
- holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(table.leaseId, table.kind, table.holderId),
748
- staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
749
- leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId)
750
- }));
751
- var sessionRecordingStateValues = ["recording", "finalizing", "available", "failed"];
752
- var sessionRecordingModeValues = ["manual", "on-turn", "on-verify"];
753
- var sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"];
754
- var sessionRecordings = pgTable("session_recordings", {
755
- id: uuid("id").primaryKey().defaultRandom(),
756
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
757
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
758
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
759
- turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
760
- state: text("state", { enum: sessionRecordingStateValues }).notNull(),
761
- mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
762
- codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
763
- storageKey: text("storage_key"),
764
- sizeBytes: bigint("size_bytes", { mode: "number" }),
765
- durationSeconds: numeric("duration_seconds").$type(),
766
- width: integer("width").notNull(),
767
- height: integer("height").notNull(),
768
- reason: text("reason"),
769
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
770
- finalizedAt: timestamp("finalized_at", { withTimezone: true })
771
- }, (table) => ({
772
- sessionIdx: index("session_recordings_session_idx").on(table.workspaceId, table.sessionId, table.createdAt)
773
- }));
774
- var sandboxPtySessions = pgTable("sandbox_pty_sessions", {
775
- id: uuid("id").primaryKey().defaultRandom(),
776
- // == ptyId on the wire
777
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
778
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
779
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
780
- // The SDK numeric exec-session id used by writeStdin({ sessionId }). Null until
781
- // the open exec yields a still-running process (a fast-exiting shell has none).
782
- execSessionId: integer("exec_session_id"),
783
- leaseEpoch: integer("lease_epoch").notNull(),
784
- // fenced to the box that opened it
785
- cols: integer("cols").notNull(),
786
- rows: integer("rows").notNull(),
787
- shell: text("shell").notNull(),
788
- cwd: text("cwd").notNull(),
789
- status: text("status").notNull().default("open"),
790
- // 'open' | 'closed'
791
- // The viewer grant/subject that opened it (free-text — access subjects are not
792
- // always UUIDs, M5; so a text column, never a uuid NOT NULL).
793
- openedBy: text("opened_by").notNull(),
794
- lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
795
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
796
- closedAt: timestamp("closed_at", { withTimezone: true })
797
- }, (table) => ({
798
- openIdx: index("sandbox_pty_sessions_session_idx").on(table.workspaceId, table.sessionId).where(sql`${table.status} = 'open'`)
799
- }));
800
- var enrollmentExposureValues = ["whole-machine"];
801
- var enrollmentStatusValues = ["active", "revoked"];
802
- var enrollmentOsValues = ["linux", "macos", "windows"];
803
- var sandboxKindValues = ["modal", "selfhosted"];
804
- var enrollments = pgTable("enrollments", {
805
- id: uuid("id").primaryKey().defaultRandom(),
806
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
807
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
808
- // The agent's ed25519 public key (the machine identity).
809
- pubkey: text("pubkey").notNull(),
810
- exposure: text("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
811
- hasDisplay: boolean("has_display").notNull().default(false),
812
- // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
813
- // not granted), the agent reports has_display=false AND a human, actionable reason
814
- // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
815
- // permitted (has_display=true) or the machine is genuinely headless — the reason
816
- // distinguishes "display present but capture not granted" from plain "no display"
817
- // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
818
- // from every connect Hello alongside has_display.
819
- desktopUnavailableReason: text("desktop_unavailable_reason"),
820
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
821
- status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
822
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
823
- arch: text("arch").notNull().default("x86_64"),
824
- // Heartbeat liveness cursor. Null until the first connect.
825
- lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
826
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
827
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
828
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
829
- }, (table) => ({
830
- // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
831
- workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(table.workspaceId, table.pubkey),
832
- // List a workspace's ACTIVE machines without scanning revoked rows.
833
- workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
834
- }));
835
- var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
836
- var deviceEnrollmentRequests = pgTable("device_enrollment_requests", {
837
- id: uuid("id").primaryKey().defaultRandom(),
838
- // The opaque code the agent polls with (unguessable, single-use). Unique.
839
- deviceCode: text("device_code").notNull(),
840
- // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
841
- // rows via a partial unique index so a recycled code never collides with a
842
- // terminal row.
843
- userCode: text("user_code").notNull(),
844
- // The workspace this request was started for (resolved from the deployment-edge
845
- // request context — the agent presents the access key, the flow binds to the
846
- // single managed workspace OR a workspace hint). account_id rides along for RLS.
847
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
848
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
849
- // The agent's ed25519 public key (the machine identity the enrollment binds to).
850
- pubkey: text("pubkey").notNull(),
851
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
852
- arch: text("arch").notNull().default("x86_64"),
853
- machineName: text("machine_name"),
854
- // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
855
- // approve). Mirrors the enrollment column domain.
856
- requestedExposure: text("requested_exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
857
- // The agent CAN offer a display (a real screen / Xvfb is available) — gates
858
- // whether screen-control consent is even meaningful. has_display on the
859
- // resulting enrollment is derived from this.
860
- canOfferDisplay: boolean("can_offer_display").notNull().default(false),
861
- // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
862
- // at approve is the AUTHORITATIVE consent; this is only the agent's request.
863
- requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
864
- status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
865
- // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
866
- approvedBySubjectId: text("approved_by_subject_id"),
867
- approvedBySubjectLabel: text("approved_by_subject_label"),
868
- // The user's screen-control consent decision (whole-machine is mandatory at
869
- // approve; screen-control is opt-in per this flag).
870
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
871
- approvedAt: timestamp("approved_at", { withTimezone: true }),
872
- // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
873
- // row AND a sandbox row appear). Null until approved.
874
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
875
- sandboxId: uuid("sandbox_id").references(() => sandboxes.id, { onDelete: "set null" }),
876
- // The short-TTL expiry; a pending row past this is EXPIRED on poll.
877
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
878
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
879
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
880
- }, (table) => ({
881
- // The device_code is the agent's poll key — globally unique + indexed.
882
- deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
883
- // The user_code must be unique among LIVE (pending) rows so the approve lookup
884
- // is unambiguous; a terminal row's code may be recycled.
885
- userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx").on(table.userCode).where(sql`${table.status} = 'pending'`),
886
- workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(table.workspaceId, table.createdAt),
887
- expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt)
888
- }));
889
- var sandboxes = pgTable("sandboxes", {
890
- id: uuid("id").primaryKey().defaultRandom(),
891
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
892
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
893
- kind: text("kind", { enum: sandboxKindValues }).notNull(),
894
- name: text("name").notNull(),
895
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
896
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
897
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
898
- }, (table) => ({
899
- workspaceCreated: index("sandboxes_workspace_created_idx").on(table.workspaceId, table.createdAt),
900
- enrollment: index("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql`${table.enrollmentId} is not null`)
901
- }));
902
- var machineMetricsLatest = pgTable("machine_metrics_latest", {
903
- enrollmentId: uuid("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
904
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
905
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
906
- cpuPercent: numeric("cpu_percent").$type(),
907
- load1: numeric("load1").$type(),
908
- load5: numeric("load5").$type(),
909
- load15: numeric("load15").$type(),
910
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
911
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
912
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
913
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
914
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
915
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
916
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
917
- contention: numeric("contention").$type(),
918
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
919
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
920
- }, (table) => ({
921
- workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId)
922
- }));
923
- var machineMetricsSeries = pgTable("machine_metrics_series", {
924
- id: uuid("id").primaryKey().defaultRandom(),
925
- enrollmentId: uuid("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
926
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
927
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
928
- cpuPercent: numeric("cpu_percent").$type(),
929
- load1: numeric("load1").$type(),
930
- load5: numeric("load5").$type(),
931
- load15: numeric("load15").$type(),
932
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
933
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
934
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
935
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
936
- gpuUtilPercent: numeric("gpu_util_percent").$type(),
937
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
938
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
939
- contention: numeric("contention").$type(),
940
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
941
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
942
- }, (table) => ({
943
- enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(table.enrollmentId, table.sampledAt),
944
- sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt)
945
- }));
946
- var scheduledTasks = pgTable("scheduled_tasks", {
947
- id: uuid("id").primaryKey().defaultRandom(),
948
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
949
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
950
- name: text("name").notNull(),
951
- status: text("status").notNull().default("active"),
952
- schedule: jsonb("schedule").$type().notNull(),
953
- temporalScheduleId: text("temporal_schedule_id").notNull(),
954
- runMode: text("run_mode").notNull().default("new_session_per_run"),
955
- overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
956
- agentConfig: jsonb("agent_config").$type().notNull(),
957
- reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, { onDelete: "set null" }),
958
- environmentId: uuid("environment_id").references(() => workspaceEnvironments.id, { onDelete: "restrict" }),
959
- metadata: jsonb("metadata").$type().notNull().default({}),
960
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
961
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
962
- }, (table) => ({
963
- temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(table.workspaceId, table.temporalScheduleId),
964
- status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
965
- environment: index("scheduled_tasks_environment_idx").on(table.workspaceId, table.environmentId)
966
- }));
967
- var scheduledTaskRuns = pgTable("scheduled_task_runs", {
968
- id: uuid("id").primaryKey().defaultRandom(),
969
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
970
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
971
- taskId: uuid("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
972
- status: text("status").notNull().default("queued"),
973
- triggerType: text("trigger_type").notNull(),
974
- scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
975
- firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
976
- sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null" }),
977
- triggerEventId: uuid("trigger_event_id"),
978
- error: text("error"),
979
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
980
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
981
- }, (table) => ({
982
- taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(table.workspaceId, table.taskId, table.createdAt),
983
- session: index("scheduled_task_runs_workspace_session_idx").on(table.workspaceId, table.sessionId)
984
- }));
985
- var githubInstallations = pgTable("github_installations", {
986
- id: uuid("id").primaryKey().defaultRandom(),
987
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
988
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
989
- installationId: integer("installation_id").notNull(),
990
- accountLogin: text("account_login"),
991
- accountType: text("account_type"),
992
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
993
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
994
- }, (table) => ({
995
- workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(table.workspaceId, table.installationId),
996
- installation: index("github_installations_installation_idx").on(table.installationId),
997
- workspace: index("github_installations_workspace_idx").on(table.workspaceId)
998
- }));
999
- var usageEvents = pgTable("usage_events", {
1000
- id: uuid("id").primaryKey().defaultRandom(),
1001
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1002
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1003
- subjectId: text("subject_id"),
1004
- eventType: text("event_type").notNull(),
1005
- quantity: bigint("quantity", { mode: "number" }).notNull(),
1006
- unit: text("unit").notNull(),
1007
- sourceResourceType: text("source_resource_type"),
1008
- sourceResourceId: text("source_resource_id"),
1009
- idempotencyKey: text("idempotency_key").notNull(),
1010
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
1011
- recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
1012
- exportedToBillingAt: timestamp("exported_to_billing_at", { withTimezone: true }),
1013
- billingProviderEventId: text("billing_provider_event_id")
1014
- }, (table) => ({
1015
- idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
1016
- workspaceMetric: index("usage_events_workspace_metric_idx").on(table.workspaceId, table.eventType, table.occurredAt),
1017
- accountMetric: index("usage_events_account_metric_idx").on(table.accountId, table.eventType, table.occurredAt)
1018
- }));
1019
- var creditLedgerEntries = pgTable("credit_ledger_entries", {
1020
- id: uuid("id").primaryKey().defaultRandom(),
1021
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1022
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1023
- type: text("type").notNull(),
1024
- amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
1025
- currency: text("currency").notNull().default("usd"),
1026
- sourceType: text("source_type"),
1027
- sourceId: text("source_id"),
1028
- idempotencyKey: text("idempotency_key").notNull(),
1029
- metadata: jsonb("metadata").$type().notNull().default({}),
1030
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1031
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1032
- }, (table) => ({
1033
- idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
1034
- accountCreated: index("credit_ledger_entries_account_created_idx").on(table.accountId, table.createdAt)
1035
- }));
1036
- var billingCustomers = pgTable("billing_customers", {
1037
- id: uuid("id").primaryKey().defaultRandom(),
1038
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1039
- provider: text("provider").notNull().default("stripe"),
1040
- providerCustomerId: text("provider_customer_id").notNull(),
1041
- email: text("email"),
1042
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1043
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1044
- }, (table) => ({
1045
- accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(table.accountId, table.provider),
1046
- providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(table.provider, table.providerCustomerId)
1047
- }));
1048
- var stripeWebhookEvents = pgTable("stripe_webhook_events", {
1049
- id: text("id").primaryKey(),
1050
- type: text("type").notNull(),
1051
- livemode: text("livemode").notNull().default("false"),
1052
- payload: jsonb("payload").$type().notNull(),
1053
- processedAt: timestamp("processed_at", { withTimezone: true }),
1054
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1055
- });
1056
- var auditEvents = pgTable("audit_events", {
1057
- id: uuid("id").primaryKey().defaultRandom(),
1058
- accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "set null" }),
1059
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1060
- subjectId: text("subject_id"),
1061
- action: text("action").notNull(),
1062
- targetType: text("target_type"),
1063
- targetId: text("target_id"),
1064
- metadata: jsonb("metadata").$type().notNull().default({}),
1065
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow()
1066
- }, (table) => ({
1067
- accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
1068
- workspaceCreated: index("audit_events_workspace_created_idx").on(table.workspaceId, table.occurredAt)
1069
- }));
1070
- var packInstallations = pgTable("pack_installations", {
1071
- id: uuid("id").primaryKey().defaultRandom(),
1072
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1073
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1074
- packId: text("pack_id").notNull(),
1075
- status: text("status").notNull().default("active"),
1076
- metadata: jsonb("metadata").$type().notNull().default({}),
1077
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
1078
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1079
- }, (table) => ({
1080
- workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(table.workspaceId, table.packId),
1081
- status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status)
1082
- }));
1083
- var workspacePacks = pgTable("workspace_packs", {
1084
- id: uuid("id").primaryKey().defaultRandom(),
1085
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1086
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1087
- packId: text("pack_id").notNull(),
1088
- manifest: jsonb("manifest").$type().notNull(),
1089
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1090
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1091
- }, (table) => ({
1092
- workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(table.workspaceId, table.packId)
1093
- }));
1094
- var importBatches = pgTable("import_batches", {
1095
- id: uuid("id").primaryKey().defaultRandom(),
1096
- source: text("source").notNull(),
1097
- snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
1098
- snapshotRef: text("snapshot_ref"),
1099
- attributionNote: text("attribution_note").notNull(),
1100
- importedCount: integer("imported_count").notNull().default(0),
1101
- skippedCount: integer("skipped_count").notNull().default(0),
1102
- quarantinedCount: integer("quarantined_count").notNull().default(0),
1103
- logoFailureCount: integer("logo_failure_count").notNull().default(0),
1104
- staleCount: integer("stale_count").notNull().default(0),
1105
- details: jsonb("details").$type().notNull().default({}),
1106
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1107
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1108
- }, (table) => ({
1109
- sourceSnapshot: index("import_batches_source_snapshot_idx").on(table.source, table.snapshotDate),
1110
- createdAt: index("import_batches_created_at_idx").on(table.createdAt)
1111
- }));
1112
- var capabilityCatalogItems = pgTable("capability_catalog_items", {
1113
- id: text("id").notNull(),
1114
- accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade" }),
1115
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
1116
- kind: text("kind").notNull(),
1117
- source: text("source").notNull().default("manual"),
1118
- name: text("name").notNull(),
1119
- description: text("description"),
1120
- category: text("category").notNull().default("custom"),
1121
- tags: jsonb("tags").$type().notNull().default([]),
1122
- homepageUrl: text("homepage_url"),
1123
- endpointUrl: text("endpoint_url"),
1124
- installUrl: text("install_url"),
1125
- authModel: text("auth_model"),
1126
- providerDomain: text("provider_domain"),
1127
- surfaceType: text("surface_type"),
1128
- transport: text("transport"),
1129
- mcpUrl: text("mcp_url"),
1130
- authKind: text("auth_kind"),
1131
- credentialFacts: jsonb("credential_facts").$type().notNull().default([]),
1132
- tier: text("tier"),
1133
- provenance: text("provenance"),
1134
- logoAssetPath: text("logo_asset_path"),
1135
- importBatchId: uuid("import_batch_id").references(() => importBatches.id, { onDelete: "set null" }),
1136
- stale: boolean("stale").notNull().default(false),
1137
- staleAt: timestamp("stale_at", { withTimezone: true }),
1138
- metadata: jsonb("metadata").$type().notNull().default({}),
1139
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1140
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1141
- }, (table) => ({
1142
- workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(table.workspaceId, table.id),
1143
- registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(table.source, table.providerDomain, table.mcpUrl),
1144
- globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx").on(table.id).where(sql`${table.workspaceId} is null`),
1145
- kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
1146
- category: index("capability_catalog_items_workspace_category_idx").on(table.workspaceId, table.category),
1147
- source: index("capability_catalog_items_workspace_source_idx").on(table.workspaceId, table.source),
1148
- providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
1149
- importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
1150
- stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale)
1151
- }));
1152
- var capabilityInstallations = pgTable("capability_installations", {
1153
- id: uuid("id").primaryKey().defaultRandom(),
1154
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1155
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1156
- capabilityId: text("capability_id").notNull(),
1157
- kind: text("kind").notNull(),
1158
- status: text("status").notNull().default("active"),
1159
- config: jsonb("config").$type().notNull().default({}),
1160
- metadata: jsonb("metadata").$type().notNull().default({}),
1161
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
1162
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1163
- }, (table) => ({
1164
- workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(table.workspaceId, table.capabilityId),
1165
- kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
1166
- status: index("capability_installations_workspace_status_idx").on(table.workspaceId, table.status)
1167
- }));
1168
- var socialConnections = pgTable("social_connections", {
1169
- id: uuid("id").primaryKey().defaultRandom(),
1170
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1171
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1172
- provider: text("provider").notNull(),
1173
- accountHandle: text("account_handle").notNull(),
1174
- accountName: text("account_name"),
1175
- externalAccountId: text("external_account_id"),
1176
- status: text("status").notNull().default("connected"),
1177
- scopes: jsonb("scopes").$type().notNull().default([]),
1178
- credentialRef: text("credential_ref"),
1179
- tokenMetadata: jsonb("token_metadata").$type().notNull().default({}),
1180
- metadata: jsonb("metadata").$type().notNull().default({}),
1181
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1182
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
1183
- }, (table) => ({
1184
- workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(table.workspaceId, table.provider, table.accountHandle),
1185
- providerStatus: index("social_connections_workspace_provider_status_idx").on(table.workspaceId, table.provider, table.status)
1186
- }));
1187
- var socialPosts = pgTable("social_posts", {
1188
- id: uuid("id").primaryKey().defaultRandom(),
1189
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1190
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1191
- connectionId: uuid("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
1192
- provider: text("provider").notNull(),
1193
- externalPostId: text("external_post_id"),
1194
- url: text("url"),
1195
- authorHandle: text("author_handle"),
1196
- text: text("text").notNull(),
1197
- publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
1198
- metrics: jsonb("metrics").$type().notNull().default({}),
1199
- raw: jsonb("raw").$type().notNull().default({}),
1200
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1201
- }, (table) => ({
1202
- connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(table.workspaceId, table.connectionId, table.externalPostId),
1203
- connectionPublished: index("social_posts_workspace_connection_published_idx").on(table.workspaceId, table.connectionId, table.publishedAt),
1204
- providerPublished: index("social_posts_workspace_provider_published_idx").on(table.workspaceId, table.provider, table.publishedAt)
1205
- }));
1206
-
1207
- export {
1208
- managedAccounts,
1209
- workspaces,
1210
- workspaceMemberships,
1211
- apiKeys,
1212
- workspaceEnvironments,
1213
- workspaceEnvironmentVariables,
1214
- codexSubscriptionCredentials,
1215
- connections,
1216
- integrationOauthClients,
1217
- integrationOauthStateNonces,
1218
- codexRotationSettings,
1219
- sessions,
1220
- sessionMcpServers,
1221
- files,
1222
- fileUploads,
1223
- documentBases,
1224
- documents,
1225
- documentChunks,
1226
- knowledgeMemories,
1227
- sessionTurns,
1228
- sessionGoals,
1229
- sessionEvents,
1230
- agentRunStates,
1231
- sessionHistoryItems,
1232
- sandboxSessionEnvelopes,
1233
- sandboxLeaseLivenessValues,
1234
- sandboxLeases,
1235
- sandboxLeaseHolders,
1236
- sessionRecordingStateValues,
1237
- sessionRecordingModeValues,
1238
- sessionRecordingCodecValues,
1239
- sessionRecordings,
1240
- sandboxPtySessions,
1241
- enrollmentExposureValues,
1242
- enrollmentStatusValues,
1243
- enrollmentOsValues,
1244
- sandboxKindValues,
1245
- enrollments,
1246
- deviceEnrollmentStatusValues,
1247
- deviceEnrollmentRequests,
1248
- sandboxes,
1249
- machineMetricsLatest,
1250
- machineMetricsSeries,
1251
- scheduledTasks,
1252
- scheduledTaskRuns,
1253
- githubInstallations,
1254
- usageEvents,
1255
- creditLedgerEntries,
1256
- billingCustomers,
1257
- stripeWebhookEvents,
1258
- auditEvents,
1259
- packInstallations,
1260
- workspacePacks,
1261
- importBatches,
1262
- capabilityCatalogItems,
1263
- capabilityInstallations,
1264
- socialConnections,
1265
- socialPosts,
1266
- schema_exports
1267
- };
1268
- //# sourceMappingURL=chunk-ZIUCA2IO.js.map