@opengeni/db 0.22.1 → 0.23.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 (48) hide show
  1. package/dist/{chunk-CYGFLLMN.js → chunk-3UCHDMKG.js} +656 -282
  2. package/dist/chunk-3UCHDMKG.js.map +1 -0
  3. package/dist/{chunk-BNGEN5QZ.js → chunk-L6ADMZHE.js} +24 -2
  4. package/dist/chunk-L6ADMZHE.js.map +1 -0
  5. package/dist/index.d.ts +42 -3
  6. package/dist/index.js +6919 -3760
  7. package/dist/index.js.map +1 -1
  8. package/dist/provision-roles.js +1 -1
  9. package/dist/runtime-posture.d.ts +3 -3
  10. package/dist/schema.d.ts +1416 -92
  11. package/dist/schema.js +11 -1
  12. package/dist/session-control.d.ts +7 -1
  13. package/dist/session-queue-commands.d.ts +8 -0
  14. package/dist/session-realtime-context.d.ts +56 -0
  15. package/dist/session-realtime-ledger.d.ts +188 -0
  16. package/dist/session-realtime-mirror.d.ts +30 -0
  17. package/dist/session-realtime-state.d.ts +2 -0
  18. package/dist/session-realtime-terminal.d.ts +40 -0
  19. package/dist/session-realtime.d.ts +59 -0
  20. package/dist/workspace-instruction-policies-schema.d.ts +239 -0
  21. package/dist/workspace-instruction-policies.d.ts +44 -0
  22. package/drizzle/0156_slack_reaction_trigger.sql +49 -0
  23. package/drizzle/0157_session_policy_role_snapshots.sql +1146 -0
  24. package/drizzle/0158_session_realtime_mode.sql +88 -0
  25. package/drizzle/0159_session_realtime_ledger.sql +198 -0
  26. package/drizzle/0160_session_realtime_delegation_terminal.sql +38 -0
  27. package/drizzle/0161_session_realtime_context_projection.sql +82 -0
  28. package/drizzle/0162_session_realtime_connection_promotion.sql +53 -0
  29. package/drizzle/0163_session_realtime_delegation_progress.sql +35 -0
  30. package/drizzle/0164_session_realtime_models.sql +28 -0
  31. package/package.json +4 -4
  32. package/src/index.ts +670 -79
  33. package/src/preference-registry.ts +11 -6
  34. package/src/provision-roles.ts +12 -0
  35. package/src/runtime-posture.ts +10 -0
  36. package/src/schema.ts +400 -43
  37. package/src/session-control.ts +596 -21
  38. package/src/session-queue-commands.ts +76 -7
  39. package/src/session-realtime-context.ts +393 -0
  40. package/src/session-realtime-ledger.ts +1790 -0
  41. package/src/session-realtime-mirror.ts +160 -0
  42. package/src/session-realtime-state.ts +25 -0
  43. package/src/session-realtime-terminal.ts +306 -0
  44. package/src/session-realtime.ts +611 -0
  45. package/src/workspace-instruction-policies-schema.ts +41 -0
  46. package/src/workspace-instruction-policies.ts +131 -2
  47. package/dist/chunk-BNGEN5QZ.js.map +0 -1
  48. package/dist/chunk-CYGFLLMN.js.map +0 -1
@@ -101,6 +101,10 @@ __export(schema_exports, {
101
101
  sessionMcpServers: () => sessionMcpServers,
102
102
  sessionPendingToolCalls: () => sessionPendingToolCalls,
103
103
  sessionPins: () => sessionPins,
104
+ sessionRealtimeConnections: () => sessionRealtimeConnections,
105
+ sessionRealtimeContextProjections: () => sessionRealtimeContextProjections,
106
+ sessionRealtimeEntries: () => sessionRealtimeEntries,
107
+ sessionRealtimeModes: () => sessionRealtimeModes,
104
108
  sessionRecordingCodecValues: () => sessionRecordingCodecValues,
105
109
  sessionRecordingModeValues: () => sessionRecordingModeValues,
106
110
  sessionRecordingStateValues: () => sessionRecordingStateValues,
@@ -131,6 +135,7 @@ __export(schema_exports, {
131
135
  workspaceInstructionPolicyActivationEvents: () => workspaceInstructionPolicyActivationEvents,
132
136
  workspaceInstructionPolicyHeads: () => workspaceInstructionPolicyHeads,
133
137
  workspaceInstructionPolicyRevisions: () => workspaceInstructionPolicyRevisions,
138
+ workspaceInstructionPolicySnapshots: () => workspaceInstructionPolicySnapshots,
134
139
  workspaceMemberships: () => workspaceMemberships,
135
140
  workspaceModelPolicies: () => workspaceModelPolicies,
136
141
  workspacePacks: () => workspacePacks,
@@ -146,8 +151,8 @@ import {
146
151
  check as check4,
147
152
  foreignKey,
148
153
  index as index5,
149
- integer as integer4,
150
- jsonb as jsonb4,
154
+ integer as integer5,
155
+ jsonb as jsonb5,
151
156
  numeric,
152
157
  pgTable as pgTable5,
153
158
  text as text5,
@@ -163,6 +168,8 @@ import {
163
168
  bigint,
164
169
  check,
165
170
  index,
171
+ integer,
172
+ jsonb,
166
173
  pgTable,
167
174
  text,
168
175
  timestamp,
@@ -283,6 +290,43 @@ var workspaceInstructionPolicyActivationEvents = pgTable(
283
290
  )
284
291
  })
285
292
  );
293
+ var workspaceInstructionPolicySnapshots = pgTable(
294
+ "workspace_instruction_policy_snapshots",
295
+ {
296
+ id: uuid("id").primaryKey().defaultRandom(),
297
+ accountId: uuid("account_id").notNull(),
298
+ workspaceId: uuid("workspace_id").notNull(),
299
+ sessionId: uuid("session_id").notNull(),
300
+ turnId: uuid("turn_id").notNull(),
301
+ attemptId: uuid("attempt_id").notNull(),
302
+ executionGeneration: integer("execution_generation").notNull(),
303
+ policyRole: text("policy_role"),
304
+ roleSource: text("role_source").notNull(),
305
+ entries: jsonb("entries").$type().notNull(),
306
+ entryHash: text("entry_hash").notNull(),
307
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
308
+ },
309
+ (table) => ({
310
+ attempt: uniqueIndex("workspace_instruction_policy_snapshots_attempt_uq").on(
311
+ table.accountId,
312
+ table.workspaceId,
313
+ table.attemptId
314
+ ),
315
+ workspaceTimeline: index("workspace_instruction_policy_snapshots_workspace_time_idx").on(
316
+ table.workspaceId,
317
+ table.createdAt,
318
+ table.id
319
+ ),
320
+ entriesShape: check(
321
+ "workspace_instruction_policy_snapshots_entries_chk",
322
+ sql`jsonb_typeof(${table.entries}) = 'array' and jsonb_array_length(${table.entries}) <= 3`
323
+ ),
324
+ roleSourceValid: check(
325
+ "workspace_instruction_policy_snapshots_role_source_chk",
326
+ sql`${table.roleSource} in ('session_binding', 'metadata_fallback', 'none', 'invalid_metadata_fallback')`
327
+ )
328
+ })
329
+ );
286
330
 
287
331
  // src/preference-registry-schema.ts
288
332
  import { sql as sql2 } from "drizzle-orm";
@@ -291,8 +335,8 @@ import {
291
335
  boolean,
292
336
  check as check2,
293
337
  index as index2,
294
- integer,
295
- jsonb,
338
+ integer as integer2,
339
+ jsonb as jsonb2,
296
340
  pgTable as pgTable2,
297
341
  text as text2,
298
342
  timestamp as timestamp2,
@@ -309,8 +353,8 @@ var preferenceRegistryPreferences = pgTable2(
309
353
  scopeWorkspaceId: uuid2("scope_workspace_id"),
310
354
  scopeSubjectId: text2("scope_subject_id"),
311
355
  status: text2("status").notNull().default("proposed"),
312
- scopeVersion: integer("scope_version").notNull().default(1),
313
- activationVersion: integer("activation_version").notNull().default(0),
356
+ scopeVersion: integer2("scope_version").notNull().default(1),
357
+ activationVersion: integer2("activation_version").notNull().default(0),
314
358
  activeRevisionId: uuid2("active_revision_id"),
315
359
  activeRevision: bigint2("active_revision", { mode: "number" }),
316
360
  activeContentHash: text2("active_content_hash"),
@@ -352,9 +396,9 @@ var preferenceRegistryRevisions = pgTable2(
352
396
  description: text2("description").notNull(),
353
397
  content: text2("content").notNull(),
354
398
  contentHash: text2("content_hash").notNull(),
355
- precedenceRank: integer("precedence_rank").notNull().default(0),
399
+ precedenceRank: integer2("precedence_rank").notNull().default(0),
356
400
  conflictStrategy: text2("conflict_strategy").notNull(),
357
- conflictsWith: jsonb("conflicts_with").$type().notNull().default([]),
401
+ conflictsWith: jsonb2("conflicts_with").$type().notNull().default([]),
358
402
  provenanceSource: text2("provenance_source").notNull(),
359
403
  provenanceSourceId: text2("provenance_source_id"),
360
404
  trust: text2("trust").notNull(),
@@ -381,7 +425,7 @@ var preferenceRegistryEvents = pgTable2(
381
425
  accountId: uuid2("account_id").notNull(),
382
426
  preferenceId: uuid2("preference_id").notNull(),
383
427
  type: text2("type").notNull(),
384
- version: integer("version").notNull(),
428
+ version: integer2("version").notNull(),
385
429
  oldRevisionId: uuid2("old_revision_id"),
386
430
  newRevisionId: uuid2("new_revision_id"),
387
431
  oldScope: text2("old_scope"),
@@ -416,9 +460,9 @@ var preferenceRegistrySnapshots = pgTable2(
416
460
  sessionId: uuid2("session_id").notNull(),
417
461
  turnId: uuid2("turn_id").notNull(),
418
462
  attemptId: uuid2("attempt_id").notNull(),
419
- executionGeneration: integer("execution_generation").notNull(),
463
+ executionGeneration: integer2("execution_generation").notNull(),
420
464
  initiatingHumanSubjectId: text2("initiating_human_subject_id").notNull(),
421
- descriptors: jsonb("descriptors").$type().notNull(),
465
+ descriptors: jsonb2("descriptors").$type().notNull(),
422
466
  descriptorHash: text2("descriptor_hash").notNull(),
423
467
  truncated: boolean("truncated").notNull().default(false),
424
468
  createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow()
@@ -446,8 +490,8 @@ import { sql as sql3 } from "drizzle-orm";
446
490
  import {
447
491
  check as check3,
448
492
  index as index3,
449
- integer as integer2,
450
- jsonb as jsonb2,
493
+ integer as integer3,
494
+ jsonb as jsonb3,
451
495
  pgTable as pgTable3,
452
496
  text as text3,
453
497
  timestamp as timestamp3,
@@ -463,7 +507,7 @@ var knowledgeMemoryRelationships = pgTable3(
463
507
  sourceMemoryId: uuid3("source_memory_id").notNull(),
464
508
  targetMemoryId: uuid3("target_memory_id").notNull(),
465
509
  relationshipType: text3("relationship_type").notNull(),
466
- version: integer2("version").notNull().default(1),
510
+ version: integer3("version").notNull().default(1),
467
511
  createdByEventId: uuid3("created_by_event_id").notNull(),
468
512
  removedByEventId: uuid3("removed_by_event_id"),
469
513
  createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -528,10 +572,10 @@ var knowledgeMemoryLifecycleEvents = pgTable3(
528
572
  actorSessionId: uuid3("actor_session_id"),
529
573
  actorTurnId: uuid3("actor_turn_id"),
530
574
  actorAttemptId: uuid3("actor_attempt_id"),
531
- actorExecutionGeneration: integer2("actor_execution_generation"),
575
+ actorExecutionGeneration: integer3("actor_execution_generation"),
532
576
  planHash: text3("plan_hash").notNull(),
533
- beforeState: jsonb2("before_state").$type().notNull(),
534
- afterState: jsonb2("after_state").$type().notNull(),
577
+ beforeState: jsonb3("before_state").$type().notNull(),
578
+ afterState: jsonb3("after_state").$type().notNull(),
535
579
  revertsEventId: uuid3("reverts_event_id"),
536
580
  createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
537
581
  },
@@ -600,8 +644,8 @@ import {
600
644
  bigint as bigint3,
601
645
  boolean as boolean2,
602
646
  index as index4,
603
- integer as integer3,
604
- jsonb as jsonb3,
647
+ integer as integer4,
648
+ jsonb as jsonb4,
605
649
  pgTable as pgTable4,
606
650
  text as text4,
607
651
  timestamp as timestamp4,
@@ -772,7 +816,7 @@ var knowledgeSyncRuns = pgTable4(
772
816
  state: text4("state").notNull().default("started"),
773
817
  outputCursor: text4("output_cursor"),
774
818
  watermark: timestamp4("watermark", { withTimezone: true }),
775
- metadata: jsonb3("metadata").$type().notNull().default({}),
819
+ metadata: jsonb4("metadata").$type().notNull().default({}),
776
820
  errorCode: text4("error_code"),
777
821
  completionHash: text4("completion_hash"),
778
822
  ...actorColumns(),
@@ -848,7 +892,7 @@ var knowledgeDocumentVersions = pgTable4(
848
892
  contentSha256: text4("content_sha256").notNull(),
849
893
  ingestionKey: text4("ingestion_key").notNull(),
850
894
  sourceCursor: text4("source_cursor"),
851
- sourceMetadata: jsonb3("source_metadata").$type().notNull().default({}),
895
+ sourceMetadata: jsonb4("source_metadata").$type().notNull().default({}),
852
896
  sourceCreatedAt: timestamp4("source_created_at", { withTimezone: true }),
853
897
  sourceUpdatedAt: timestamp4("source_updated_at", { withTimezone: true }),
854
898
  observedAt: timestamp4("observed_at", { withTimezone: true }).notNull().defaultNow(),
@@ -856,7 +900,7 @@ var knowledgeDocumentVersions = pgTable4(
856
900
  aclGeneration: bigint3("acl_generation", { mode: "number" }).notNull(),
857
901
  documentId: uuid4("document_id"),
858
902
  fileId: uuid4("file_id"),
859
- locationMetadata: jsonb3("location_metadata").$type().notNull().default({}),
903
+ locationMetadata: jsonb4("location_metadata").$type().notNull().default({}),
860
904
  operationId: text4("operation_id").notNull(),
861
905
  inputHash: text4("input_hash").notNull(),
862
906
  ...actorColumns(),
@@ -990,7 +1034,7 @@ var knowledgeFacts = pgTable4(
990
1034
  predicateKey: text4("predicate_key").notNull(),
991
1035
  objectKind: text4("object_kind").notNull(),
992
1036
  objectEntityId: uuid4("object_entity_id"),
993
- objectValue: jsonb3("object_value").$type(),
1037
+ objectValue: jsonb4("object_value").$type(),
994
1038
  objectHash: text4("object_hash").notNull(),
995
1039
  operationId: text4("operation_id").notNull(),
996
1040
  inputHash: text4("input_hash").notNull(),
@@ -1020,11 +1064,11 @@ var knowledgeClaims = pgTable4(
1020
1064
  ...tenantScopeColumns(),
1021
1065
  factId: uuid4("fact_id").notNull(),
1022
1066
  origin: text4("origin").notNull(),
1023
- confidenceBps: integer3("confidence_bps").notNull(),
1067
+ confidenceBps: integer4("confidence_bps").notNull(),
1024
1068
  effectiveAt: timestamp4("effective_at", { withTimezone: true }).notNull(),
1025
1069
  expiresAt: timestamp4("expires_at", { withTimezone: true }),
1026
1070
  extractionMethod: text4("extraction_method").notNull(),
1027
- extractionMetadata: jsonb3("extraction_metadata").$type().notNull().default({}),
1071
+ extractionMetadata: jsonb4("extraction_metadata").$type().notNull().default({}),
1028
1072
  modelProvider: text4("model_provider"),
1029
1073
  modelName: text4("model_name"),
1030
1074
  modelVersion: text4("model_version"),
@@ -1081,7 +1125,7 @@ var knowledgeClaimEvidence = pgTable4(
1081
1125
  documentVersionId: uuid4("document_version_id").notNull(),
1082
1126
  polarity: text4("polarity").notNull(),
1083
1127
  documentChunkId: uuid4("document_chunk_id"),
1084
- chunkIndex: integer3("chunk_index"),
1128
+ chunkIndex: integer4("chunk_index"),
1085
1129
  locator: text4("locator"),
1086
1130
  quoteHash: text4("quote_hash"),
1087
1131
  contentHash: text4("content_hash").notNull(),
@@ -1208,7 +1252,7 @@ var workspaces = pgTable5(
1208
1252
  agentInstructions: text5("agent_instructions"),
1209
1253
  // Growth-ready per-workspace settings bag (migration 0045). Holds memoryEnabled
1210
1254
  // and future workspace-level toggles; validated/merged via WorkspaceSettingsSchema.
1211
- settings: jsonb4("settings").$type().notNull().default({}),
1255
+ settings: jsonb5("settings").$type().notNull().default({}),
1212
1256
  // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions
1213
1257
  // created without an explicit rig ride no rig (today's behavior exactly). FK
1214
1258
  // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle
@@ -1284,16 +1328,16 @@ var workspaceArtifactVersions = pgTable5(
1284
1328
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1285
1329
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1286
1330
  artifactId: uuid5("artifact_id").notNull(),
1287
- revision: integer4("revision").notNull(),
1331
+ revision: integer5("revision").notNull(),
1288
1332
  contentKey: text5("content_key").notNull(),
1289
1333
  contentType: text5("content_type").$type().notNull().default("text/html"),
1290
1334
  contentSha256: text5("content_sha256").notNull(),
1291
- sizeBytes: integer4("size_bytes").notNull(),
1335
+ sizeBytes: integer5("size_bytes").notNull(),
1292
1336
  operationKey: text5("operation_key").notNull(),
1293
1337
  sourceSessionId: uuid5("source_session_id"),
1294
1338
  sourceTurnId: uuid5("source_turn_id"),
1295
1339
  sourceAttemptId: uuid5("source_attempt_id"),
1296
- sourceExecutionGeneration: integer4("source_execution_generation"),
1340
+ sourceExecutionGeneration: integer5("source_execution_generation"),
1297
1341
  createdBySubjectId: text5("created_by_subject_id").notNull(),
1298
1342
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
1299
1343
  },
@@ -1351,7 +1395,7 @@ var workspaceArtifactEvents = pgTable5(
1351
1395
  sourceSessionId: uuid5("source_session_id"),
1352
1396
  sourceTurnId: uuid5("source_turn_id"),
1353
1397
  sourceAttemptId: uuid5("source_attempt_id"),
1354
- sourceExecutionGeneration: integer4("source_execution_generation"),
1398
+ sourceExecutionGeneration: integer5("source_execution_generation"),
1355
1399
  actorSubjectId: text5("actor_subject_id").notNull(),
1356
1400
  reason: text5("reason").notNull(),
1357
1401
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
@@ -1396,7 +1440,7 @@ var nestedAgentDepthConfiguration = pgTable5(
1396
1440
  "nested_agent_depth_configuration",
1397
1441
  {
1398
1442
  singleton: boolean3("singleton").primaryKey().notNull().default(true),
1399
- maxNestedAgentDepth: integer4("max_nested_agent_depth").notNull(),
1443
+ maxNestedAgentDepth: integer5("max_nested_agent_depth").notNull(),
1400
1444
  policySource: text5("policy_source").$type().notNull(),
1401
1445
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
1402
1446
  },
@@ -1484,7 +1528,7 @@ var workspaceMemberships = pgTable5(
1484
1528
  subjectId: text5("subject_id").notNull(),
1485
1529
  subjectLabel: text5("subject_label"),
1486
1530
  role: text5("role").notNull().default("member"),
1487
- permissions: jsonb4("permissions").$type().notNull().default([]),
1531
+ permissions: jsonb5("permissions").$type().notNull().default([]),
1488
1532
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1489
1533
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
1490
1534
  },
@@ -1508,7 +1552,7 @@ var apiKeys = pgTable5(
1508
1552
  name: text5("name").notNull(),
1509
1553
  prefix: text5("prefix").notNull(),
1510
1554
  keyHash: text5("key_hash").notNull(),
1511
- permissions: jsonb4("permissions").$type().notNull().default([]),
1555
+ permissions: jsonb5("permissions").$type().notNull().default([]),
1512
1556
  expiresAt: timestamp5("expires_at", { withTimezone: true }),
1513
1557
  revokedAt: timestamp5("revoked_at", { withTimezone: true }),
1514
1558
  lastUsedAt: timestamp5("last_used_at", { withTimezone: true }),
@@ -1554,7 +1598,7 @@ var workspaceVariableSetVariables = pgTable5(
1554
1598
  name: text5("name").notNull(),
1555
1599
  // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
1556
1600
  valueEncrypted: text5("value_encrypted").notNull(),
1557
- version: integer4("version").notNull().default(1),
1601
+ version: integer5("version").notNull().default(1),
1558
1602
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1559
1603
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
1560
1604
  },
@@ -1590,7 +1634,7 @@ var codexSubscriptionCredentials = pgTable5(
1590
1634
  status: text5("status").notNull().default("active"),
1591
1635
  // active | needs_relogin | error
1592
1636
  lastError: text5("last_error"),
1593
- version: integer4("version").notNull().default(1),
1637
+ version: integer5("version").notNull().default(1),
1594
1638
  label: text5("label"),
1595
1639
  // user-chosen nickname; null ⇒ derive from email/plan/account
1596
1640
  accountEmail: text5("account_email"),
@@ -1598,9 +1642,9 @@ var codexSubscriptionCredentials = pgTable5(
1598
1642
  // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
1599
1643
  // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
1600
1644
  // (limit_window_seconds 18000), secondary = weekly (604800).
1601
- primaryUsedPercent: integer4("primary_used_percent"),
1645
+ primaryUsedPercent: integer5("primary_used_percent"),
1602
1646
  primaryResetAt: timestamp5("primary_reset_at", { withTimezone: true }),
1603
- secondaryUsedPercent: integer4("secondary_used_percent"),
1647
+ secondaryUsedPercent: integer5("secondary_used_percent"),
1604
1648
  secondaryResetAt: timestamp5("secondary_reset_at", { withTimezone: true }),
1605
1649
  usageCheckedAt: timestamp5("usage_checked_at", { withTimezone: true }),
1606
1650
  // snapshot freshness → cache TTL clock
@@ -1627,22 +1671,18 @@ var codexSubscriptionCredentials = pgTable5(
1627
1671
  allocatorEnabled: boolean3("allocator_enabled").notNull().default(true),
1628
1672
  // Independent OCC/audit sequence for the allocator toggle. Token refresh
1629
1673
  // continues to own `version`; quota/cache writes own neither counter.
1630
- allocatorVersion: integer4("allocator_version").notNull().default(1),
1674
+ allocatorVersion: integer5("allocator_version").notNull().default(1),
1631
1675
  allocatorUpdatedBySubjectId: text5("allocator_updated_by_subject_id"),
1632
- allocatorUpdatedAt: timestamp5("allocator_updated_at", {
1633
- withTimezone: true
1634
- }),
1676
+ allocatorUpdatedAt: timestamp5("allocator_updated_at", { withTimezone: true }),
1635
1677
  // Authoritative count-only summary cached from /wham/usage. Detailed rows
1636
1678
  // are never persisted as redemption authority; every first POST preflights
1637
1679
  // the provider's fresh detail endpoint.
1638
- resetCreditAvailableCount: integer4("reset_credit_available_count"),
1639
- resetCreditsCheckedAt: timestamp5("reset_credits_checked_at", {
1640
- withTimezone: true
1641
- }),
1680
+ resetCreditAvailableCount: integer5("reset_credit_available_count"),
1681
+ resetCreditsCheckedAt: timestamp5("reset_credits_checked_at", { withTimezone: true }),
1642
1682
  // Set only by a direct Better Auth cookie connection/reconnection. Legacy,
1643
1683
  // configured, delegated, API-key, and agent-created rows remain view-only.
1644
1684
  connectedBySubjectId: text5("connected_by_subject_id"),
1645
- selectionCount: integer4("selection_count").notNull().default(0),
1685
+ selectionCount: integer5("selection_count").notNull().default(0),
1646
1686
  lastSelectedAt: timestamp5("last_selected_at", { withTimezone: true }),
1647
1687
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1648
1688
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -1677,13 +1717,11 @@ var codexResetRedemptionAttempts = pgTable5(
1677
1717
  outcome: text5("outcome"),
1678
1718
  claimHolderId: uuid5("claim_holder_id"),
1679
1719
  claimExpiresAt: timestamp5("claim_expires_at", { withTimezone: true }),
1680
- confirmationExpiresAt: timestamp5("confirmation_expires_at", {
1681
- withTimezone: true
1682
- }).notNull(),
1720
+ confirmationExpiresAt: timestamp5("confirmation_expires_at", { withTimezone: true }).notNull(),
1683
1721
  providerStartedAt: timestamp5("provider_started_at", { withTimezone: true }),
1684
1722
  completedAt: timestamp5("completed_at", { withTimezone: true }),
1685
1723
  lastFailureKind: text5("last_failure_kind"),
1686
- retryCount: integer4("retry_count").notNull().default(0),
1724
+ retryCount: integer5("retry_count").notNull().default(0),
1687
1725
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1688
1726
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
1689
1727
  },
@@ -1738,19 +1776,19 @@ var connections = pgTable5(
1738
1776
  kind: text5("kind").notNull(),
1739
1777
  status: text5("status").notNull().default("active"),
1740
1778
  credentialEncrypted: text5("credential_encrypted").notNull(),
1741
- grantedScopes: jsonb4("granted_scopes").$type().notNull().default([]),
1779
+ grantedScopes: jsonb5("granted_scopes").$type().notNull().default([]),
1742
1780
  expiresAt: timestamp5("expires_at", { withTimezone: true }),
1743
1781
  lastRefreshAt: timestamp5("last_refresh_at", { withTimezone: true }),
1744
1782
  lastUsedAt: timestamp5("last_used_at", { withTimezone: true }),
1745
1783
  lastError: text5("last_error"),
1746
- version: integer4("version").notNull().default(1),
1784
+ version: integer5("version").notNull().default(1),
1747
1785
  // Server-owned proof that the dedicated install route verified the exact
1748
1786
  // credential at this connection version. Generic/legacy writers cannot set
1749
1787
  // these columns, and migration 0131 clears them when protected fields change
1750
1788
  // without a fresh verification in the same statement.
1751
1789
  verifiedInstallAt: timestamp5("verified_install_at", { withTimezone: true }),
1752
- verifiedInstallVersion: integer4("verified_install_version"),
1753
- metadata: jsonb4("metadata").$type().notNull().default({}),
1790
+ verifiedInstallVersion: integer5("verified_install_version"),
1791
+ metadata: jsonb5("metadata").$type().notNull().default({}),
1754
1792
  createdBySubjectId: text5("created_by_subject_id"),
1755
1793
  updatedBySubjectId: text5("updated_by_subject_id"),
1756
1794
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -1785,7 +1823,7 @@ var connectorActionPolicies = pgTable5(
1785
1823
  toolName: text5("tool_name").notNull(),
1786
1824
  actionName: text5("action_name").notNull(),
1787
1825
  policy: text5("policy").$type().notNull(),
1788
- version: integer4("version").notNull().default(1),
1826
+ version: integer5("version").notNull().default(1),
1789
1827
  createdBySubjectId: text5("created_by_subject_id").notNull(),
1790
1828
  updatedBySubjectId: text5("updated_by_subject_id").notNull(),
1791
1829
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -1860,9 +1898,10 @@ var slackInteractionInbox = pgTable5(
1860
1898
  status: text5("status").$type().notNull().default("pending"),
1861
1899
  claimHolderId: uuid5("claim_holder_id"),
1862
1900
  claimExpiresAt: timestamp5("claim_expires_at", { withTimezone: true }),
1863
- attemptCount: integer4("attempt_count").notNull().default(0),
1901
+ attemptCount: integer5("attempt_count").notNull().default(0),
1864
1902
  retryAt: timestamp5("retry_at", { withTimezone: true }),
1865
1903
  lastErrorCode: text5("last_error_code"),
1904
+ reactionContextCheckpoint: jsonb5("reaction_context_checkpoint").$type(),
1866
1905
  processedAt: timestamp5("processed_at", { withTimezone: true }),
1867
1906
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1868
1907
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -1902,16 +1941,16 @@ var slackInteractions = pgTable5(
1902
1941
  sessionId: uuid5("session_id").references(() => sessions.id, {
1903
1942
  onDelete: "cascade"
1904
1943
  }),
1905
- lastDeliveredSessionEventSequence: integer4("last_delivered_session_event_sequence").notNull().default(0),
1944
+ lastDeliveredSessionEventSequence: integer5("last_delivered_session_event_sequence").notNull().default(0),
1906
1945
  deliveryClaimHolderId: uuid5("delivery_claim_holder_id"),
1907
1946
  deliveryClaimExpiresAt: timestamp5("delivery_claim_expires_at", {
1908
1947
  withTimezone: true
1909
1948
  }),
1910
- deliveryAttemptCount: integer4("delivery_attempt_count").notNull().default(0),
1949
+ deliveryAttemptCount: integer5("delivery_attempt_count").notNull().default(0),
1911
1950
  deliveryRetryAt: timestamp5("delivery_retry_at", { withTimezone: true }),
1912
1951
  deliveryLastErrorCode: text5("delivery_last_error_code"),
1913
1952
  ackSlackMessageTs: text5("ack_slack_message_ts"),
1914
- progressCount: integer4("progress_count").notNull().default(0),
1953
+ progressCount: integer5("progress_count").notNull().default(0),
1915
1954
  terminalDeliveryState: text5("terminal_delivery_state").$type().notNull().default("open"),
1916
1955
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1917
1956
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -1943,8 +1982,8 @@ var slackInteractionProgressDeliveries = pgTable5(
1943
1982
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1944
1983
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1945
1984
  interactionId: uuid5("interaction_id").notNull(),
1946
- sessionEventSequence: integer4("session_event_sequence").notNull(),
1947
- slot: integer4("slot").notNull(),
1985
+ sessionEventSequence: integer5("session_event_sequence").notNull(),
1986
+ slot: integer5("slot").notNull(),
1948
1987
  operationId: uuid5("operation_id").notNull(),
1949
1988
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
1950
1989
  },
@@ -1987,7 +2026,7 @@ var slackBotPostOperations = pgTable5(
1987
2026
  status: text5("status").$type().notNull(),
1988
2027
  claimHolderId: uuid5("claim_holder_id"),
1989
2028
  claimExpiresAt: timestamp5("claim_expires_at", { withTimezone: true }),
1990
- attemptCount: integer4("attempt_count").notNull().default(0),
2029
+ attemptCount: integer5("attempt_count").notNull().default(0),
1991
2030
  lastFailureCode: text5("last_failure_code"),
1992
2031
  slackChannelId: text5("slack_channel_id"),
1993
2032
  slackMessageTimestamp: text5("slack_message_timestamp"),
@@ -2057,7 +2096,7 @@ var slackBotDeleteOperations = pgTable5(
2057
2096
  status: text5("status").$type().notNull(),
2058
2097
  claimHolderId: uuid5("claim_holder_id"),
2059
2098
  claimExpiresAt: timestamp5("claim_expires_at", { withTimezone: true }),
2060
- attemptCount: integer4("attempt_count").notNull().default(0),
2099
+ attemptCount: integer5("attempt_count").notNull().default(0),
2061
2100
  lastFailureCode: text5("last_failure_code"),
2062
2101
  slackChannelId: text5("slack_channel_id"),
2063
2102
  slackMessageTimestamp: text5("slack_message_timestamp"),
@@ -2120,7 +2159,7 @@ var integrationOauthClients = pgTable5(
2120
2159
  clientId: text5("client_id").notNull(),
2121
2160
  clientSecretEncrypted: text5("client_secret_encrypted"),
2122
2161
  tokenEndpointAuthMethod: text5("token_endpoint_auth_method").notNull().default("none"),
2123
- metadata: jsonb4("metadata").$type().notNull().default({}),
2162
+ metadata: jsonb5("metadata").$type().notNull().default({}),
2124
2163
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2125
2164
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2126
2165
  },
@@ -2196,7 +2235,7 @@ var codexCredentialLeases = pgTable5(
2196
2235
  // durable turn replaces holderId and increments generation atomically;
2197
2236
  // stale/zombie heartbeats and releases must match both values.
2198
2237
  holderId: text5("holder_id").notNull(),
2199
- generation: integer4("generation").notNull().default(1),
2238
+ generation: integer5("generation").notNull().default(1),
2200
2239
  leasedUntil: timestamp5("leased_until", { withTimezone: true }).notNull(),
2201
2240
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2202
2241
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -2235,15 +2274,20 @@ var sessions = pgTable5(
2235
2274
  // Composed system-level AFTER the workspace agentInstructions; never emitted
2236
2275
  // as a timeline event.
2237
2276
  instructions: text5("instructions"),
2238
- resources: jsonb4("resources").$type().notNull().default([]),
2239
- skills: jsonb4("skills").$type().notNull().default([]),
2240
- tools: jsonb4("tools").$type().notNull().default([]),
2241
- metadata: jsonb4("metadata").$type().notNull().default({}),
2277
+ // Immutable normalized prompt-policy role. This is deliberately separate
2278
+ // from workspace membership roles and memory selectors. Existing rows keep
2279
+ // NULL and use the bounded metadata.role compatibility fallback at the
2280
+ // attempt-snapshot boundary.
2281
+ policyRole: text5("policy_role"),
2282
+ resources: jsonb5("resources").$type().notNull().default([]),
2283
+ skills: jsonb5("skills").$type().notNull().default([]),
2284
+ tools: jsonb5("tools").$type().notNull().default([]),
2285
+ metadata: jsonb5("metadata").$type().notNull().default({}),
2242
2286
  // Frozen creator fact. This is used for creation attribution and for the
2243
2287
  // idempotent first-turn repair only; later turns capture their own actor.
2244
2288
  createdByKind: text5("created_by_kind").notNull().default("service"),
2245
2289
  createdBySubjectId: text5("created_by_subject_id").notNull().default("unattributed-legacy"),
2246
- createdByContext: jsonb4("created_by_context").$type().notNull().default({ backfill: true }),
2290
+ createdByContext: jsonb5("created_by_context").$type().notNull().default({ backfill: true }),
2247
2291
  model: text5("model").notNull(),
2248
2292
  sandboxBackend: text5("sandbox_backend").notNull(),
2249
2293
  // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
@@ -2273,7 +2317,7 @@ var sessions = pgTable5(
2273
2317
  // in-flight op fenced by a stale active_epoch retries against the new active
2274
2318
  // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
2275
2319
  // JS string and breaks the strict fence; int4 returns a number.
2276
- activeEpoch: integer4("active_epoch").notNull().default(0),
2320
+ activeEpoch: integer5("active_epoch").notNull().default(0),
2277
2321
  // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
2278
2322
  // agent/terminal/file-dock operate under. A launch-workspace_root-relative
2279
2323
  // subdir or an absolute machine path; surfaced alongside the active-sandbox
@@ -2294,20 +2338,20 @@ var sessions = pgTable5(
2294
2338
  rigVersionId: uuid5("rig_version_id"),
2295
2339
  // Non-default first-party MCP token permissions (manager-style sessions);
2296
2340
  // null means the fixed worker default set in @opengeni/runtime.
2297
- firstPartyMcpPermissions: jsonb4("first_party_mcp_permissions").$type(),
2341
+ firstPartyMcpPermissions: jsonb5("first_party_mcp_permissions").$type(),
2298
2342
  // Exact model-visible first-party tool selection. All catalogued tools are
2299
2343
  // selected by default; [] intentionally selects no broad-server tools.
2300
- firstPartyMcpTools: jsonb4("first_party_mcp_tools").$type().notNull(),
2344
+ firstPartyMcpTools: jsonb5("first_party_mcp_tools").$type().notNull(),
2301
2345
  // Initial-command staging only. initializeSessionStartAtomically copies
2302
2346
  // this immutable snapshot onto the first turn so create repair survives a
2303
2347
  // crash between the session insert and first-turn transaction. Runtime
2304
2348
  // credential authority must never read this session field.
2305
- initialPersonalConnectionDelegations: jsonb4("initial_personal_connection_delegations").$type().notNull().default([]),
2349
+ initialPersonalConnectionDelegations: jsonb5("initial_personal_connection_delegations").$type().notNull().default([]),
2306
2350
  // Durable tool-policy origin. Migration 0136 removes the old null/legacy
2307
2351
  // representation so every session has one explicit policy mode.
2308
- toolPolicy: jsonb4("tool_policy").$type().notNull(),
2352
+ toolPolicy: jsonb5("tool_policy").$type().notNull(),
2309
2353
  // Optimistic-concurrency fence for durable session tool-policy writes.
2310
- toolPolicyVersion: integer4("tool_policy_version").notNull().default(1),
2354
+ toolPolicyVersion: integer5("tool_policy_version").notNull().default(1),
2311
2355
  // The manager session that spawned this one via session_create. Set only
2312
2356
  // when the creating grant carried a worker-signed sessionId claim (a session
2313
2357
  // spawning a worker); null for direct API creates and scheduled-task runs.
@@ -2331,9 +2375,9 @@ var sessions = pgTable5(
2331
2375
  // populated by the database admission boundary and never re-derived from
2332
2376
  // a live workspace setting for an existing session.
2333
2377
  rootSessionId: uuid5("root_session_id").notNull(),
2334
- nestedAgentDepth: integer4("nested_agent_depth").notNull(),
2335
- maxNestedAgentDepthOverride: integer4("max_nested_agent_depth_override"),
2336
- effectiveMaxNestedAgentDepth: integer4("effective_max_nested_agent_depth").notNull(),
2378
+ nestedAgentDepth: integer5("nested_agent_depth").notNull(),
2379
+ maxNestedAgentDepthOverride: integer5("max_nested_agent_depth_override"),
2380
+ effectiveMaxNestedAgentDepth: integer5("effective_max_nested_agent_depth").notNull(),
2337
2381
  nestedAgentDepthPolicySource: text5("nested_agent_depth_policy_source").notNull(),
2338
2382
  nestedAgentDepthPolicySessionId: uuid5("nested_agent_depth_policy_session_id"),
2339
2383
  temporalWorkflowId: text5("temporal_workflow_id"),
@@ -2342,13 +2386,13 @@ var sessions = pgTable5(
2342
2386
  // turn. The pre-turn portable compaction trigger reads this as its budget
2343
2387
  // signal (char/4 estimate is the same-turn fallback). Null until a turn with
2344
2388
  // usage has completed.
2345
- lastInputTokens: integer4("last_input_tokens"),
2389
+ lastInputTokens: integer5("last_input_tokens"),
2346
2390
  // Operator /compact request flag. The API sets
2347
2391
  // it true; the worker honors it BEFORE the next turn's model call by forcing
2348
2392
  // a compaction, then clears it. A durable flag (not a transient signal) so
2349
2393
  // the trigger survives a worker restart and converges before the next turn.
2350
2394
  compactRequested: boolean3("compact_requested").notNull().default(false),
2351
- queueVersion: integer4("queue_version").notNull().default(0),
2395
+ queueVersion: integer5("queue_version").notNull().default(0),
2352
2396
  queueHeadPosition: bigint4("queue_head_position", { mode: "number" }).notNull().default(0),
2353
2397
  queueTailPosition: bigint4("queue_tail_position", { mode: "number" }).notNull().default(0),
2354
2398
  directControlState: text5("direct_control_state").notNull().default("active"),
@@ -2362,7 +2406,7 @@ var sessions = pgTable5(
2362
2406
  directControlChangedAt: timestamp5("direct_control_changed_at", {
2363
2407
  withTimezone: true
2364
2408
  }),
2365
- lastSequence: integer4("last_sequence").notNull().default(0),
2409
+ lastSequence: integer5("last_sequence").notNull().default(0),
2366
2410
  // The session's PINNED Codex account (manual override from the in-session
2367
2411
  // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
2368
2412
  // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
@@ -2433,6 +2477,296 @@ var sessions = pgTable5(
2433
2477
  )
2434
2478
  })
2435
2479
  );
2480
+ var sessionRealtimeModes = pgTable5(
2481
+ "session_realtime_modes",
2482
+ {
2483
+ id: uuid5("id").primaryKey().defaultRandom(),
2484
+ accountId: uuid5("account_id").notNull(),
2485
+ workspaceId: uuid5("workspace_id").notNull(),
2486
+ sessionId: uuid5("session_id").notNull(),
2487
+ operationId: uuid5("operation_id").notNull(),
2488
+ ownerSubjectId: text5("owner_subject_id").notNull(),
2489
+ browserInstanceId: text5("browser_instance_id").notNull(),
2490
+ ownerKeyHash: text5("owner_key_hash").notNull(),
2491
+ model: text5("model").notNull(),
2492
+ state: text5("state").notNull().default("active"),
2493
+ version: integer5("version").notNull().default(1),
2494
+ connectionEpoch: integer5("connection_epoch").notNull().default(1),
2495
+ leaseExpiresAt: timestamp5("lease_expires_at", { withTimezone: true }).notNull(),
2496
+ lastHeartbeatAt: timestamp5("last_heartbeat_at", { withTimezone: true }).notNull(),
2497
+ startedAt: timestamp5("started_at", { withTimezone: true }).notNull().defaultNow(),
2498
+ endedAt: timestamp5("ended_at", { withTimezone: true }),
2499
+ endReason: text5("end_reason"),
2500
+ // The rolling migration owns this forward reference. End commits at most
2501
+ // one canonical transcript-tail Steer and binds its audit projection here.
2502
+ contextProjectionId: uuid5("context_projection_id"),
2503
+ contextProjectedAt: timestamp5("context_projected_at", { withTimezone: true }),
2504
+ createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2505
+ updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2506
+ },
2507
+ (table) => ({
2508
+ workspaceAccount: foreignKey({
2509
+ name: "session_realtime_modes_workspace_account_fk",
2510
+ columns: [table.workspaceId, table.accountId],
2511
+ foreignColumns: [workspaces.id, workspaces.accountId]
2512
+ }).onDelete("cascade"),
2513
+ workspaceSession: foreignKey({
2514
+ name: "session_realtime_modes_workspace_session_fk",
2515
+ columns: [table.workspaceId, table.sessionId],
2516
+ foreignColumns: [sessions.workspaceId, sessions.id]
2517
+ }).onDelete("cascade"),
2518
+ operation: uniqueIndex5("session_realtime_modes_operation_uq").on(
2519
+ table.workspaceId,
2520
+ table.sessionId,
2521
+ table.operationId
2522
+ ),
2523
+ oneActive: uniqueIndex5("session_realtime_modes_one_active_uq").on(table.workspaceId, table.sessionId).where(sql5`${table.state} = 'active'`),
2524
+ activeLease: index5("session_realtime_modes_active_lease_idx").on(table.leaseExpiresAt, table.workspaceId, table.sessionId).where(sql5`${table.state} = 'active'`),
2525
+ stateValid: check4(
2526
+ "session_realtime_modes_state_check",
2527
+ sql5`${table.state} in ('active', 'ended')`
2528
+ ),
2529
+ modelValid: check4(
2530
+ "session_realtime_modes_model_check",
2531
+ sql5`${table.model} in (
2532
+ 'gpt-live-1-boulder-alpha',
2533
+ 'opengeni-gateway/openai/gpt-realtime-2.1',
2534
+ 'opengeni-gateway/openai/gpt-realtime-mini',
2535
+ 'opengeni-gateway/xai/grok-voice-think-fast-2.0',
2536
+ 'workspace-gateway/openai/gpt-realtime-2.1',
2537
+ 'workspace-gateway/openai/gpt-realtime-mini',
2538
+ 'workspace-gateway/xai/grok-voice-think-fast-2.0'
2539
+ )`
2540
+ ),
2541
+ endReasonValid: check4(
2542
+ "session_realtime_modes_end_reason_check",
2543
+ sql5`${table.endReason} is null or ${table.endReason} in ('user_stop', 'browser_unload', 'lease_expired')`
2544
+ ),
2545
+ versionValid: check4("session_realtime_modes_version_check", sql5`${table.version} >= 1`),
2546
+ epochValid: check4("session_realtime_modes_epoch_check", sql5`${table.connectionEpoch} >= 1`),
2547
+ ownerSubjectValid: check4(
2548
+ "session_realtime_modes_owner_subject_check",
2549
+ sql5`octet_length(${table.ownerSubjectId}) between 1 and 1024`
2550
+ ),
2551
+ browserInstanceValid: check4(
2552
+ "session_realtime_modes_browser_instance_check",
2553
+ sql5`octet_length(${table.browserInstanceId}) between 1 and 256`
2554
+ ),
2555
+ ownerKeyHashValid: check4(
2556
+ "session_realtime_modes_owner_key_hash_check",
2557
+ sql5`${table.ownerKeyHash} ~ '^[0-9a-f]{64}$'`
2558
+ ),
2559
+ leaseValid: check4(
2560
+ "session_realtime_modes_lease_check",
2561
+ sql5`${table.leaseExpiresAt} > ${table.lastHeartbeatAt}`
2562
+ ),
2563
+ terminalValid: check4(
2564
+ "session_realtime_modes_terminal_check",
2565
+ sql5`(${table.state} = 'active' and ${table.endedAt} is null and ${table.endReason} is null)
2566
+ or (${table.state} = 'ended' and ${table.endedAt} is not null and ${table.endReason} is not null)`
2567
+ )
2568
+ })
2569
+ );
2570
+ var sessionRealtimeConnections = pgTable5(
2571
+ "session_realtime_connections",
2572
+ {
2573
+ id: uuid5("id").primaryKey().defaultRandom(),
2574
+ accountId: uuid5("account_id").notNull(),
2575
+ workspaceId: uuid5("workspace_id").notNull(),
2576
+ sessionId: uuid5("session_id").notNull(),
2577
+ realtimeId: uuid5("realtime_id").notNull().references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
2578
+ operationId: uuid5("operation_id").notNull(),
2579
+ connectionEpoch: integer5("connection_epoch").notNull(),
2580
+ startupFenceSequence: integer5("startup_fence_sequence").notNull().default(0),
2581
+ promotionMode: text5("promotion_mode").notNull().default("legacy"),
2582
+ state: text5("state").notNull().default("negotiating"),
2583
+ sdpAnswer: text5("sdp_answer"),
2584
+ failureCode: text5("failure_code"),
2585
+ providerSessionId: text5("provider_session_id"),
2586
+ startupEventId: text5("startup_event_id"),
2587
+ startupAcknowledgedAt: timestamp5("startup_acknowledged_at", { withTimezone: true }),
2588
+ negotiatedAt: timestamp5("negotiated_at", { withTimezone: true }),
2589
+ closedAt: timestamp5("closed_at", { withTimezone: true }),
2590
+ createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2591
+ updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2592
+ },
2593
+ (table) => ({
2594
+ workspaceAccount: foreignKey({
2595
+ name: "session_realtime_connections_workspace_account_fk",
2596
+ columns: [table.workspaceId, table.accountId],
2597
+ foreignColumns: [workspaces.id, workspaces.accountId]
2598
+ }).onDelete("cascade"),
2599
+ workspaceSession: foreignKey({
2600
+ name: "session_realtime_connections_workspace_session_fk",
2601
+ columns: [table.workspaceId, table.sessionId],
2602
+ foreignColumns: [sessions.workspaceId, sessions.id]
2603
+ }).onDelete("cascade"),
2604
+ operation: uniqueIndex5("session_realtime_connections_operation_uq").on(
2605
+ table.realtimeId,
2606
+ table.operationId
2607
+ ),
2608
+ epoch: uniqueIndex5("session_realtime_connections_epoch_uq").on(
2609
+ table.realtimeId,
2610
+ table.connectionEpoch
2611
+ ),
2612
+ oneActive: uniqueIndex5("session_realtime_connections_one_active_uq").on(table.realtimeId).where(
2613
+ sql5`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active'))
2614
+ or (${table.promotionMode} = 'staged' and ${table.state} = 'active')`
2615
+ ),
2616
+ onePreparing: uniqueIndex5("session_realtime_connections_one_preparing_uq").on(table.realtimeId).where(
2617
+ sql5`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active'))
2618
+ or (${table.promotionMode} = 'staged' and ${table.state} in ('negotiating', 'ready'))`
2619
+ ),
2620
+ epochValid: check4(
2621
+ "session_realtime_connections_epoch_check",
2622
+ sql5`${table.connectionEpoch} >= 1`
2623
+ ),
2624
+ startupFenceValid: check4(
2625
+ "session_realtime_connections_startup_fence_check",
2626
+ sql5`${table.startupFenceSequence} >= 0`
2627
+ ),
2628
+ promotionModeValid: check4(
2629
+ "session_realtime_connections_promotion_mode_check",
2630
+ sql5`${table.promotionMode} in ('legacy', 'staged')`
2631
+ ),
2632
+ stateValid: check4(
2633
+ "session_realtime_connections_state_check",
2634
+ sql5`${table.state} in ('negotiating', 'ready', 'active', 'failed', 'closed')`
2635
+ ),
2636
+ sdpValid: check4(
2637
+ "session_realtime_connections_sdp_check",
2638
+ sql5`${table.sdpAnswer} is null or octet_length(${table.sdpAnswer}) between 1 and 1048576`
2639
+ ),
2640
+ failureValid: check4(
2641
+ "session_realtime_connections_failure_check",
2642
+ sql5`${table.failureCode} is null or octet_length(${table.failureCode}) between 1 and 128`
2643
+ ),
2644
+ providerSessionValid: check4(
2645
+ "session_realtime_connections_provider_session_check",
2646
+ sql5`${table.providerSessionId} is null or octet_length(${table.providerSessionId}) between 1 and 1024`
2647
+ ),
2648
+ startupEventValid: check4(
2649
+ "session_realtime_connections_startup_event_check",
2650
+ sql5`${table.startupEventId} is null or octet_length(${table.startupEventId}) between 1 and 1024`
2651
+ ),
2652
+ startupAckValid: check4(
2653
+ "session_realtime_connections_startup_ack_check",
2654
+ sql5`(${table.startupAcknowledgedAt} is null and ${table.providerSessionId} is null and ${table.startupEventId} is null)
2655
+ or (${table.startupAcknowledgedAt} is not null and ${table.providerSessionId} is not null)`
2656
+ ),
2657
+ terminalValid: check4(
2658
+ "session_realtime_connections_terminal_check",
2659
+ sql5`(${table.state} = 'negotiating' and ${table.sdpAnswer} is null and ${table.failureCode} is null and ${table.negotiatedAt} is null and ${table.closedAt} is null)
2660
+ or (${table.state} = 'ready' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null)
2661
+ or (${table.state} = 'active' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null)
2662
+ or (${table.state} = 'failed' and ${table.sdpAnswer} is null and ${table.failureCode} is not null and ${table.closedAt} is not null)
2663
+ or (${table.state} = 'closed' and ${table.closedAt} is not null)`
2664
+ )
2665
+ })
2666
+ );
2667
+ var sessionRealtimeEntries = pgTable5(
2668
+ "session_realtime_entries",
2669
+ {
2670
+ id: uuid5("id").primaryKey().defaultRandom(),
2671
+ accountId: uuid5("account_id").notNull(),
2672
+ workspaceId: uuid5("workspace_id").notNull(),
2673
+ sessionId: uuid5("session_id").notNull(),
2674
+ realtimeId: uuid5("realtime_id").notNull().references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
2675
+ operationId: uuid5("operation_id").notNull(),
2676
+ connectionEpoch: integer5("connection_epoch").notNull(),
2677
+ sequence: integer5("sequence").notNull(),
2678
+ direction: text5("direction").notNull(),
2679
+ kind: text5("kind").notNull(),
2680
+ role: text5("role"),
2681
+ providerEventId: text5("provider_event_id"),
2682
+ delegationItemId: text5("delegation_item_id"),
2683
+ // The referenced tables are declared later in this schema module; the
2684
+ // rolling migration owns all three ON DELETE SET NULL foreign keys.
2685
+ sourceUpdateId: uuid5("source_update_id"),
2686
+ historyItemId: uuid5("history_item_id"),
2687
+ // The rolling migration owns this ON DELETE SET NULL foreign key because
2688
+ // sessionTurns is declared later in this schema module. A non-null value
2689
+ // links the accepted provider call and its one terminal outbound
2690
+ // result/error to the same ordinary turn. It never denotes a child/fork
2691
+ // session.
2692
+ turnId: uuid5("turn_id"),
2693
+ text: text5("text"),
2694
+ payload: jsonb5("payload").$type().notNull().default({}),
2695
+ clientAckedAt: timestamp5("client_acked_at", { withTimezone: true }),
2696
+ providerAckedAt: timestamp5("provider_acked_at", { withTimezone: true }),
2697
+ createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2698
+ updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2699
+ },
2700
+ (table) => ({
2701
+ workspaceAccount: foreignKey({
2702
+ name: "session_realtime_entries_workspace_account_fk",
2703
+ columns: [table.workspaceId, table.accountId],
2704
+ foreignColumns: [workspaces.id, workspaces.accountId]
2705
+ }).onDelete("cascade"),
2706
+ workspaceSession: foreignKey({
2707
+ name: "session_realtime_entries_workspace_session_fk",
2708
+ columns: [table.workspaceId, table.sessionId],
2709
+ foreignColumns: [sessions.workspaceId, sessions.id]
2710
+ }).onDelete("cascade"),
2711
+ operation: uniqueIndex5("session_realtime_entries_operation_uq").on(
2712
+ table.realtimeId,
2713
+ table.operationId
2714
+ ),
2715
+ sequence: uniqueIndex5("session_realtime_entries_sequence_uq").on(
2716
+ table.realtimeId,
2717
+ table.sequence
2718
+ ),
2719
+ sourceUpdate: uniqueIndex5("session_realtime_entries_source_update_uq").on(table.realtimeId, table.sourceUpdateId).where(sql5`${table.sourceUpdateId} is not null`),
2720
+ delegationTurn: uniqueIndex5("session_realtime_entries_delegation_turn_uq").on(table.turnId).where(sql5`${table.kind} = 'delegation_call' and ${table.turnId} is not null`),
2721
+ delegationTerminal: uniqueIndex5("session_realtime_entries_delegation_terminal_uq").on(table.turnId).where(
2722
+ sql5`${table.direction} = 'provider_out' and ${table.kind} in ('delegation_result', 'error') and ${table.turnId} is not null`
2723
+ ),
2724
+ delegationCall: uniqueIndex5("session_realtime_entries_delegation_call_uq").on(table.realtimeId, table.delegationItemId).where(sql5`${table.kind} = 'delegation_call' and ${table.delegationItemId} is not null`),
2725
+ outboundPending: index5("session_realtime_entries_outbound_pending_idx").on(table.realtimeId, table.sequence).where(sql5`${table.direction} = 'provider_out' and ${table.providerAckedAt} is null`),
2726
+ epochValid: check4("session_realtime_entries_epoch_check", sql5`${table.connectionEpoch} >= 1`),
2727
+ sequenceValid: check4("session_realtime_entries_sequence_check", sql5`${table.sequence} >= 1`),
2728
+ directionValid: check4(
2729
+ "session_realtime_entries_direction_check",
2730
+ sql5`${table.direction} in ('provider_in', 'provider_out')`
2731
+ ),
2732
+ kindValid: check4(
2733
+ "session_realtime_entries_kind_check",
2734
+ sql5`${table.kind} in ('user_transcript', 'assistant_transcript', 'delegation_call', 'delegation_progress', 'delegation_result', 'interruption', 'session_update', 'error')`
2735
+ ),
2736
+ roleValid: check4(
2737
+ "session_realtime_entries_role_check",
2738
+ sql5`${table.role} is null or ${table.role} in ('user', 'assistant')`
2739
+ ),
2740
+ providerEventValid: check4(
2741
+ "session_realtime_entries_provider_event_check",
2742
+ sql5`${table.providerEventId} is null or octet_length(${table.providerEventId}) between 1 and 1024`
2743
+ ),
2744
+ delegationItemValid: check4(
2745
+ "session_realtime_entries_delegation_item_check",
2746
+ sql5`${table.delegationItemId} is null or octet_length(${table.delegationItemId}) between 1 and 1024`
2747
+ ),
2748
+ textValid: check4(
2749
+ "session_realtime_entries_text_check",
2750
+ sql5`${table.text} is null or octet_length(${table.text}) <= 131072`
2751
+ ),
2752
+ payloadValid: check4(
2753
+ "session_realtime_entries_payload_check",
2754
+ sql5`octet_length(${table.payload}::text) <= 131072`
2755
+ ),
2756
+ turnValid: check4(
2757
+ "session_realtime_entries_turn_check",
2758
+ sql5`${table.turnId} is null
2759
+ or (${table.kind} = 'delegation_call' and ${table.direction} = 'provider_in')
2760
+ or (${table.kind} in ('delegation_progress', 'delegation_result', 'error') and ${table.direction} = 'provider_out')`
2761
+ ),
2762
+ transcriptValid: check4(
2763
+ "session_realtime_entries_transcript_check",
2764
+ sql5`(${table.kind} = 'user_transcript' and ${table.role} = 'user' and ${table.text} is not null)
2765
+ or (${table.kind} = 'assistant_transcript' and ${table.role} = 'assistant' and ${table.text} is not null)
2766
+ or (${table.kind} not in ('user_transcript', 'assistant_transcript') and ${table.role} is null)`
2767
+ )
2768
+ })
2769
+ );
2436
2770
  var sessionSpawnDenials = pgTable5(
2437
2771
  "session_spawn_denials",
2438
2772
  {
@@ -2441,10 +2775,10 @@ var sessionSpawnDenials = pgTable5(
2441
2775
  workspaceId: uuid5("workspace_id").notNull(),
2442
2776
  parentSessionId: uuid5("parent_session_id"),
2443
2777
  rootSessionId: uuid5("root_session_id"),
2444
- currentDepth: integer4("current_depth").notNull(),
2778
+ currentDepth: integer5("current_depth").notNull(),
2445
2779
  attemptedDepth: bigint4("attempted_depth", { mode: "number" }).notNull(),
2446
- effectiveMaxNestedAgentDepth: integer4("effective_max_nested_agent_depth").notNull(),
2447
- requestedMaxNestedAgentDepthOverride: integer4("requested_max_nested_agent_depth_override"),
2780
+ effectiveMaxNestedAgentDepth: integer5("effective_max_nested_agent_depth").notNull(),
2781
+ requestedMaxNestedAgentDepthOverride: integer5("requested_max_nested_agent_depth_override"),
2448
2782
  policySource: text5("policy_source").notNull(),
2449
2783
  policySessionId: uuid5("policy_session_id"),
2450
2784
  subjectId: text5("subject_id"),
@@ -2488,7 +2822,7 @@ var sessionPins = pgTable5(
2488
2822
  // unpin+re-pin that would otherwise recreate version 1.
2489
2823
  pinned: boolean3("pinned").notNull().default(true),
2490
2824
  pinnedAt: timestamp5("pinned_at", { withTimezone: true }).defaultNow(),
2491
- version: integer4("version").notNull().default(1)
2825
+ version: integer5("version").notNull().default(1)
2492
2826
  },
2493
2827
  (table) => ({
2494
2828
  subjectNonempty: check4(
@@ -2573,19 +2907,19 @@ var sessionMcpServers = pgTable5(
2573
2907
  serverId: text5("server_id").notNull(),
2574
2908
  name: text5("name"),
2575
2909
  url: text5("url").notNull(),
2576
- allowedTools: jsonb4("allowed_tools").$type(),
2577
- timeoutMs: integer4("timeout_ms"),
2910
+ allowedTools: jsonb5("allowed_tools").$type(),
2911
+ timeoutMs: integer5("timeout_ms"),
2578
2912
  cacheToolsList: boolean3("cache_tools_list").notNull().default(false),
2579
2913
  // Human-approval policy: `true` = every tool requires approval, a string[] of
2580
2914
  // UNPREFIXED tool names = only those require it, null/absent = auto-run.
2581
- requireApproval: jsonb4("require_approval").$type(),
2915
+ requireApproval: jsonb5("require_approval").$type(),
2582
2916
  // Non-secret pointer resolved at request time by the standalone broker or
2583
2917
  // an embedding host. Unlike headersEncrypted, this is safe to project.
2584
- connectionRef: jsonb4("connection_ref").$type(),
2918
+ connectionRef: jsonb5("connection_ref").$type(),
2585
2919
  // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
2586
2920
  // worker's run-preparation path and never returned by API helpers.
2587
- headersEncrypted: jsonb4("headers_encrypted").$type().notNull().default({}),
2588
- credentialVersion: integer4("credential_version").notNull().default(1),
2921
+ headersEncrypted: jsonb5("headers_encrypted").$type().notNull().default({}),
2922
+ credentialVersion: integer5("credential_version").notNull().default(1),
2589
2923
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2590
2924
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2591
2925
  },
@@ -2670,7 +3004,7 @@ var documents = pgTable5(
2670
3004
  status: text5("status").notNull().default("queued"),
2671
3005
  title: text5("title").notNull(),
2672
3006
  parser: text5("parser").notNull().default("liteparse"),
2673
- chunkCount: integer4("chunk_count").notNull().default(0),
3007
+ chunkCount: integer5("chunk_count").notNull().default(0),
2674
3008
  error: text5("error"),
2675
3009
  sourceKind: text5("source_kind").notNull().default("manual_upload"),
2676
3010
  sourceUri: text5("source_uri"),
@@ -2680,7 +3014,7 @@ var documents = pgTable5(
2680
3014
  sourceCreatedAt: timestamp5("source_created_at", { withTimezone: true }),
2681
3015
  sourceUpdatedAt: timestamp5("source_updated_at", { withTimezone: true }),
2682
3016
  sourceVersion: text5("source_version"),
2683
- aclTags: jsonb4("acl_tags").$type().notNull().default([]),
3017
+ aclTags: jsonb5("acl_tags").$type().notNull().default([]),
2684
3018
  // Per-document access controls. visibility 'private' restricts human reads to
2685
3019
  // created_by (a grant subject id, not a uuid); agent_access=false hides the
2686
3020
  // document from agent retrieval surfaces (docs MCP) while humans keep REST.
@@ -2689,9 +3023,9 @@ var documents = pgTable5(
2689
3023
  agentAccess: boolean3("agent_access").notNull().default(true),
2690
3024
  // Auto-curation output (knowledge drops).
2691
3025
  summary: text5("summary"),
2692
- topics: jsonb4("topics").$type().notNull().default([]),
3026
+ topics: jsonb5("topics").$type().notNull().default([]),
2693
3027
  curationStatus: text5("curation_status").notNull().default("none"),
2694
- curation: jsonb4("curation").$type(),
3028
+ curation: jsonb5("curation").$type(),
2695
3029
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
2696
3030
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
2697
3031
  },
@@ -2746,9 +3080,9 @@ var documentChunks = pgTable5(
2746
3080
  documentId: uuid5("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
2747
3081
  baseId: uuid5("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
2748
3082
  fileId: uuid5("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
2749
- chunkIndex: integer4("chunk_index").notNull(),
3083
+ chunkIndex: integer5("chunk_index").notNull(),
2750
3084
  text: text5("text").notNull(),
2751
- metadata: jsonb4("metadata").$type().notNull().default({}),
3085
+ metadata: jsonb5("metadata").$type().notNull().default({}),
2752
3086
  embedding: vector("embedding").notNull(),
2753
3087
  embeddingModel: text5("embedding_model").notNull(),
2754
3088
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
@@ -2772,9 +3106,9 @@ var knowledgeMemories = pgTable5(
2772
3106
  kind: text5("kind").notNull().default("semantic"),
2773
3107
  scope: text5("scope").notNull().default("workspace"),
2774
3108
  text: text5("text").notNull(),
2775
- sourceRefs: jsonb4("source_refs").$type().notNull().default([]),
2776
- confidence: integer4("confidence").notNull().default(50),
2777
- metadata: jsonb4("metadata").$type().notNull().default({}),
3109
+ sourceRefs: jsonb5("source_refs").$type().notNull().default([]),
3110
+ confidence: integer5("confidence").notNull().default(50),
3111
+ metadata: jsonb5("metadata").$type().notNull().default({}),
2778
3112
  createdBySessionId: uuid5("created_by_session_id").references(() => sessions.id, {
2779
3113
  onDelete: "set null"
2780
3114
  }),
@@ -2785,7 +3119,7 @@ var knowledgeMemories = pgTable5(
2785
3119
  embedding: vector("embedding"),
2786
3120
  embeddingModel: text5("embedding_model"),
2787
3121
  pinned: boolean3("pinned").notNull().default(false),
2788
- usageCount: integer4("usage_count").notNull().default(0),
3122
+ usageCount: integer5("usage_count").notNull().default(0),
2789
3123
  lastUsedAt: timestamp5("last_used_at", { withTimezone: true }),
2790
3124
  // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
2791
3125
  // NULL); declared here as plain columns like the migration-only composite FK.
@@ -2801,10 +3135,10 @@ var knowledgeMemories = pgTable5(
2801
3135
  scopeSessionId: uuid5("scope_session_id"),
2802
3136
  namespace: text5("namespace_key").notNull().default("general"),
2803
3137
  labels: text5("labels").array().notNull().default([]),
2804
- memoryVersion: integer4("memory_version").notNull().default(1),
3138
+ memoryVersion: integer5("memory_version").notNull().default(1),
2805
3139
  createdByKind: text5("created_by_kind").notNull().default("service"),
2806
3140
  createdBySubjectId: text5("created_by_subject_id").notNull().default("unattributed-legacy"),
2807
- createdByContext: jsonb4("created_by_context").$type().notNull().default({ backfill: true }),
3141
+ createdByContext: jsonb5("created_by_context").$type().notNull().default({ backfill: true }),
2808
3142
  // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
2809
3143
  textHash: text5("text_hash"),
2810
3144
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -2872,8 +3206,8 @@ var sessionTurns = pgTable5(
2872
3206
  // Host context for this exact turn. System-level at runtime and deliberately
2873
3207
  // separate from the visible prompt/event payload.
2874
3208
  turnInstructions: text5("turn_instructions"),
2875
- resources: jsonb4("resources").$type().notNull().default([]),
2876
- tools: jsonb4("tools").$type().notNull().default([]),
3209
+ resources: jsonb5("resources").$type().notNull().default([]),
3210
+ tools: jsonb5("tools").$type().notNull().default([]),
2877
3211
  // false = inherit the durable session policy; true = this turn explicitly
2878
3212
  // replaces it with `tools` after the core subset fence.
2879
3213
  toolsProvided: boolean3("tools_provided").notNull().default(false),
@@ -2885,30 +3219,35 @@ var sessionTurns = pgTable5(
2885
3219
  // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
2886
3220
  // constrained to the SandboxOs enum (or NULL) in migration 0018.
2887
3221
  sandboxOs: text5("sandbox_os"),
2888
- metadata: jsonb4("metadata").$type().notNull().default({}),
2889
- version: integer4("version").notNull().default(1),
2890
- executionGeneration: integer4("execution_generation").notNull().default(0),
3222
+ metadata: jsonb5("metadata").$type().notNull().default({}),
3223
+ version: integer5("version").notNull().default(1),
3224
+ executionGeneration: integer5("execution_generation").notNull().default(0),
2891
3225
  // Composite FK to session_turn_attempts is installed by migration 0063.
2892
3226
  // It lives in SQL because attempts carry the reciprocal turn FK and because
2893
3227
  // the claim transaction preallocates this ID before inserting the attempt;
2894
3228
  // the SQL constraint is therefore DEFERRABLE INITIALLY DEFERRED.
2895
3229
  activeAttemptId: uuid5("active_attempt_id"),
2896
- lineage: jsonb4("lineage").$type().notNull().default({}),
3230
+ lineage: jsonb5("lineage").$type().notNull().default({}),
2897
3231
  // Required immutable authority captured when the turn is accepted. These
2898
3232
  // columns are deliberately outside mutable metadata/lineage.
2899
3233
  initiatorKind: text5("initiator_kind").notNull().default("service"),
2900
3234
  initiatorSubjectId: text5("initiator_subject_id").notNull().default("unattributed-legacy"),
2901
- initiatorContext: jsonb4("initiator_context").$type().notNull().default({ backfill: true }),
3235
+ initiatorContext: jsonb5("initiator_context").$type().notNull().default({ backfill: true }),
3236
+ // Immutable human authority for exact-attempt governance. Human turns bind
3237
+ // their own subject; trusted continuations/compactions may inherit the
3238
+ // causal turn's value while retaining a service initiator. Null means the
3239
+ // turn has no human preference authority.
3240
+ initiatingHumanSubjectId: text5("initiating_human_subject_id"),
2902
3241
  // Immutable exact personal MCP authority for this logical turn. Recovery,
2903
3242
  // approval, retries, and Toolspace reuse this row; no runtime may infer
2904
3243
  // broader authority from the session creator or mutable session state.
2905
- personalConnectionDelegations: jsonb4("personal_connection_delegations").$type().notNull().default([]),
3244
+ personalConnectionDelegations: jsonb5("personal_connection_delegations").$type().notNull().default([]),
2906
3245
  cancelledBy: text5("cancelled_by"),
2907
3246
  cancelReason: text5("cancel_reason"),
2908
3247
  // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
2909
3248
  // by a single conditional UPDATE at tools/call time; the row lock serializes
2910
3249
  // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
2911
- toolspaceCallCount: integer4("toolspace_call_count").notNull().default(0),
3250
+ toolspaceCallCount: integer5("toolspace_call_count").notNull().default(0),
2912
3251
  startedAt: timestamp5("started_at", { withTimezone: true }),
2913
3252
  finishedAt: timestamp5("finished_at", { withTimezone: true }),
2914
3253
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -2932,6 +3271,58 @@ var sessionTurns = pgTable5(
2932
3271
  )
2933
3272
  })
2934
3273
  );
3274
+ var sessionRealtimeContextProjections = pgTable5(
3275
+ "session_realtime_context_projections",
3276
+ {
3277
+ id: uuid5("id").primaryKey().defaultRandom(),
3278
+ accountId: uuid5("account_id").notNull(),
3279
+ workspaceId: uuid5("workspace_id").notNull(),
3280
+ sessionId: uuid5("session_id").notNull(),
3281
+ turnId: uuid5("turn_id").notNull(),
3282
+ context: text5("context"),
3283
+ sourceModeCount: integer5("source_mode_count").notNull(),
3284
+ sourceEntryCount: integer5("source_entry_count").notNull(),
3285
+ includedEntryCount: integer5("included_entry_count").notNull(),
3286
+ omittedEntryCount: integer5("omitted_entry_count").notNull(),
3287
+ createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
3288
+ },
3289
+ (table) => ({
3290
+ workspaceAccount: foreignKey({
3291
+ name: "session_realtime_context_projections_workspace_account_fk",
3292
+ columns: [table.workspaceId, table.accountId],
3293
+ foreignColumns: [workspaces.id, workspaces.accountId]
3294
+ }).onDelete("cascade"),
3295
+ workspaceSession: foreignKey({
3296
+ name: "session_realtime_context_projections_workspace_session_fk",
3297
+ columns: [table.workspaceId, table.sessionId],
3298
+ foreignColumns: [sessions.workspaceId, sessions.id]
3299
+ }).onDelete("cascade"),
3300
+ workspaceTurn: foreignKey({
3301
+ name: "session_realtime_context_projections_workspace_turn_fk",
3302
+ columns: [table.workspaceId, table.turnId],
3303
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
3304
+ }).onDelete("cascade"),
3305
+ turn: uniqueIndex5("session_realtime_context_projections_turn_uq").on(
3306
+ table.workspaceId,
3307
+ table.sessionId,
3308
+ table.turnId
3309
+ ),
3310
+ contextValid: check4(
3311
+ "session_realtime_context_projections_context_check",
3312
+ sql5`${table.context} is null or octet_length(${table.context}) between 1 and 65536`
3313
+ ),
3314
+ countsValid: check4(
3315
+ "session_realtime_context_projections_counts_check",
3316
+ sql5`${table.sourceModeCount} >= 1
3317
+ and ${table.sourceEntryCount} >= 0
3318
+ and ${table.includedEntryCount} >= 0
3319
+ and ${table.omittedEntryCount} >= 0
3320
+ and ${table.includedEntryCount} + ${table.omittedEntryCount} = ${table.sourceEntryCount}
3321
+ and ((${table.sourceEntryCount} = 0 and ${table.context} is null)
3322
+ or (${table.sourceEntryCount} > 0 and ${table.context} is not null))`
3323
+ )
3324
+ })
3325
+ );
2935
3326
  var sessionTurnAttempts = pgTable5(
2936
3327
  "session_turn_attempts",
2937
3328
  {
@@ -2940,7 +3331,7 @@ var sessionTurnAttempts = pgTable5(
2940
3331
  workspaceId: uuid5("workspace_id").notNull(),
2941
3332
  sessionId: uuid5("session_id").notNull(),
2942
3333
  turnId: uuid5("turn_id").notNull(),
2943
- executionGeneration: integer4("execution_generation").notNull(),
3334
+ executionGeneration: integer5("execution_generation").notNull(),
2944
3335
  state: text5("state").notNull().default("claimed"),
2945
3336
  outcome: text5("outcome"),
2946
3337
  temporalWorkflowId: text5("temporal_workflow_id").notNull(),
@@ -2953,8 +3344,8 @@ var sessionTurnAttempts = pgTable5(
2953
3344
  mode: "number"
2954
3345
  }).notNull(),
2955
3346
  // Immutable policy snapshot captured under the session lock at claim.
2956
- mcpApprovalPolicies: jsonb4("mcp_approval_policies").$type().notNull(),
2957
- connectorActionPolicies: jsonb4("connector_action_policies").$type().notNull().default([]),
3347
+ mcpApprovalPolicies: jsonb5("mcp_approval_policies").$type().notNull(),
3348
+ connectorActionPolicies: jsonb5("connector_action_policies").$type().notNull().default([]),
2958
3349
  startedAt: timestamp5("started_at", { withTimezone: true }).notNull().defaultNow(),
2959
3350
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow(),
2960
3351
  closedAt: timestamp5("closed_at", { withTimezone: true }),
@@ -3034,20 +3425,20 @@ var connectorActionRequests = pgTable5(
3034
3425
  sessionId: uuid5("session_id").notNull(),
3035
3426
  turnId: uuid5("turn_id").notNull(),
3036
3427
  creationAttemptId: uuid5("creation_attempt_id").notNull(),
3037
- creationExecutionGeneration: integer4("creation_execution_generation").notNull(),
3428
+ creationExecutionGeneration: integer5("creation_execution_generation").notNull(),
3038
3429
  executionAttemptId: uuid5("execution_attempt_id"),
3039
- executionAttemptGeneration: integer4("execution_attempt_generation"),
3430
+ executionAttemptGeneration: integer5("execution_attempt_generation"),
3040
3431
  approvalId: text5("approval_id").notNull(),
3041
3432
  initiatorKind: text5("initiator_kind").$type().notNull(),
3042
3433
  initiatorSubjectId: text5("initiator_subject_id").notNull(),
3043
3434
  connectionId: text5("connection_id").notNull(),
3044
- connectionVersion: integer4("connection_version"),
3435
+ connectionVersion: integer5("connection_version"),
3045
3436
  serverId: text5("server_id").notNull(),
3046
3437
  toolName: text5("tool_name").notNull(),
3047
3438
  actionName: text5("action_name").notNull(),
3048
3439
  // Attempt-frozen provenance intentionally survives policy deletion.
3049
3440
  policyId: uuid5("policy_id"),
3050
- policyVersion: integer4("policy_version"),
3441
+ policyVersion: integer5("policy_version"),
3051
3442
  policySource: text5("policy_source").$type().notNull(),
3052
3443
  policyDecision: text5("policy_decision").$type().notNull(),
3053
3444
  actionFingerprint: text5("action_fingerprint").notNull(),
@@ -3144,10 +3535,10 @@ var sessionCommandReceipts = pgTable5(
3144
3535
  appliedControlRevision: bigint4("applied_control_revision", {
3145
3536
  mode: "number"
3146
3537
  }),
3147
- appliedQueueVersion: integer4("applied_queue_version"),
3148
- appliedTurnVersion: integer4("applied_turn_version"),
3538
+ appliedQueueVersion: integer5("applied_queue_version"),
3539
+ appliedTurnVersion: integer5("applied_turn_version"),
3149
3540
  appliedDraftRevision: bigint4("applied_draft_revision", { mode: "number" }),
3150
- result: jsonb4("result").$type().notNull().default({}),
3541
+ result: jsonb5("result").$type().notNull().default({}),
3151
3542
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
3152
3543
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
3153
3544
  },
@@ -3208,11 +3599,11 @@ var workspaceControlEvents = pgTable5(
3208
3599
  action: text5("action").notNull(),
3209
3600
  automatic: boolean3("automatic").notNull().default(false),
3210
3601
  reason: text5("reason"),
3211
- reasonOriginalBytes: integer4("reason_original_bytes"),
3602
+ reasonOriginalBytes: integer5("reason_original_bytes"),
3212
3603
  actor: text5("actor").notNull(),
3213
3604
  // Null is the rolling-upgrade shape for untouched, already-bounded legacy
3214
3605
  // rows. New writes and rewritten poison rows carry exact source byte facts.
3215
- actorOriginalBytes: integer4("actor_original_bytes"),
3606
+ actorOriginalBytes: integer5("actor_original_bytes"),
3216
3607
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull().defaultNow()
3217
3608
  },
3218
3609
  (table) => ({
@@ -3305,14 +3696,14 @@ var composerDrafts = pgTable5(
3305
3696
  subjectId: text5("subject_id").notNull(),
3306
3697
  revision: bigint4("revision", { mode: "number" }).notNull().default(1),
3307
3698
  text: text5("text").notNull().default(""),
3308
- resources: jsonb4("resources").$type().notNull().default([]),
3309
- tools: jsonb4("tools").$type().notNull().default([]),
3699
+ resources: jsonb5("resources").$type().notNull().default([]),
3700
+ tools: jsonb5("tools").$type().notNull().default([]),
3310
3701
  toolsProvided: boolean3("tools_provided").notNull().default(false),
3311
3702
  model: text5("model").notNull(),
3312
3703
  reasoningEffort: text5("reasoning_effort").notNull(),
3313
3704
  latencyMode: text5("latency_mode").notNull().default("standard"),
3314
3705
  sourceTurnId: uuid5("source_turn_id"),
3315
- sourceTurnVersion: integer4("source_turn_version"),
3706
+ sourceTurnVersion: integer5("source_turn_version"),
3316
3707
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
3317
3708
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
3318
3709
  },
@@ -3357,12 +3748,12 @@ var newSessionDrafts = pgTable5(
3357
3748
  subjectId: text5("subject_id").notNull(),
3358
3749
  revision: bigint4("revision", { mode: "number" }).notNull().default(1),
3359
3750
  text: text5("text").notNull().default(""),
3360
- resources: jsonb4("resources").$type().notNull().default([]),
3361
- tools: jsonb4("tools").$type().notNull().default([]),
3751
+ resources: jsonb5("resources").$type().notNull().default([]),
3752
+ tools: jsonb5("tools").$type().notNull().default([]),
3362
3753
  model: text5("model").notNull(),
3363
3754
  reasoningEffort: text5("reasoning_effort").notNull(),
3364
3755
  latencyMode: text5("latency_mode").notNull().default("standard"),
3365
- sessionOptions: jsonb4("session_options").$type().notNull().default({}),
3756
+ sessionOptions: jsonb5("session_options").$type().notNull().default({}),
3366
3757
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
3367
3758
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
3368
3759
  },
@@ -3399,11 +3790,11 @@ var sessionSystemUpdates = pgTable5(
3399
3790
  sourceId: text5("source_id").notNull(),
3400
3791
  dedupeKey: text5("dedupe_key").notNull(),
3401
3792
  summary: text5("summary").notNull(),
3402
- payload: jsonb4("payload").$type().notNull().default({}),
3403
- lineage: jsonb4("lineage").$type().notNull().default({}),
3793
+ payload: jsonb5("payload").$type().notNull().default({}),
3794
+ lineage: jsonb5("lineage").$type().notNull().default({}),
3404
3795
  // Private immutable authority frozen when this machine input is accepted.
3405
3796
  // Public projections intentionally omit connection ids and owner subjects.
3406
- personalConnectionDelegations: jsonb4("personal_connection_delegations").$type().notNull().default([]),
3797
+ personalConnectionDelegations: jsonb5("personal_connection_delegations").$type().notNull().default([]),
3407
3798
  // pending is visible queue truth; delivered means its exact model-memory
3408
3799
  // batch was durably claimed. Terminal cancellation/supersession is explicit.
3409
3800
  state: text5("state").notNull().default("pending"),
@@ -3464,13 +3855,13 @@ var sessionSystemUpdateOutbox = pgTable5(
3464
3855
  classification: text5("classification").notNull(),
3465
3856
  sourceId: text5("source_id").notNull(),
3466
3857
  summary: text5("summary").notNull(),
3467
- payload: jsonb4("payload").$type().notNull().default({}),
3468
- lineage: jsonb4("lineage").$type().notNull().default({}),
3858
+ payload: jsonb5("payload").$type().notNull().default({}),
3859
+ lineage: jsonb5("lineage").$type().notNull().default({}),
3469
3860
  // Exact private authority copied from the causal parent turn in the source
3470
3861
  // terminal transaction. Delivery retries cannot replace this snapshot.
3471
- personalConnectionDelegations: jsonb4("personal_connection_delegations").$type().notNull().default([]),
3862
+ personalConnectionDelegations: jsonb5("personal_connection_delegations").$type().notNull().default([]),
3472
3863
  status: text5("status").notNull().default("pending"),
3473
- attempts: integer4("attempts").notNull().default(0),
3864
+ attempts: integer5("attempts").notNull().default(0),
3474
3865
  updateId: uuid5("update_id"),
3475
3866
  lastError: text5("last_error"),
3476
3867
  deliveredAt: timestamp5("delivered_at", { withTimezone: true }),
@@ -3503,7 +3894,7 @@ var sessionWorkflowWakeOutbox = pgTable5(
3503
3894
  wakeRevision: bigint4("wake_revision", { mode: "number" }).notNull().default(1),
3504
3895
  deliveredRevision: bigint4("delivered_revision", { mode: "number" }).notNull().default(0),
3505
3896
  reason: text5("reason").notNull(),
3506
- attempts: integer4("attempts").notNull().default(0),
3897
+ attempts: integer5("attempts").notNull().default(0),
3507
3898
  nextAttemptAt: timestamp5("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
3508
3899
  lastError: text5("last_error"),
3509
3900
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -3554,27 +3945,23 @@ var sessionGoals = pgTable5(
3554
3945
  // agent | user_pause | api | no_progress | max_auto_continuations | limits
3555
3946
  createdBy: text5("created_by").notNull().default("api"),
3556
3947
  // api | agent | scheduled_task
3557
- version: integer4("version").notNull().default(1),
3948
+ version: integer5("version").notNull().default(1),
3558
3949
  // bumped on every set/update; progress signal
3559
- autoContinuations: integer4("auto_continuations").notNull().default(0),
3560
- noProgressStreak: integer4("no_progress_streak").notNull().default(0),
3561
- maxAutoContinuations: integer4("max_auto_continuations"),
3950
+ autoContinuations: integer5("auto_continuations").notNull().default(0),
3951
+ noProgressStreak: integer5("no_progress_streak").notNull().default(0),
3952
+ maxAutoContinuations: integer5("max_auto_continuations"),
3562
3953
  // per-goal override; a configured settings cap (if any) remains the hard ceiling
3563
3954
  lastContinuationTurnId: uuid5("last_continuation_turn_id"),
3564
- versionAtLastContinuation: integer4("version_at_last_continuation"),
3955
+ versionAtLastContinuation: integer5("version_at_last_continuation"),
3565
3956
  // Postgres owns the continuation obligation. Terminal settlement advances
3566
3957
  // wakeRevision in the same transaction that makes the session idle;
3567
3958
  // materialization advances observedRevision only alongside the one typed
3568
3959
  // update, timeline events, usage row, and workflow-wake outbox row.
3569
3960
  // Temporal signals and workflow history are replaceable nudges over these
3570
3961
  // monotonic revisions.
3571
- continuationWakeRevision: bigint4("continuation_wake_revision", {
3572
- mode: "number"
3573
- }).notNull().default(0),
3574
- continuationObservedRevision: bigint4("continuation_observed_revision", {
3575
- mode: "number"
3576
- }).notNull().default(0),
3577
- metadata: jsonb4("metadata").$type().notNull().default({}),
3962
+ continuationWakeRevision: bigint4("continuation_wake_revision", { mode: "number" }).notNull().default(0),
3963
+ continuationObservedRevision: bigint4("continuation_observed_revision", { mode: "number" }).notNull().default(0),
3964
+ metadata: jsonb5("metadata").$type().notNull().default({}),
3578
3965
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
3579
3966
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
3580
3967
  },
@@ -3603,23 +3990,23 @@ var codexCapacityWaiters = pgTable5(
3603
3990
  sessionId: uuid5("session_id").notNull(),
3604
3991
  goalId: uuid5("goal_id"),
3605
3992
  blockedTurnId: uuid5("blocked_turn_id").notNull(),
3606
- blockedTurnGeneration: integer4("blocked_turn_generation").notNull(),
3993
+ blockedTurnGeneration: integer5("blocked_turn_generation").notNull(),
3607
3994
  workflowId: text5("workflow_id").notNull(),
3608
- generation: integer4("generation").notNull().default(1),
3995
+ generation: integer5("generation").notNull().default(1),
3609
3996
  status: text5("status").notNull().default("waiting"),
3610
3997
  // waiting | resumed | superseded
3611
- goalVersion: integer4("goal_version"),
3998
+ goalVersion: integer5("goal_version"),
3612
3999
  policyHash: text5("policy_hash"),
3613
4000
  earliestResetAt: timestamp5("earliest_reset_at", { withTimezone: true }),
3614
4001
  nextCheckAt: timestamp5("next_check_at", { withTimezone: true }).notNull(),
3615
4002
  resetKind: text5("reset_kind").notNull(),
3616
4003
  // authoritative | bounded_refresh
3617
- refreshAttempt: integer4("refresh_attempt").notNull().default(0),
4004
+ refreshAttempt: integer5("refresh_attempt").notNull().default(0),
3618
4005
  // Coalescing outbox generation. Every eligibility-affecting mutation bumps
3619
4006
  // wakeRevision. Duplicate/lost Temporal signals are harmless because only
3620
4007
  // the row-locked evaluator moves observedWakeRevision and may enqueue work.
3621
- wakeRevision: integer4("wake_revision").notNull().default(1),
3622
- observedWakeRevision: integer4("observed_wake_revision").notNull().default(0),
4008
+ wakeRevision: integer5("wake_revision").notNull().default(1),
4009
+ observedWakeRevision: integer5("observed_wake_revision").notNull().default(0),
3623
4010
  lastWakeReason: text5("last_wake_reason").notNull().default("capacity_wait_armed"),
3624
4011
  resumedUpdateId: uuid5("resumed_update_id"),
3625
4012
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -3654,17 +4041,17 @@ var sessionEvents = pgTable5(
3654
4041
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3655
4042
  sessionId: uuid5("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3656
4043
  turnId: uuid5("turn_id"),
3657
- turnGeneration: integer4("turn_generation"),
4044
+ turnGeneration: integer5("turn_generation"),
3658
4045
  turnAttemptId: uuid5("turn_attempt_id"),
3659
4046
  turnAssociation: text5("turn_association"),
3660
4047
  duplicateOfEventId: uuid5("duplicate_of_event_id"),
3661
4048
  duplicateReason: text5("duplicate_reason"),
3662
- sequence: integer4("sequence").notNull(),
4049
+ sequence: integer5("sequence").notNull(),
3663
4050
  type: text5("type").notNull(),
3664
- payload: jsonb4("payload").$type().notNull().default({}),
4051
+ payload: jsonb5("payload").$type().notNull().default({}),
3665
4052
  clientEventId: text5("client_event_id"),
3666
4053
  producerId: text5("producer_id"),
3667
- producerSeq: integer4("producer_seq"),
4054
+ producerSeq: integer5("producer_seq"),
3668
4055
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull().defaultNow(),
3669
4056
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
3670
4057
  },
@@ -3730,9 +4117,9 @@ var agentRunStates = pgTable5("agent_run_states", {
3730
4117
  turnId: uuid5("turn_id").references(() => sessionTurns.id, {
3731
4118
  onDelete: "set null"
3732
4119
  }),
3733
- stateVersion: integer4("state_version").notNull(),
4120
+ stateVersion: integer5("state_version").notNull(),
3734
4121
  serializedRunState: text5("serialized_run_state").notNull(),
3735
- pendingApprovals: jsonb4("pending_approvals").$type().notNull().default([]),
4122
+ pendingApprovals: jsonb5("pending_approvals").$type().notNull().default([]),
3736
4123
  // The Codex account that FROZE this run state: the turn's resolved codex
3737
4124
  // credential id (pin > workspace-active), or NULL when frozen on the
3738
4125
  // non-codex / Azure path (or before this column existed). The serialized
@@ -3767,13 +4154,13 @@ var sessionHumanInputRequests = pgTable5(
3767
4154
  workspaceId: uuid5("workspace_id").notNull(),
3768
4155
  sessionId: uuid5("session_id").notNull(),
3769
4156
  turnId: uuid5("turn_id").notNull(),
3770
- turnGeneration: integer4("turn_generation").notNull(),
4157
+ turnGeneration: integer5("turn_generation").notNull(),
3771
4158
  creationAttemptId: uuid5("creation_attempt_id").notNull(),
3772
4159
  toolCallId: text5("tool_call_id").notNull(),
3773
4160
  status: text5("status").notNull().default("pending"),
3774
- questions: jsonb4("questions").$type().notNull(),
4161
+ questions: jsonb5("questions").$type().notNull(),
3775
4162
  allowSkip: boolean3("allow_skip").notNull().default(false),
3776
- response: jsonb4("response").$type(),
4163
+ response: jsonb5("response").$type(),
3777
4164
  respondedBy: text5("responded_by"),
3778
4165
  respondedAt: timestamp5("responded_at", { withTimezone: true }),
3779
4166
  expiresAt: timestamp5("expires_at", { withTimezone: true }),
@@ -3849,7 +4236,7 @@ var sessionHistoryItems = pgTable5(
3849
4236
  // positions; only the summary uses the half-step. `mode: "number"` maps the
3850
4237
  // postgres.js string back to a JS number so every reader stays numeric.
3851
4238
  position: numeric("position", { mode: "number" }).notNull(),
3852
- item: jsonb4("item").$type().notNull(),
4239
+ item: jsonb5("item").$type().notNull(),
3853
4240
  // Live-row flag for client-side context compaction. The read path selects
3854
4241
  // only active rows; a compaction supersedes the summarized prefix (sets this
3855
4242
  // false — never deletes, so the full transcript stays as an audit trail) and
@@ -3895,13 +4282,13 @@ var sessionPendingToolCalls = pgTable5(
3895
4282
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3896
4283
  sessionId: uuid5("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3897
4284
  turnId: uuid5("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
3898
- executionGeneration: integer4("execution_generation").notNull(),
4285
+ executionGeneration: integer5("execution_generation").notNull(),
3899
4286
  attemptId: uuid5("attempt_id").notNull(),
3900
4287
  callId: text5("call_id").notNull(),
3901
4288
  callType: text5("call_type").notNull(),
3902
- callItem: jsonb4("call_item").$type().notNull(),
3903
- modelToolOutputTruncationTokens: integer4("model_tool_output_truncation_tokens"),
3904
- resultItem: jsonb4("result_item").$type(),
4289
+ callItem: jsonb5("call_item").$type().notNull(),
4290
+ modelToolOutputTruncationTokens: integer5("model_tool_output_truncation_tokens"),
4291
+ resultItem: jsonb5("result_item").$type(),
3905
4292
  resultRecordedAt: timestamp5("result_recorded_at", { withTimezone: true }),
3906
4293
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
3907
4294
  },
@@ -3930,7 +4317,7 @@ var sandboxSessionEnvelopes = pgTable5(
3930
4317
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3931
4318
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3932
4319
  sessionId: uuid5("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3933
- envelope: jsonb4("envelope").$type().notNull(),
4320
+ envelope: jsonb5("envelope").$type().notNull(),
3934
4321
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
3935
4322
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
3936
4323
  },
@@ -3958,27 +4345,27 @@ var sandboxCheckpointArtifacts = pgTable5(
3958
4345
  workspaceId: uuid5("workspace_id").notNull(),
3959
4346
  sandboxGroupId: uuid5("sandbox_group_id").notNull(),
3960
4347
  sourceLeaseId: uuid5("source_lease_id").notNull(),
3961
- sourceLeaseEpoch: integer4("source_lease_epoch").notNull(),
4348
+ sourceLeaseEpoch: integer5("source_lease_epoch").notNull(),
3962
4349
  sourceInstanceId: text5("source_instance_id"),
3963
- sourceWorkspaceGeneration: integer4("source_workspace_generation"),
4350
+ sourceWorkspaceGeneration: integer5("source_workspace_generation"),
3964
4351
  provenance: text5("provenance", {
3965
4352
  enum: ["native_capture", "legacy_provider_adopted"]
3966
4353
  }).notNull(),
3967
4354
  providerBackend: text5("provider_backend").notNull(),
3968
4355
  providerBindingKey: text5("provider_binding_key").notNull(),
3969
- providerBinding: jsonb4("provider_binding").$type().notNull(),
4356
+ providerBinding: jsonb5("provider_binding").$type().notNull(),
3970
4357
  objectKind: text5("object_kind", {
3971
4358
  enum: ["modal_filesystem_snapshot", "modal_directory_snapshot"]
3972
4359
  }).notNull(),
3973
4360
  objectId: text5("object_id").notNull(),
3974
4361
  archiveBase64: text5("archive_base64").notNull(),
3975
4362
  archiveSha256: text5("archive_sha256").notNull(),
3976
- archiveBytes: integer4("archive_bytes").notNull(),
3977
- descriptor: jsonb4("descriptor").$type().notNull(),
4363
+ archiveBytes: integer5("archive_bytes").notNull(),
4364
+ descriptor: jsonb5("descriptor").$type().notNull(),
3978
4365
  descriptorRevision: text5("descriptor_revision").notNull(),
3979
4366
  state: text5("state", { enum: sandboxCheckpointArtifactStateValues }).notNull().default("candidate"),
3980
4367
  deleteAfter: timestamp5("delete_after", { withTimezone: true }),
3981
- deleteAttempts: integer4("delete_attempts").notNull().default(0),
4368
+ deleteAttempts: integer5("delete_attempts").notNull().default(0),
3982
4369
  deleteClaimId: uuid5("delete_claim_id"),
3983
4370
  deleteClaimedAt: timestamp5("delete_claimed_at", { withTimezone: true }),
3984
4371
  lastDeleteError: text5("last_delete_error"),
@@ -4066,9 +4453,9 @@ var sandboxLeases = pgTable5(
4066
4453
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4067
4454
  sandboxGroupId: uuid5("sandbox_group_id").notNull(),
4068
4455
  liveness: text5("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
4069
- refcount: integer4("refcount").notNull().default(0),
4070
- turnHolders: integer4("turn_holders").notNull().default(0),
4071
- viewerHolders: integer4("viewer_holders").notNull().default(0),
4456
+ refcount: integer5("refcount").notNull().default(0),
4457
+ turnHolders: integer5("turn_holders").notNull().default(0),
4458
+ viewerHolders: integer5("viewer_holders").notNull().default(0),
4072
4459
  instanceId: text5("instance_id"),
4073
4460
  backend: text5("backend").notNull(),
4074
4461
  os: text5("os").notNull().default("linux"),
@@ -4098,21 +4485,21 @@ var sandboxLeases = pgTable5(
4098
4485
  // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
4099
4486
  // was always-true → every turn fenced); int4 returns a JS number, the fix.
4100
4487
  // Epochs never approach 2^31, so the narrower type loses nothing.
4101
- leaseEpoch: integer4("lease_epoch").notNull().default(0),
4488
+ leaseEpoch: integer5("lease_epoch").notNull().default(0),
4102
4489
  // Monotonic mutation intent for the live workspace. Every acknowledged
4103
4490
  // filesystem-writing operation advances this under the exact lease epoch +
4104
4491
  // provider-instance fence BEFORE it reaches the provider. A verified
4105
4492
  // archive fold copies the exact captured value into archive_generation in
4106
4493
  // the same row update; equality is the only durable completeness proof.
4107
- workspaceGeneration: integer4("workspace_generation").notNull().default(0),
4108
- archiveGeneration: integer4("archive_generation"),
4494
+ workspaceGeneration: integer5("workspace_generation").notNull().default(0),
4495
+ archiveGeneration: integer5("archive_generation"),
4109
4496
  // Provider-native capture may pause the live box. The exact claim is
4110
4497
  // acquired before provider I/O and cleared only after that capture settles;
4111
4498
  // new holders and workspace mutations fence on it. The SQL constraint also
4112
4499
  // requires the claimed generation to remain current, so an unaware writer
4113
4500
  // cannot advance generation through an active capture.
4114
4501
  archiveCaptureId: uuid5("archive_capture_id"),
4115
- archiveCaptureGeneration: integer4("archive_capture_generation"),
4502
+ archiveCaptureGeneration: integer5("archive_capture_generation"),
4116
4503
  archiveCaptureStartedAt: timestamp5("archive_capture_started_at", {
4117
4504
  withTimezone: true
4118
4505
  }),
@@ -4122,12 +4509,12 @@ var sandboxLeases = pgTable5(
4122
4509
  // The group box-envelope (the "envelope split" Critical): the small recovery
4123
4510
  // descriptor to resume()-by-id the group's box without a per-session join.
4124
4511
  resumeBackendId: text5("resume_backend_id"),
4125
- resumeState: jsonb4("resume_state").$type(),
4512
+ resumeState: jsonb5("resume_state").$type(),
4126
4513
  // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
4127
4514
  // idempotency tick (warm_seconds accrued idempotent on
4128
4515
  // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
4129
4516
  lastMeterAt: timestamp5("last_meter_at", { withTimezone: true }),
4130
- lastMeterTick: integer4("last_meter_tick").notNull().default(0),
4517
+ lastMeterTick: integer5("last_meter_tick").notNull().default(0),
4131
4518
  providerCreatedAt: timestamp5("provider_created_at", { withTimezone: true }),
4132
4519
  providerDeadlineAt: timestamp5("provider_deadline_at", {
4133
4520
  withTimezone: true
@@ -4221,9 +4608,7 @@ var sandboxLeaseHolders = pgTable5(
4221
4608
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4222
4609
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4223
4610
  leaseId: uuid5("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
4224
- kind: text5("kind", {
4225
- enum: ["turn", "viewer", "direct", "process"]
4226
- }).notNull(),
4611
+ kind: text5("kind", { enum: ["turn", "viewer", "direct", "process"] }).notNull(),
4227
4612
  holderId: text5("holder_id").notNull(),
4228
4613
  // The attributing session within the (possibly shared) group.
4229
4614
  subjectId: uuid5("subject_id"),
@@ -4256,20 +4641,18 @@ var sandboxWorkspaceMutationAdmissions = pgTable5(
4256
4641
  leaseId: uuid5("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
4257
4642
  sandboxGroupId: uuid5("sandbox_group_id").notNull(),
4258
4643
  sessionId: uuid5("session_id").notNull(),
4259
- actorKind: text5("actor_kind", {
4260
- enum: sandboxWorkspaceMutationActorKindValues
4261
- }).notNull(),
4644
+ actorKind: text5("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues }).notNull(),
4262
4645
  actorId: uuid5("actor_id").notNull(),
4263
4646
  // Exact turn authority is present only for actor_kind='turn'. Direct HTTP
4264
4647
  // requests and retained processes never invent a turn or quiescence owner.
4265
4648
  turnId: uuid5("turn_id"),
4266
4649
  attemptId: uuid5("attempt_id"),
4267
- executionGeneration: integer4("execution_generation"),
4650
+ executionGeneration: integer5("execution_generation"),
4268
4651
  holderKind: text5("holder_kind", {
4269
4652
  enum: sandboxWorkspaceMutationHolderKindValues
4270
4653
  }).notNull(),
4271
4654
  holderId: text5("holder_id").notNull(),
4272
- leaseEpoch: integer4("lease_epoch").notNull(),
4655
+ leaseEpoch: integer5("lease_epoch").notNull(),
4273
4656
  providerBackend: text5("provider_backend").notNull(),
4274
4657
  providerInstanceId: text5("provider_instance_id").notNull(),
4275
4658
  routeKind: text5("route_kind", { enum: ["home", "active"] }).notNull(),
@@ -4277,8 +4660,8 @@ var sandboxWorkspaceMutationAdmissions = pgTable5(
4277
4660
  // target is pinned together with the active pointer epoch observed when the
4278
4661
  // operation was admitted.
4279
4662
  routeTargetId: uuid5("route_target_id"),
4280
- routeEpoch: integer4("route_epoch").notNull(),
4281
- workspaceGeneration: integer4("workspace_generation").notNull(),
4663
+ routeEpoch: integer5("route_epoch").notNull(),
4664
+ workspaceGeneration: integer5("workspace_generation").notNull(),
4282
4665
  operation: text5("operation").notNull(),
4283
4666
  providerOutcome: text5("provider_outcome", {
4284
4667
  enum: ["resolved", "rejected", "retained"]
@@ -4396,27 +4779,25 @@ var sandboxRetainedProcesses = pgTable5(
4396
4779
  sandboxGroupId: uuid5("sandbox_group_id").notNull(),
4397
4780
  parentAdmissionId: uuid5("parent_admission_id").notNull(),
4398
4781
  holderId: text5("holder_id").notNull(),
4399
- ownerActorKind: text5("owner_actor_kind", {
4400
- enum: ["turn", "direct"]
4401
- }).notNull(),
4782
+ ownerActorKind: text5("owner_actor_kind", { enum: ["turn", "direct"] }).notNull(),
4402
4783
  ownerActorId: uuid5("owner_actor_id").notNull(),
4403
4784
  ownerTurnId: uuid5("owner_turn_id"),
4404
4785
  ownerAttemptId: uuid5("owner_attempt_id"),
4405
- ownerExecutionGeneration: integer4("owner_execution_generation"),
4406
- leaseEpoch: integer4("lease_epoch").notNull(),
4786
+ ownerExecutionGeneration: integer5("owner_execution_generation"),
4787
+ leaseEpoch: integer5("lease_epoch").notNull(),
4407
4788
  providerBackend: text5("provider_backend").notNull(),
4408
4789
  providerInstanceId: text5("provider_instance_id").notNull(),
4409
4790
  // Provider object ids are namespace-scoped. New Modal processes bind the
4410
4791
  // exact authenticated workspace before execution; legacy rows remain null
4411
4792
  // until a positive lookup proves which namespace owns the historical box.
4412
4793
  providerBindingKey: text5("provider_binding_key"),
4413
- providerBinding: jsonb4("provider_binding").$type(),
4794
+ providerBinding: jsonb5("provider_binding").$type(),
4414
4795
  routeKind: text5("route_kind", { enum: ["home", "active"] }).notNull(),
4415
4796
  routeTargetId: uuid5("route_target_id"),
4416
- routeEpoch: integer4("route_epoch").notNull(),
4417
- providerSessionId: integer4("provider_session_id").notNull(),
4797
+ routeEpoch: integer5("route_epoch").notNull(),
4798
+ providerSessionId: integer5("provider_session_id").notNull(),
4418
4799
  state: text5("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"),
4419
- exitCode: integer4("exit_code"),
4800
+ exitCode: integer5("exit_code"),
4420
4801
  settlementReason: text5("settlement_reason"),
4421
4802
  startedAt: timestamp5("started_at", { withTimezone: true }).notNull().defaultNow(),
4422
4803
  settledAt: timestamp5("settled_at", { withTimezone: true }),
@@ -4426,19 +4807,13 @@ var sandboxRetainedProcesses = pgTable5(
4426
4807
  // never exit/loss proof.
4427
4808
  reconcileAfter: timestamp5("reconcile_after", { withTimezone: true }).notNull().defaultNow(),
4428
4809
  reconcileClaimId: uuid5("reconcile_claim_id"),
4429
- reconcileClaimedAt: timestamp5("reconcile_claimed_at", {
4430
- withTimezone: true
4431
- }),
4432
- reconcileAttempts: integer4("reconcile_attempts").notNull().default(0),
4810
+ reconcileClaimedAt: timestamp5("reconcile_claimed_at", { withTimezone: true }),
4811
+ reconcileAttempts: integer5("reconcile_attempts").notNull().default(0),
4433
4812
  lastReconcileOutcome: text5("last_reconcile_outcome"),
4434
- reconcileProofOutcome: text5("reconcile_proof_outcome", {
4435
- enum: ["exited", "lost"]
4436
- }),
4437
- reconcileProofExitCode: integer4("reconcile_proof_exit_code"),
4813
+ reconcileProofOutcome: text5("reconcile_proof_outcome", { enum: ["exited", "lost"] }),
4814
+ reconcileProofExitCode: integer5("reconcile_proof_exit_code"),
4438
4815
  reconcileProofReason: text5("reconcile_proof_reason"),
4439
- reconcileProofObservedAt: timestamp5("reconcile_proof_observed_at", {
4440
- withTimezone: true
4441
- })
4816
+ reconcileProofObservedAt: timestamp5("reconcile_proof_observed_at", { withTimezone: true })
4442
4817
  },
4443
4818
  (table) => ({
4444
4819
  workspaceAccount: foreignKey({
@@ -4614,8 +4989,8 @@ var sessionRecordings = pgTable5(
4614
4989
  storageKey: text5("storage_key"),
4615
4990
  sizeBytes: bigint4("size_bytes", { mode: "number" }),
4616
4991
  durationSeconds: numeric("duration_seconds").$type(),
4617
- width: integer4("width").notNull(),
4618
- height: integer4("height").notNull(),
4992
+ width: integer5("width").notNull(),
4993
+ height: integer5("height").notNull(),
4619
4994
  reason: text5("reason"),
4620
4995
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
4621
4996
  finalizedAt: timestamp5("finalized_at", { withTimezone: true })
@@ -4639,7 +5014,7 @@ var workspaceCaptures = pgTable5(
4639
5014
  onDelete: "set null"
4640
5015
  }),
4641
5016
  revision: bigint4("revision", { mode: "number" }).notNull(),
4642
- leaseEpoch: integer4("lease_epoch").notNull(),
5017
+ leaseEpoch: integer5("lease_epoch").notNull(),
4643
5018
  // 'available' on a committed capture. 'failed' reserved for a future two-phase
4644
5019
  // write; the current synchronous capture only ever inserts 'available'.
4645
5020
  state: text5("state", { enum: ["available", "failed"] }).notNull().default("available"),
@@ -4649,9 +5024,9 @@ var workspaceCaptures = pgTable5(
4649
5024
  // or sign it independently of the (usually small) manifest metadata.
4650
5025
  treeIndexKey: text5("tree_index_key"),
4651
5026
  // Content-addressed after-image blob keys this revision references (GC input).
4652
- blobKeys: jsonb4("blob_keys").$type().notNull().default([]),
5027
+ blobKeys: jsonb5("blob_keys").$type().notNull().default([]),
4653
5028
  sizeBytes: bigint4("size_bytes", { mode: "number" }),
4654
- stats: jsonb4("stats").$type().notNull().default({}),
5029
+ stats: jsonb5("stats").$type().notNull().default({}),
4655
5030
  capturedAt: timestamp5("captured_at", { withTimezone: true }).notNull().defaultNow()
4656
5031
  },
4657
5032
  (table) => ({
@@ -4679,15 +5054,15 @@ var sandboxPtySessions = pgTable5(
4679
5054
  retainedProcessId: uuid5("retained_process_id"),
4680
5055
  openAdmissionId: uuid5("open_admission_id"),
4681
5056
  // Copied provider locator for the adopted retained process.
4682
- execSessionId: integer4("exec_session_id"),
4683
- leaseEpoch: integer4("lease_epoch").notNull(),
5057
+ execSessionId: integer5("exec_session_id"),
5058
+ leaseEpoch: integer5("lease_epoch").notNull(),
4684
5059
  providerBackend: text5("provider_backend"),
4685
5060
  providerInstanceId: text5("provider_instance_id"),
4686
5061
  routeKind: text5("route_kind", { enum: ["home", "active"] }),
4687
5062
  routeTargetId: uuid5("route_target_id"),
4688
- routeEpoch: integer4("route_epoch"),
4689
- cols: integer4("cols").notNull(),
4690
- rows: integer4("rows").notNull(),
5063
+ routeEpoch: integer5("route_epoch"),
5064
+ cols: integer5("cols").notNull(),
5065
+ rows: integer5("rows").notNull(),
4691
5066
  shell: text5("shell").notNull(),
4692
5067
  cwd: text5("cwd").notNull(),
4693
5068
  status: text5("status").notNull().default("open"),
@@ -4943,15 +5318,15 @@ var scheduledTasks = pgTable5(
4943
5318
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4944
5319
  name: text5("name").notNull(),
4945
5320
  status: text5("status").notNull().default("active"),
4946
- schedule: jsonb4("schedule").$type().notNull(),
5321
+ schedule: jsonb5("schedule").$type().notNull(),
4947
5322
  temporalScheduleId: text5("temporal_schedule_id").notNull(),
4948
5323
  runMode: text5("run_mode").notNull().default("new_session_per_run"),
4949
5324
  overlapPolicy: text5("overlap_policy").notNull().default("allow_concurrent"),
4950
- agentConfig: jsonb4("agent_config").$type().notNull(),
5325
+ agentConfig: jsonb5("agent_config").$type().notNull(),
4951
5326
  createdByKind: text5("created_by_kind").notNull().default("service"),
4952
5327
  createdBySubjectId: text5("created_by_subject_id").notNull().default("unattributed-legacy"),
4953
- createdByContext: jsonb4("created_by_context").$type().notNull().default({ backfill: true }),
4954
- personalConnectionDelegations: jsonb4("personal_connection_delegations").$type().notNull().default([]),
5328
+ createdByContext: jsonb5("created_by_context").$type().notNull().default({ backfill: true }),
5329
+ personalConnectionDelegations: jsonb5("personal_connection_delegations").$type().notNull().default([]),
4955
5330
  reusableSessionId: uuid5("reusable_session_id").references(() => sessions.id, {
4956
5331
  onDelete: "set null"
4957
5332
  }),
@@ -4962,7 +5337,7 @@ var scheduledTasks = pgTable5(
4962
5337
  // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
4963
5338
  // in migration 0047 (forward-reference pattern). Consumed in M3.
4964
5339
  rigId: uuid5("rig_id"),
4965
- metadata: jsonb4("metadata").$type().notNull().default({}),
5340
+ metadata: jsonb5("metadata").$type().notNull().default({}),
4966
5341
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
4967
5342
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
4968
5343
  },
@@ -5019,7 +5394,7 @@ var githubInstallations = pgTable5(
5019
5394
  id: uuid5("id").primaryKey().defaultRandom(),
5020
5395
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5021
5396
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5022
- installationId: integer4("installation_id").notNull(),
5397
+ installationId: integer5("installation_id").notNull(),
5023
5398
  githubAccountId: bigint4("github_account_id", { mode: "number" }),
5024
5399
  accountLogin: text5("account_login"),
5025
5400
  accountType: text5("account_type"),
@@ -5028,12 +5403,8 @@ var githubInstallations = pgTable5(
5028
5403
  githubActorId: bigint4("github_actor_id", { mode: "number" }),
5029
5404
  githubActorLogin: text5("github_actor_login"),
5030
5405
  authorityKind: text5("authority_kind"),
5031
- authorityCheckedAt: timestamp5("authority_checked_at", {
5032
- withTimezone: true
5033
- }),
5034
- authorityExpiresAt: timestamp5("authority_expires_at", {
5035
- withTimezone: true
5036
- }),
5406
+ authorityCheckedAt: timestamp5("authority_checked_at", { withTimezone: true }),
5407
+ authorityExpiresAt: timestamp5("authority_expires_at", { withTimezone: true }),
5037
5408
  authorityNonce: text5("authority_nonce"),
5038
5409
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
5039
5410
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -5104,7 +5475,7 @@ var githubInstallationRepositories = pgTable5(
5104
5475
  id: uuid5("id").primaryKey().defaultRandom(),
5105
5476
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5106
5477
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5107
- installationId: integer4("installation_id").notNull(),
5478
+ installationId: integer5("installation_id").notNull(),
5108
5479
  repositoryId: bigint4("repository_id", { mode: "number" }).notNull(),
5109
5480
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
5110
5481
  },
@@ -5151,7 +5522,7 @@ var usageEvents = pgTable5(
5151
5522
  turnAttemptId: uuid5("turn_attempt_id"),
5152
5523
  initiatorKind: text5("initiator_kind"),
5153
5524
  initiatorSubjectId: text5("initiator_subject_id"),
5154
- initiatorContext: jsonb4("initiator_context").$type().notNull().default({}),
5525
+ initiatorContext: jsonb5("initiator_context").$type().notNull().default({}),
5155
5526
  origin: text5("origin"),
5156
5527
  idempotencyKey: text5("idempotency_key").notNull(),
5157
5528
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull(),
@@ -5290,7 +5661,7 @@ var modelCallFacts = pgTable5(
5290
5661
  var hostExportConfig = pgTable5(
5291
5662
  "host_export_config",
5292
5663
  {
5293
- id: integer4("id").primaryKey().default(1),
5664
+ id: integer5("id").primaryKey().default(1),
5294
5665
  sessionEventsEnabled: boolean3("session_events_enabled").notNull().default(false),
5295
5666
  usageEventsEnabled: boolean3("usage_events_enabled").notNull().default(false),
5296
5667
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -5311,24 +5682,22 @@ var hostExportOutbox = pgTable5(
5311
5682
  sessionId: uuid5("session_id"),
5312
5683
  rootSessionId: uuid5("root_session_id"),
5313
5684
  turnId: uuid5("turn_id"),
5314
- turnGeneration: integer4("turn_generation"),
5685
+ turnGeneration: integer5("turn_generation"),
5315
5686
  turnAttemptId: uuid5("turn_attempt_id"),
5316
- sessionSequence: integer4("session_sequence"),
5687
+ sessionSequence: integer5("session_sequence"),
5317
5688
  clientEventId: text5("client_event_id"),
5318
5689
  turnAssociation: text5("turn_association"),
5319
5690
  duplicateOfEventId: uuid5("duplicate_of_event_id"),
5320
5691
  duplicateReason: text5("duplicate_reason"),
5321
5692
  eventType: text5("event_type").notNull(),
5322
5693
  idempotencyKey: text5("idempotency_key").notNull(),
5323
- initiator: jsonb4("initiator").$type(),
5324
- initiatorContext: jsonb4("initiator_context").$type().notNull().default({}),
5694
+ initiator: jsonb5("initiator").$type(),
5695
+ initiatorContext: jsonb5("initiator_context").$type().notNull().default({}),
5325
5696
  origin: text5("origin"),
5326
- payload: jsonb4("payload").$type().notNull(),
5327
- envelopeBytes: integer4("envelope_bytes").notNull(),
5697
+ payload: jsonb5("payload").$type().notNull(),
5698
+ envelopeBytes: integer5("envelope_bytes").notNull(),
5328
5699
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull(),
5329
- sourceRecordedAt: timestamp5("source_recorded_at", {
5330
- withTimezone: true
5331
- }).notNull(),
5700
+ sourceRecordedAt: timestamp5("source_recorded_at", { withTimezone: true }).notNull(),
5332
5701
  enqueuedAt: timestamp5("enqueued_at", { withTimezone: true }).notNull()
5333
5702
  },
5334
5703
  (table) => ({
@@ -5389,7 +5758,7 @@ var hostExportConsumers = pgTable5(
5389
5758
  leaseExpiresAt: timestamp5("lease_expires_at", { withTimezone: true }),
5390
5759
  leaseFrom: bigint4("lease_from", { mode: "bigint" }),
5391
5760
  leaseThrough: bigint4("lease_through", { mode: "bigint" }),
5392
- consecutiveFailures: integer4("consecutive_failures").notNull().default(0),
5761
+ consecutiveFailures: integer5("consecutive_failures").notNull().default(0),
5393
5762
  nextAttemptAt: timestamp5("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
5394
5763
  lastError: text5("last_error"),
5395
5764
  lastErrorAt: timestamp5("last_error_at", { withTimezone: true }),
@@ -5423,7 +5792,7 @@ var hostExportDeadLetters = pgTable5(
5423
5792
  exportCursor: bigint4("export_cursor", { mode: "bigint" }).notNull(),
5424
5793
  sourceId: uuid5("source_id").notNull(),
5425
5794
  reason: text5("reason").notNull(),
5426
- envelope: jsonb4("envelope").$type().notNull(),
5795
+ envelope: jsonb5("envelope").$type().notNull(),
5427
5796
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
5428
5797
  },
5429
5798
  (table) => ({
@@ -5460,7 +5829,7 @@ var creditLedgerEntries = pgTable5(
5460
5829
  sourceType: text5("source_type"),
5461
5830
  sourceId: text5("source_id"),
5462
5831
  idempotencyKey: text5("idempotency_key").notNull(),
5463
- metadata: jsonb4("metadata").$type().notNull().default({}),
5832
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5464
5833
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull().defaultNow(),
5465
5834
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
5466
5835
  },
@@ -5498,7 +5867,7 @@ var stripeWebhookEvents = pgTable5("stripe_webhook_events", {
5498
5867
  id: text5("id").primaryKey(),
5499
5868
  type: text5("type").notNull(),
5500
5869
  livemode: text5("livemode").notNull().default("false"),
5501
- payload: jsonb4("payload").$type().notNull(),
5870
+ payload: jsonb5("payload").$type().notNull(),
5502
5871
  processedAt: timestamp5("processed_at", { withTimezone: true }),
5503
5872
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
5504
5873
  });
@@ -5516,7 +5885,7 @@ var auditEvents = pgTable5(
5516
5885
  action: text5("action").notNull(),
5517
5886
  targetType: text5("target_type"),
5518
5887
  targetId: text5("target_id"),
5519
- metadata: jsonb4("metadata").$type().notNull().default({}),
5888
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5520
5889
  occurredAt: timestamp5("occurred_at", { withTimezone: true }).notNull().defaultNow()
5521
5890
  },
5522
5891
  (table) => ({
@@ -5535,7 +5904,7 @@ var packInstallations = pgTable5(
5535
5904
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5536
5905
  packId: text5("pack_id").notNull(),
5537
5906
  status: text5("status").notNull().default("active"),
5538
- metadata: jsonb4("metadata").$type().notNull().default({}),
5907
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5539
5908
  enabledAt: timestamp5("enabled_at", { withTimezone: true }).notNull().defaultNow(),
5540
5909
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5541
5910
  },
@@ -5554,7 +5923,7 @@ var workspacePacks = pgTable5(
5554
5923
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5555
5924
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5556
5925
  packId: text5("pack_id").notNull(),
5557
- manifest: jsonb4("manifest").$type().notNull(),
5926
+ manifest: jsonb5("manifest").$type().notNull(),
5558
5927
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
5559
5928
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5560
5929
  },
@@ -5573,12 +5942,12 @@ var importBatches = pgTable5(
5573
5942
  snapshotDate: timestamp5("snapshot_date", { withTimezone: true }).notNull(),
5574
5943
  snapshotRef: text5("snapshot_ref"),
5575
5944
  attributionNote: text5("attribution_note").notNull(),
5576
- importedCount: integer4("imported_count").notNull().default(0),
5577
- skippedCount: integer4("skipped_count").notNull().default(0),
5578
- quarantinedCount: integer4("quarantined_count").notNull().default(0),
5579
- logoFailureCount: integer4("logo_failure_count").notNull().default(0),
5580
- staleCount: integer4("stale_count").notNull().default(0),
5581
- details: jsonb4("details").$type().notNull().default({}),
5945
+ importedCount: integer5("imported_count").notNull().default(0),
5946
+ skippedCount: integer5("skipped_count").notNull().default(0),
5947
+ quarantinedCount: integer5("quarantined_count").notNull().default(0),
5948
+ logoFailureCount: integer5("logo_failure_count").notNull().default(0),
5949
+ staleCount: integer5("stale_count").notNull().default(0),
5950
+ details: jsonb5("details").$type().notNull().default({}),
5582
5951
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
5583
5952
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5584
5953
  },
@@ -5605,7 +5974,7 @@ var capabilityCatalogItems = pgTable5(
5605
5974
  name: text5("name").notNull(),
5606
5975
  description: text5("description"),
5607
5976
  category: text5("category").notNull().default("custom"),
5608
- tags: jsonb4("tags").$type().notNull().default([]),
5977
+ tags: jsonb5("tags").$type().notNull().default([]),
5609
5978
  homepageUrl: text5("homepage_url"),
5610
5979
  endpointUrl: text5("endpoint_url"),
5611
5980
  installUrl: text5("install_url"),
@@ -5615,7 +5984,7 @@ var capabilityCatalogItems = pgTable5(
5615
5984
  transport: text5("transport"),
5616
5985
  mcpUrl: text5("mcp_url"),
5617
5986
  authKind: text5("auth_kind"),
5618
- credentialFacts: jsonb4("credential_facts").$type().notNull().default([]),
5987
+ credentialFacts: jsonb5("credential_facts").$type().notNull().default([]),
5619
5988
  tier: text5("tier"),
5620
5989
  provenance: text5("provenance"),
5621
5990
  logoAssetPath: text5("logo_asset_path"),
@@ -5624,7 +5993,7 @@ var capabilityCatalogItems = pgTable5(
5624
5993
  }),
5625
5994
  stale: boolean3("stale").notNull().default(false),
5626
5995
  staleAt: timestamp5("stale_at", { withTimezone: true }),
5627
- metadata: jsonb4("metadata").$type().notNull().default({}),
5996
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5628
5997
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
5629
5998
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5630
5999
  },
@@ -5662,8 +6031,8 @@ var capabilityInstallations = pgTable5(
5662
6031
  capabilityId: text5("capability_id").notNull(),
5663
6032
  kind: text5("kind").notNull(),
5664
6033
  status: text5("status").notNull().default("active"),
5665
- config: jsonb4("config").$type().notNull().default({}),
5666
- metadata: jsonb4("metadata").$type().notNull().default({}),
6034
+ config: jsonb5("config").$type().notNull().default({}),
6035
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5667
6036
  enabledAt: timestamp5("enabled_at", { withTimezone: true }).notNull().defaultNow(),
5668
6037
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5669
6038
  },
@@ -5690,14 +6059,14 @@ var socialConnections = pgTable5(
5690
6059
  accountName: text5("account_name"),
5691
6060
  externalAccountId: text5("external_account_id"),
5692
6061
  status: text5("status").notNull().default("connected"),
5693
- scopes: jsonb4("scopes").$type().notNull().default([]),
6062
+ scopes: jsonb5("scopes").$type().notNull().default([]),
5694
6063
  credentialRef: text5("credential_ref"),
5695
6064
  // AES-256-GCM envelope (environment-crypto v1 format) holding the OAuth
5696
6065
  // token bundle. Never exposed through contracts or MCP tools; only the
5697
6066
  // host-side social API client decrypts it.
5698
6067
  credentialEncrypted: text5("credential_encrypted"),
5699
- tokenMetadata: jsonb4("token_metadata").$type().notNull().default({}),
5700
- metadata: jsonb4("metadata").$type().notNull().default({}),
6068
+ tokenMetadata: jsonb5("token_metadata").$type().notNull().default({}),
6069
+ metadata: jsonb5("metadata").$type().notNull().default({}),
5701
6070
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
5702
6071
  updatedAt: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
5703
6072
  },
@@ -5727,8 +6096,8 @@ var socialPosts = pgTable5(
5727
6096
  authorHandle: text5("author_handle"),
5728
6097
  text: text5("text").notNull(),
5729
6098
  publishedAt: timestamp5("published_at", { withTimezone: true }).notNull(),
5730
- metrics: jsonb4("metrics").$type().notNull().default({}),
5731
- raw: jsonb4("raw").$type().notNull().default({}),
6099
+ metrics: jsonb5("metrics").$type().notNull().default({}),
6100
+ raw: jsonb5("raw").$type().notNull().default({}),
5732
6101
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow()
5733
6102
  },
5734
6103
  (table) => ({
@@ -5774,15 +6143,15 @@ var rigVersions = pgTable5(
5774
6143
  accountId: uuid5("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5775
6144
  workspaceId: uuid5("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5776
6145
  rigId: uuid5("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
5777
- version: integer4("version").notNull(),
6146
+ version: integer5("version").notNull(),
5778
6147
  image: text5("image"),
5779
6148
  setupScript: text5("setup_script"),
5780
6149
  // Self-declared health checks: [{ name, command }].
5781
- checks: jsonb4("checks").$type().notNull().default([]),
6150
+ checks: jsonb5("checks").$type().notNull().default([]),
5782
6151
  // Registered credential-hook names (resolved to hook implementations in M3).
5783
- credentialHooks: jsonb4("credential_hooks").$type().notNull().default([]),
6152
+ credentialHooks: jsonb5("credential_hooks").$type().notNull().default([]),
5784
6153
  // Variable-set ids layered below the session's variable set at run time (M3).
5785
- defaultVariableSetIds: jsonb4("default_variable_set_ids").$type().notNull().default([]),
6154
+ defaultVariableSetIds: jsonb5("default_variable_set_ids").$type().notNull().default([]),
5786
6155
  changelog: text5("changelog"),
5787
6156
  createdBy: text5("created_by"),
5788
6157
  active: boolean3("active").notNull().default(false),
@@ -5811,11 +6180,11 @@ var rigChanges = pgTable5(
5811
6180
  }),
5812
6181
  // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
5813
6182
  kind: text5("kind").notNull(),
5814
- payload: jsonb4("payload").$type().notNull(),
6183
+ payload: jsonb5("payload").$type().notNull(),
5815
6184
  // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
5816
6185
  status: text5("status").notNull().default("proposed"),
5817
6186
  proposedBy: text5("proposed_by"),
5818
- verification: jsonb4("verification").$type(),
6187
+ verification: jsonb5("verification").$type(),
5819
6188
  resultVersionId: uuid5("result_version_id").references(() => rigVersions.id, {
5820
6189
  onDelete: "set null"
5821
6190
  }),
@@ -5836,6 +6205,7 @@ export {
5836
6205
  workspaceInstructionPolicyRevisions,
5837
6206
  workspaceInstructionPolicyHeads,
5838
6207
  workspaceInstructionPolicyActivationEvents,
6208
+ workspaceInstructionPolicySnapshots,
5839
6209
  preferenceRegistryPreferences,
5840
6210
  preferenceRegistryRevisions,
5841
6211
  preferenceRegistryEvents,
@@ -5886,6 +6256,9 @@ export {
5886
6256
  workspaceModelPolicies,
5887
6257
  codexCredentialLeases,
5888
6258
  sessions,
6259
+ sessionRealtimeModes,
6260
+ sessionRealtimeConnections,
6261
+ sessionRealtimeEntries,
5889
6262
  sessionSpawnDenials,
5890
6263
  sessionPins,
5891
6264
  sessionListSnapshots,
@@ -5897,6 +6270,7 @@ export {
5897
6270
  documentChunks,
5898
6271
  knowledgeMemories,
5899
6272
  sessionTurns,
6273
+ sessionRealtimeContextProjections,
5900
6274
  sessionTurnAttempts,
5901
6275
  connectorActionRequests,
5902
6276
  sessionCommandReceipts,
@@ -5968,4 +6342,4 @@ export {
5968
6342
  rigChanges,
5969
6343
  schema_exports
5970
6344
  };
5971
- //# sourceMappingURL=chunk-CYGFLLMN.js.map
6345
+ //# sourceMappingURL=chunk-3UCHDMKG.js.map