@opengeni/db 0.36.1 → 3.1.0-canary.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 (274) hide show
  1. package/dist/attached-browser-devices.d.ts +7 -0
  2. package/dist/automations.d.ts +154 -0
  3. package/dist/canonical-human-identities.js +3 -3
  4. package/dist/capability-integrations.d.ts +13 -0
  5. package/dist/child-lifecycle-notices.d.ts +68 -0
  6. package/dist/{chunk-GYO7ED2Q.js → chunk-EULAN2NP.js} +2 -2
  7. package/dist/{chunk-VTPRIXKG.js → chunk-NJVZPWXY.js} +3 -3
  8. package/dist/{chunk-HSOWSYOX.js → chunk-NMUBV7Z5.js} +19 -11
  9. package/dist/chunk-NMUBV7Z5.js.map +1 -0
  10. package/dist/chunk-OF5OBB76.js +4457 -0
  11. package/dist/chunk-OF5OBB76.js.map +1 -0
  12. package/dist/{chunk-5KTIEDX7.js → chunk-PR2WMLOQ.js} +7714 -4443
  13. package/dist/chunk-PR2WMLOQ.js.map +1 -0
  14. package/dist/{chunk-Z7VYMNPZ.js → chunk-SCPUJS53.js} +41 -4
  15. package/dist/chunk-SCPUJS53.js.map +1 -0
  16. package/dist/{chunk-SK7YYHBI.js → chunk-SIBYBA2D.js} +46 -1
  17. package/dist/chunk-SIBYBA2D.js.map +1 -0
  18. package/dist/chunk-TIKF3KTI.js +383 -0
  19. package/dist/chunk-TIKF3KTI.js.map +1 -0
  20. package/dist/chunk-ZZ5LJEFX.js +516 -0
  21. package/dist/chunk-ZZ5LJEFX.js.map +1 -0
  22. package/dist/codemode-operations.d.ts +1 -6
  23. package/dist/company-brain-context-selection-schema.d.ts +705 -0
  24. package/dist/company-brain-context-selection.d.ts +94 -0
  25. package/dist/company-brain-governed-writes.d.ts +24 -0
  26. package/dist/company-brain.d.ts +55 -0
  27. package/dist/company-profile-agent-admin.d.ts +15 -0
  28. package/dist/company-profile-schema.d.ts +619 -2
  29. package/dist/company-profile.d.ts +9 -4
  30. package/dist/connection-authority.d.ts +95 -0
  31. package/dist/connection-scopes.d.ts +8 -0
  32. package/dist/connection-tenancy-backfill.d.ts +41 -0
  33. package/dist/connection-token-resolver.d.ts +30 -1
  34. package/dist/database.d.ts +19 -0
  35. package/dist/editable-artifact-durable-export.d.ts +10 -0
  36. package/dist/editable-artifact-durable-export.js +18 -3
  37. package/dist/editable-artifact-durable-export.js.map +1 -1
  38. package/dist/editable-artifacts.d.ts +2 -2
  39. package/dist/editable-artifacts.js +3 -3
  40. package/dist/governed-learning-activation-schema.d.ts +984 -0
  41. package/dist/governed-learning-activation.d.ts +98 -0
  42. package/dist/governed-learning-evaluator-schema.d.ts +633 -0
  43. package/dist/governed-learning-evaluator.d.ts +28 -0
  44. package/dist/index.d.ts +1633 -87
  45. package/dist/index.js +22004 -8109
  46. package/dist/index.js.map +1 -1
  47. package/dist/insights.d.ts +18 -0
  48. package/dist/integration-bindings.d.ts +1 -0
  49. package/dist/integration-facets.d.ts +30 -0
  50. package/dist/interaction-placement-loss.d.ts +22 -0
  51. package/dist/knowledge-source-sync-schema.d.ts +730 -0
  52. package/dist/knowledge-source-sync.d.ts +60 -0
  53. package/dist/managed-human-provisioning.d.ts +25 -0
  54. package/dist/memory-domain.d.ts +3 -3
  55. package/dist/migrate.d.ts +11 -1
  56. package/dist/migrate.js +1 -1
  57. package/dist/new-session-drafts.d.ts +43 -5
  58. package/dist/organization-membership-backfill.d.ts +174 -0
  59. package/dist/organization-membership-lifecycle.d.ts +162 -0
  60. package/dist/pr-review.d.ts +107 -0
  61. package/dist/preference-registry-schema.d.ts +2 -0
  62. package/dist/preference-registry.d.ts +2 -0
  63. package/dist/provision-roles.js +1 -1
  64. package/dist/runtime-posture.d.ts +23 -9
  65. package/dist/schema.d.ts +24925 -13697
  66. package/dist/schema.js +103 -1
  67. package/dist/scoped-knowledge-schema.d.ts +52 -1
  68. package/dist/session-background-commands.d.ts +125 -0
  69. package/dist/session-background-commands.js +34 -0
  70. package/dist/session-background-commands.js.map +1 -0
  71. package/dist/session-control.d.ts +156 -3
  72. package/dist/session-goal-pacing.d.ts +68 -0
  73. package/dist/session-queue-commands.d.ts +42 -5
  74. package/dist/session-realtime-ledger.d.ts +3 -0
  75. package/dist/session-tenancy.d.ts +71 -1
  76. package/dist/session-tenancy.js +25 -3
  77. package/dist/session-tool-call-settlement.d.ts +9 -4
  78. package/dist/slack-routing-personal-workspace.d.ts +23 -0
  79. package/dist/slack-routing.d.ts +153 -0
  80. package/dist/slack-task-policy-schema.d.ts +34 -0
  81. package/dist/slack-task-policy.d.ts +8 -0
  82. package/dist/slack-user-link-access.d.ts +1 -0
  83. package/dist/task-notes-schema.d.ts +594 -0
  84. package/dist/task-notes.d.ts +39 -0
  85. package/dist/turn-initiator.d.ts +2 -0
  86. package/dist/user-resource-authority.d.ts +109 -0
  87. package/dist/video-generation.js +3 -3
  88. package/dist/workspace-authority.d.ts +81 -0
  89. package/dist/workspace-instruction-policies-schema.d.ts +279 -0
  90. package/dist/workspace-instruction-policies.d.ts +62 -0
  91. package/dist/workspace-learning-policy.d.ts +1 -0
  92. package/dist/workspace-membership-permissions.d.ts +2 -0
  93. package/drizzle/0240_enrollment_connection_authority.sql +39 -0
  94. package/drizzle/0240_model_context_user_messages.sql +204 -0
  95. package/drizzle/0241_atomic_personal_resource_delegation.sql +1000 -0
  96. package/drizzle/0241_enrollment_agent_runtime.sql +70 -0
  97. package/drizzle/0243_google_drive_object_acl_authority.sql +554 -0
  98. package/drizzle/0244_slack_app_home_refresh_queue.sql +120 -0
  99. package/drizzle/0245_model_context_contribution_facts.sql +88 -0
  100. package/drizzle/0246_integration_personal_instance_authority.sql +70 -0
  101. package/drizzle/0247_terraform_stacks_provenance_repair.sql +428 -0
  102. package/drizzle/0248_terraform_stacks_component_resolution_fence.sql +83 -0
  103. package/drizzle/0249_personal_resource_delegation_authority_correction.sql +662 -0
  104. package/drizzle/0250_direct_retained_process_owner_liveness.sql +199 -0
  105. package/drizzle/0251_connected_machine_operation_policy.sql +45 -0
  106. package/drizzle/0252_scheduled_personal_resource_delegation.sql +1867 -0
  107. package/drizzle/0253_common_user_resource_authority_lifecycle.sql +1555 -0
  108. package/drizzle/0254_scoped_variable_set_authority.sql +1255 -0
  109. package/drizzle/0255_company_brain_governed_write_proposals.sql +524 -0
  110. package/drizzle/0256_connection_authority_delegation.sql +703 -0
  111. package/drizzle/0257_goal_revision_decisions_and_root_constraints.sql +436 -0
  112. package/drizzle/0258_three_scope_document_knowledge_authority.sql +1273 -0
  113. package/drizzle/0259_company_brain_context_selection_receipts.sql +869 -0
  114. package/drizzle/0260_task_note_knowledge_promotion.sql +820 -0
  115. package/drizzle/0261_preference_knowledge_proposal_actor_binding.sql +471 -0
  116. package/drizzle/0262_scoped_connected_machines_and_rigs.sql +1700 -0
  117. package/drizzle/0263_organization_membership_lifecycle.sql +3284 -0
  118. package/drizzle/0264_connection_authority_runtime_activation.sql +1084 -0
  119. package/drizzle/0266_company_brain_context_receipt_inspection.sql +156 -0
  120. package/drizzle/0268_governed_learning_decision_receipts.sql +825 -0
  121. package/drizzle/0269_governed_learning_activation_controller.sql +1874 -0
  122. package/drizzle/0270_governed_learning_history_inspection.sql +170 -0
  123. package/drizzle/0271_company_brain_retrieval_only_default.sql +524 -0
  124. package/drizzle/0272_human_confirmed_learning_activation.sql +591 -0
  125. package/drizzle/0273_scheduled_variable_set_materialization.sql +268 -0
  126. package/drizzle/0274_human_confirmed_knowledge_review.sql +310 -0
  127. package/drizzle/0275_scheduled_connection_authority.sql +5527 -0
  128. package/drizzle/0276_onboarding_proposal_initiating_human_guc.sql +198 -0
  129. package/drizzle/0277_workspace_writer_authority_attribution.sql +393 -0
  130. package/drizzle/0278_workspace_membership_removal_fencing.sql +1174 -0
  131. package/drizzle/0279_workspace_connection_use_lane.sql +343 -0
  132. package/drizzle/0280_connection_and_variable_set_audit_attribution.sql +773 -0
  133. package/drizzle/0281_viewer_holder_authority_claims.sql +52 -0
  134. package/drizzle/0282_variable_set_session_attach_attribution.sql +178 -0
  135. package/drizzle/0283_editable_spreadsheet_authored_state.sql +82 -0
  136. package/drizzle/0284_truthful_human_confirmed_review_reason.sql +930 -0
  137. package/drizzle/0285_organization_tenancy_inventory.sql +329 -0
  138. package/drizzle/0286_widen_task_note_expiry_ceiling.sql +391 -0
  139. package/drizzle/0287_open_suffix_pending_tool_calls.sql +18 -0
  140. package/drizzle/0288_attached_browser_reenrollment.sql +64 -0
  141. package/drizzle/0289_session_composer_policy_authority.sql +597 -0
  142. package/drizzle/0290_organization_membership_backfill.sql +268 -0
  143. package/drizzle/0291_resource_authority_classification_assertion.sql +371 -0
  144. package/drizzle/0292_truthful_tenancy_inventory_counters.sql +291 -0
  145. package/drizzle/0293_confirm_time_rule_rebaseline.sql +615 -0
  146. package/drizzle/0294_preference_activation_authority.sql +237 -0
  147. package/drizzle/0295_retire_legacy_standing_memory_mode.sql +476 -0
  148. package/drizzle/0296_force_rls_backfill_noop_repair.sql +215 -0
  149. package/drizzle/0297_session_ownership_classification_and_backfill.sql +752 -0
  150. package/drizzle/0298_organization_tenancy_parity.sql +609 -0
  151. package/drizzle/0299_organization_membership_lock_order.sql +291 -0
  152. package/drizzle/0300_tenancy_backfill_ledger.sql +459 -0
  153. package/drizzle/0301_session_snapshot_and_pin_visibility.sql +181 -0
  154. package/drizzle/0302_personal_workspace_session_ownership.sql +303 -0
  155. package/drizzle/0303_session_tenancy_product_activation.sql +919 -0
  156. package/drizzle/0304_personal_workspace_private_session_reads.sql +97 -0
  157. package/drizzle/0305_personal_resource_grant_management.sql +584 -0
  158. package/drizzle/0306_atomic_personal_resource_attachments.sql +1374 -0
  159. package/drizzle/0307_session_attention_state.sql +51 -0
  160. package/drizzle/0308_session_archives.sql +35 -0
  161. package/drizzle/0309_channel_project_pins.sql +6 -0
  162. package/drizzle/0310_channel_project_order.sql +27 -0
  163. package/drizzle/0311_company_scope_and_private_session_create.sql +656 -0
  164. package/drizzle/0312_quiescent_session_tree_deletion.sql +39 -0
  165. package/drizzle/0313_private_child_session_authority.sql +365 -0
  166. package/drizzle/0314_unregistered_organization_invitations.sql +606 -0
  167. package/drizzle/0315_personal_github_repository_selection.sql +624 -0
  168. package/drizzle/0316_human_confirmed_activation_resumed_generation.sql +869 -0
  169. package/drizzle/0317_session_goal_continuation_hold.sql +64 -0
  170. package/drizzle/0318_session_turn_startup_milestones.sql +115 -0
  171. package/drizzle/0319_event_triggered_automations.sql +254 -0
  172. package/drizzle/0320_pr_review_pack.sql +113 -0
  173. package/drizzle/0321_slack_bot_environment_display_name.sql +15 -0
  174. package/drizzle/0322_session_turns_unclaimed_prompt_trigger_index.sql +5 -0
  175. package/drizzle/0323_organization_private_session_enablement.sql +489 -0
  176. package/drizzle/0324_human_confirmed_company_profile_agent_admin.sql +856 -0
  177. package/drizzle/0325_child_lifecycle_notices.sql +44 -0
  178. package/drizzle/0326_interaction_operation_error_codes.sql +62 -0
  179. package/drizzle/0327_slack_first_task_hint.sql +29 -0
  180. package/drizzle/0328_session_background_commands.sql +590 -0
  181. package/drizzle/0329_slack_orchestration_delivery_events.sql +91 -0
  182. package/drizzle/0330_api_key_descriptions.sql +20 -0
  183. package/drizzle/0331_managed_organization_creation.sql +163 -0
  184. package/drizzle/0332_organization_shared_workspace_control_plane.sql +539 -0
  185. package/drizzle/0333_session_turn_prompt_routing.sql +45 -0
  186. package/drizzle/0334_connected_machine_workspace_root.sql +99 -0
  187. package/drizzle/0335_slack_workspace_routing.sql +460 -0
  188. package/drizzle/0336_atomic_session_fork_visibility.sql +667 -0
  189. package/drizzle/0337_slack_routed_action_handles.sql +189 -0
  190. package/drizzle/0338_atomic_connected_machine_attachments.sql +410 -0
  191. package/drizzle/0339_document_authority_reclassification.sql +1153 -0
  192. package/drizzle/0340_tenancy_backfill_activation_evidence.sql +1347 -0
  193. package/drizzle/0341_slack_routing_probe_organization_fence.sql +109 -0
  194. package/package.json +10 -6
  195. package/src/attached-browser-devices.ts +233 -5
  196. package/src/automations.ts +911 -0
  197. package/src/browser-sessions.ts +10 -0
  198. package/src/capability-integrations.ts +175 -1
  199. package/src/child-lifecycle-notices.ts +241 -0
  200. package/src/codemode-operations.ts +1 -35
  201. package/src/company-brain-context-selection-schema.ts +100 -0
  202. package/src/company-brain-context-selection.ts +359 -0
  203. package/src/company-brain-governed-writes.ts +1170 -0
  204. package/src/company-brain.ts +309 -0
  205. package/src/company-profile-agent-admin.ts +225 -0
  206. package/src/company-profile-schema.ts +121 -1
  207. package/src/company-profile.ts +21 -0
  208. package/src/computer-sessions.ts +10 -1
  209. package/src/connection-authority.ts +290 -0
  210. package/src/connection-scopes.ts +20 -0
  211. package/src/connection-tenancy-backfill.ts +81 -0
  212. package/src/connection-token-resolver.ts +263 -31
  213. package/src/database.ts +75 -2
  214. package/src/editable-artifact-durable-export.ts +27 -0
  215. package/src/editable-artifacts-schema.ts +10 -5
  216. package/src/editable-artifacts.ts +21 -11
  217. package/src/governed-learning-activation-schema.ts +121 -0
  218. package/src/governed-learning-activation.ts +588 -0
  219. package/src/governed-learning-evaluator-schema.ts +72 -0
  220. package/src/governed-learning-evaluator.ts +217 -0
  221. package/src/index.ts +12001 -1699
  222. package/src/insights.ts +107 -0
  223. package/src/integration-bindings.ts +88 -6
  224. package/src/integration-facets.ts +287 -84
  225. package/src/interaction-placement-loss.ts +234 -0
  226. package/src/knowledge-source-sync-schema.ts +83 -0
  227. package/src/knowledge-source-sync.ts +530 -0
  228. package/src/managed-human-provisioning.ts +116 -0
  229. package/src/memory-domain.ts +27 -32
  230. package/src/migrate.ts +77 -1
  231. package/src/new-session-drafts.ts +229 -35
  232. package/src/organization-membership-backfill.ts +735 -0
  233. package/src/organization-membership-lifecycle.ts +985 -0
  234. package/src/pr-review.ts +890 -0
  235. package/src/preference-registry.ts +31 -1
  236. package/src/provision-roles.ts +931 -24
  237. package/src/runtime-posture-cli.ts +2 -0
  238. package/src/runtime-posture.ts +1315 -52
  239. package/src/schema.ts +3336 -438
  240. package/src/scoped-knowledge-schema.ts +16 -8
  241. package/src/scoped-knowledge.ts +1 -1
  242. package/src/session-background-commands.ts +759 -0
  243. package/src/session-control.ts +640 -74
  244. package/src/session-goal-pacing.ts +126 -0
  245. package/src/session-queue-commands.ts +450 -98
  246. package/src/session-realtime-context.ts +19 -3
  247. package/src/session-realtime-ledger.ts +75 -12
  248. package/src/session-realtime-mirror.ts +1 -1
  249. package/src/session-tenancy.ts +403 -49
  250. package/src/session-tool-call-settlement.ts +38 -29
  251. package/src/slack-routing-personal-workspace.ts +67 -0
  252. package/src/slack-routing.ts +469 -0
  253. package/src/slack-task-policy-schema.ts +5 -0
  254. package/src/slack-task-policy.ts +18 -0
  255. package/src/slack-user-link-access.ts +17 -1
  256. package/src/task-notes-schema.ts +74 -0
  257. package/src/task-notes.ts +124 -2
  258. package/src/turn-initiator.ts +8 -0
  259. package/src/user-resource-authority.ts +377 -0
  260. package/src/workspace-authority.ts +160 -0
  261. package/src/workspace-instruction-policies-schema.ts +53 -1
  262. package/src/workspace-instruction-policies.ts +528 -77
  263. package/src/workspace-learning-policy.ts +21 -5
  264. package/src/workspace-membership-permissions.ts +9 -0
  265. package/dist/chunk-5KTIEDX7.js.map +0 -1
  266. package/dist/chunk-FPVAD4CO.js +0 -117
  267. package/dist/chunk-FPVAD4CO.js.map +0 -1
  268. package/dist/chunk-HSOWSYOX.js.map +0 -1
  269. package/dist/chunk-SK7YYHBI.js.map +0 -1
  270. package/dist/chunk-VKLB2ZGI.js +0 -2389
  271. package/dist/chunk-VKLB2ZGI.js.map +0 -1
  272. package/dist/chunk-Z7VYMNPZ.js.map +0 -1
  273. /package/dist/{chunk-GYO7ED2Q.js.map → chunk-EULAN2NP.js.map} +0 -0
  274. /package/dist/{chunk-VTPRIXKG.js.map → chunk-NJVZPWXY.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,17 +1,20 @@
1
- import { SessionGoalSnapshot } from "@opengeni/contracts";
2
- import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilityPack, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileUploadStatus, FirstPartyMcpToolName, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExportBatch, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, McpPersonalConnectionDelegation, Permission, PackInstallation, PackInstallationStatus, ResourceRef, SandboxBackend, SandboxOs, ScheduledTask, ScheduledTaskAction, ScheduledTaskActionKind, KnowledgeSourceSyncAction, ScheduledTaskAgentConfig, ScheduledTaskOverlapPolicy, ScheduledTaskRun, ScheduledTaskRunMode, ScheduledTaskRunStatus, ScheduledTaskScheduleSpec, ScheduledTaskStatus, ScheduledTaskTriggerType, SlackInstallationBinding, Session, SessionAuthorizationListScope, SessionListResponse, SessionEvent, SessionEventPayloadMode, SessionEventReadDirection, SessionEventSemanticClass, SessionEventType, SessionGoal, SessionGoalChangeKind, SessionGoalCreatedBy, SessionGoalMutationPolicy, SessionGoalRevision, SessionGoalStatus, SessionHumanInputRequest, LineageNode, SessionMcpApprovalPolicy, SessionSkill, SessionMcpServerMetadata, SessionStatus, SessionToolPolicy, SessionTurn, SessionQueueSnapshot, SessionSystemUpdate, SessionSystemUpdateKind, SystemUpdateClassification, SessionTurnSource, SessionTurnStatus, TurnInitiator, TurnInitiatorContext, SocialConnection, SocialConnectionStatus, SocialPost, SocialProvider, ToolRef, ReasoningEffort, UsageEvent, Workspace, WorkspaceControlEvent, VariableSet, VariableSetSecret, VariableSetVariableMetadata, WorkspaceMember, WorkspaceMemoryPromptMode, WorkspaceRegisteredPack, Channel, Rig, RigProviderImage, RigProviderImages, RigVersion, RigChange, RigChangeKind, RigChangeStatus, RigCheck, NativeSnapshotDescriptor, TarWorkspaceArchiveDescriptor, WorkspaceArchiveDescriptor, ModalCheckpointProviderBinding, SandboxProviderContinuityRecovery } from "@opengeni/contracts";
3
- import { RequestHumanInteractionToolInput, XaiProviderAccountAuthoritySnapshotV1, type TimelineAnnotation } from "@opengeni/contracts";
1
+ import { type ChildLifecycleSystemUpdateKind, type ChildRequiresActionRespondedByKind, SessionGoalSnapshot } from "@opengeni/contracts";
2
+ import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilityPack, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileUploadStatus, FirstPartyMcpToolName, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExportBatch, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, McpPersonalConnectionDelegation, ModelContextContributionSummary, Permission, PersonalResourceAttachmentIntent, PackInstallation, PackInstallationStatus, ResourceRef, SandboxBackend, SandboxOs, ScheduledTask, ScheduledTaskAction, ScheduledTaskActionKind, KnowledgeSourceSyncAction, ScheduledTaskAgentConfig, ScheduledTaskOverlapPolicy, ScheduledTaskRun, ScheduledTaskRunAcceptedExecution as ScheduledTaskRunAcceptedExecutionType, ScheduledTaskRunMode, ScheduledTaskRunStatus, ScheduledTaskScheduleSpec, ScheduledTaskStatus, ScheduledTaskTriggerType, SlackInstallationBinding, Session, SessionAuthorizationListScope, SessionListResponse, SessionEvent, SessionEventPayloadMode, SessionEventReadDirection, SessionEventSemanticClass, SessionEventType, SessionGoal, SessionGoalChangeKind, SessionGoalCreatedBy, SessionGoalMutationPolicy, SessionGoalRevision, SessionGoalStatus, SessionHumanInputRequest, LineageNode, SessionMcpApprovalPolicy, SessionSkill, SessionMcpServerMetadata, SessionStatus, SessionToolPolicy, SessionTurn, SessionQueueSnapshot, SessionSystemUpdate, SessionSystemUpdateKind, SystemUpdateClassification, SessionTurnSource, SessionTurnStatus, TurnInitiator, TurnInitiatorContext, SocialConnection, SocialConnectionStatus, SocialPost, SocialProvider, ToolRef, ReasoningEffort, UsageEvent, Workspace, WorkspaceControlEvent, VariableSet, VariableSetSecret, VariableSetVariableMetadata, WorkspaceMember, WorkspaceMemoryPromptMode, WorkspaceRegisteredPack, Channel, Rig, RigProviderImage, RigProviderImages, RigVersion, RigVerificationHealth, RigChange, RigChangeKind, RigChangeStatus, RigCheck, NativeSnapshotDescriptor, TarWorkspaceArchiveDescriptor, WorkspaceArchiveDescriptor, ModalCheckpointProviderBinding, SandboxProviderContinuityRecovery } from "@opengeni/contracts";
3
+ import { type WorkspaceArchiveObjectRef, RequestHumanInteractionToolInput, XaiProviderAccountAuthoritySnapshotV1, type TimelineAnnotation } from "@opengeni/contracts";
4
4
  import { type LatencyMode, SessionSystemUpdatePayload, TurnExecutionPolicyV1 } from "@opengeni/contracts";
5
5
  import { type Settings } from "@opengeni/config";
6
6
  import { type CodexFetch } from "@opengeni/codex";
7
7
  export { isCodexBilledModel } from "@opengeni/codex";
8
+ export * from "./pr-review.js";
8
9
  import { type SQL } from "drizzle-orm";
9
10
  export { frozenInitiatorForCommandActor, type FrozenTurnInitiator } from "./turn-initiator.js";
10
11
  export { LOSSLESS_TEXT_PREFIX } from "./lossless-json.js";
12
+ import { type NewSessionDraftSnapshot } from "./new-session-drafts.js";
11
13
  import { type SessionDiscoveryControl, type SessionCommandActor, type SessionTurnAttemptOutcome } from "./session-control.js";
12
14
  import { type SessionRealtimeContinuityEntry } from "./session-realtime-context.js";
13
15
  import * as schema from "./schema.js";
14
16
  export { sql as dbSql } from "drizzle-orm";
17
+ export * from "./child-lifecycle-notices.js";
15
18
  export * from "./session-control.js";
16
19
  export * from "./session-queue-commands.js";
17
20
  export * from "./session-realtime.js";
@@ -20,17 +23,30 @@ export * from "./session-realtime-ledger.js";
20
23
  export * from "./new-session-drafts.js";
21
24
  export * from "./workspace-instruction-policies.js";
22
25
  export * from "./company-profile.js";
26
+ export * from "./company-profile-agent-admin.js";
23
27
  export * from "./workspace-learning-policy.js";
28
+ export * from "./governed-learning-evaluator.js";
24
29
  export * from "./slack-task-policy.js";
25
30
  export * from "./preference-registry.js";
26
31
  export * from "./memory-governance.js";
27
32
  export * from "./memory-slack-delivery.js";
28
33
  export * from "./scoped-knowledge.js";
34
+ export * from "./company-brain.js";
35
+ export * from "./company-brain-governed-writes.js";
36
+ export * from "./company-brain-context-selection.js";
29
37
  export * from "./knowledge-source-sync.js";
30
38
  export * from "./task-notes.js";
39
+ export * from "./managed-human-provisioning.js";
40
+ export * from "./organization-membership-backfill.js";
41
+ export * from "./connection-tenancy-backfill.js";
31
42
  export * from "./generated-images.js";
32
43
  export * from "./slack-user-link-access.js";
44
+ export * from "./slack-routing.js";
45
+ export * from "./slack-routing-personal-workspace.js";
46
+ export * from "./workspace-membership-permissions.js";
33
47
  export * from "./video-generation.js";
48
+ export * from "./user-resource-authority.js";
49
+ export * from "./connection-authority.js";
34
50
  export * from "./xai-subscription.js";
35
51
  export { interruptedToolCallResult } from "./session-tool-call-settlement.js";
36
52
  export { decryptEnvironmentValue, encryptEnvironmentValue } from "./environment-crypto.js";
@@ -41,12 +57,14 @@ export * from "./capability-integrations.js";
41
57
  export * from "./integration-bindings.js";
42
58
  export * from "./integration-facets.js";
43
59
  export * from "./insights.js";
60
+ export * from "./organization-membership-lifecycle.js";
61
+ export { rlsSubjectIdOrEmpty, subjectHasLiveWorkspaceAuthorityInScope, } from "./workspace-authority.js";
44
62
  export { memoryTextForStorage } from "./memory-domain.js";
45
63
  export { migrate, runMigrations } from "./migrate.js";
46
64
  export { provisionRoles, type ProvisionResult, type ProvisionRolesOptions, } from "./provision-roles.js";
47
65
  export * from "./memory-domain.js";
48
66
  import { type Database, type SessionActivityDatabase } from "./database.js";
49
- export { createDb, registerDbBinding, retrySessionActivityRls, rlsContextForWorkspace, rlsStrategyFor, setRlsContext, setSubjectRlsContext, withAccountRls, withDatabaseStatementTimeout, withRlsContext, withSessionActivityRlsContext, withSessionActivitySavepoint, withWorkspaceRls, withWorkspaceSessionActivityRls, withWorkspaceSubjectRls, withWorkspaceSubjectSessionActivityRls, withWorkspaceUsageLock, withSandboxProviderReadLock, SandboxProviderReadLockUnavailableError, type CreateDbOptions, type Database, type DbClient, type SessionActivityDatabase, type RlsContext, type SessionRlsActorContext, type RlsStrategy, type SandboxProviderReadLockIdentity, type UserLookup, } from "./database.js";
67
+ export { createDb, registerDbBinding, retrySessionActivityRls, rlsContextForWorkspace, rlsStrategyFor, setRlsContext, setSubjectRlsContext, withAccountRls, withDatabaseStatementTimeout, withRlsContext, withSessionActivityRlsContext, withSessionActivitySavepoint, withWorkspaceRls, withWorkspaceSessionActivityRls, withWorkspaceSubjectRls, withWorkspaceSubjectSessionActivityRls, withWorkspaceUsageLock, withSandboxProviderReadLock, SandboxProviderReadLockUnavailableError, type CreateDbOptions, type Database, type DbClient, type SessionActivityDatabase, type RlsContext, type SessionRlsActorContext, type RlsStrategy, type SandboxProviderReadLockIdentity, type ManagedUserProfile, type UserLookup, type UserProfileLookup, } from "./database.js";
50
68
  export { withSessionRlsActorContext } from "./database.js";
51
69
  import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialForRun } from "./codex-token-resolver.js";
52
70
  import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions } from "./connection-token-resolver.js";
@@ -232,6 +250,14 @@ export declare function resolveDocumentIndexAuthority(db: Database, input: {
232
250
  documentId: string;
233
251
  }): Promise<DocumentIndexAuthority | null>;
234
252
  export declare const allWorkspacePermissions: Permission[];
253
+ /**
254
+ * Runtime capabilities for the authenticated managed human's personal
255
+ * workspace. This projection is deliberately not an administrative grant:
256
+ * workspace administration is a wildcard over member management and API-key
257
+ * delegation, either of which would let the owner create another principal
258
+ * with ambient access to the private workspace.
259
+ */
260
+ export declare const managedPersonalWorkspacePermissions: Permission[];
235
261
  export declare const allAccountPermissions: Permission[];
236
262
  export type BootstrapWorkspaceInput = {
237
263
  accountExternalSource: string;
@@ -250,6 +276,7 @@ export declare function ensureManagedAccessForUser(db: Database, input: {
250
276
  userId: string;
251
277
  email: string;
252
278
  name: string;
279
+ emailVerified?: boolean;
253
280
  }): Promise<AccessContext>;
254
281
  export type ManagedAccessProvisioningResult = {
255
282
  accessContext: AccessContext;
@@ -259,6 +286,7 @@ export declare function ensureManagedAccessForUserWithOrganizationMemberships(db
259
286
  userId: string;
260
287
  email: string;
261
288
  name: string;
289
+ emailVerified?: boolean;
262
290
  }): Promise<ManagedAccessProvisioningResult>;
263
291
  export declare function getWorkspace(db: Database, workspaceId: string): Promise<Workspace | null>;
264
292
  export declare function getManagedAccount(db: Database, accountId: string): Promise<ManagedAccount | null>;
@@ -273,6 +301,20 @@ export declare function createWorkspace(db: Database, input: {
273
301
  externalId?: string | null;
274
302
  agentInstructions?: string | null;
275
303
  }): Promise<Workspace>;
304
+ /**
305
+ * Create one shared workspace through the direct managed-human organization
306
+ * control plane. Organization authority is rechecked inside the lifecycle
307
+ * function, the operation id is replay-safe, and no operational
308
+ * workspace_memberships row is created for the actor.
309
+ */
310
+ export declare function createOrganizationSharedWorkspace(db: Database, input: {
311
+ organizationId: string;
312
+ actorSubjectId: string;
313
+ name: string;
314
+ slug?: string | null;
315
+ agentInstructions?: string | null;
316
+ operationId: string;
317
+ }): Promise<Workspace>;
276
318
  export declare function grantWorkspaceAccess(db: Database, input: {
277
319
  accountId: string;
278
320
  workspaceId: string;
@@ -281,18 +323,55 @@ export declare function grantWorkspaceAccess(db: Database, input: {
281
323
  role?: string;
282
324
  permissions: Permission[];
283
325
  }): Promise<void>;
326
+ /**
327
+ * Organization control-plane metadata update for one shared workspace. This
328
+ * capability never creates a workspace membership or an operational grant for
329
+ * the actor; the database excludes every Personal workspace before mutation.
330
+ */
331
+ export declare function updateOrganizationSharedWorkspace(db: Database, input: {
332
+ organizationId: string;
333
+ workspaceId: string;
334
+ actorSubjectId: string;
335
+ name?: string;
336
+ slug?: string | null;
337
+ agentInstructions?: string | null;
338
+ }): Promise<Workspace>;
339
+ /** Same authority as metadata administration, preserving the canonical
340
+ * workspace-settings merge and inference-control lock path. */
341
+ export declare function updateOrganizationSharedWorkspaceSettings(db: Database, input: {
342
+ organizationId: string;
343
+ workspaceId: string;
344
+ actorSubjectId: string;
345
+ patch: Record<string, unknown>;
346
+ }): Promise<Workspace>;
347
+ /** Assign or update one active organization member in one shared workspace. */
348
+ export declare function upsertOrganizationSharedWorkspaceMember(db: Database, input: {
349
+ organizationId: string;
350
+ workspaceId: string;
351
+ actorSubjectId: string;
352
+ targetOrganizationMembershipId: string;
353
+ subjectLabel?: string | null;
354
+ role?: string;
355
+ permissions: Permission[];
356
+ requireExisting: boolean;
357
+ }): Promise<WorkspaceMember>;
284
358
  export declare function updateWorkspace(db: Database, workspaceId: string, input: {
285
359
  name?: string;
286
360
  slug?: string | null;
287
361
  agentInstructions?: string | null;
288
362
  }): Promise<Workspace>;
289
- export declare function updateWorkspaceSettings(db: Database, workspaceId: string, patch: Record<string, unknown>): Promise<Workspace>;
363
+ export declare function updateWorkspaceSettings(db: Database, workspaceId: string, patch: Record<string, unknown>, options?: {
364
+ /**
365
+ * Bound the workspace control prefix wait (request-scoped API callers pass
366
+ * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers.
367
+ */
368
+ controlLockTimeoutMs?: number;
369
+ }): Promise<Workspace>;
290
370
  export declare function setWorkspaceDefaultRig(db: Database, workspaceId: string, rigId: string | null): Promise<Workspace>;
291
371
  export declare function getWorkspaceGrant(db: Database, subjectId: string, workspaceId: string, provenance?: {
292
372
  principalKind?: AccessPrincipalKind;
293
373
  }): Promise<AccessGrant | null>;
294
374
  export declare function listWorkspaceMembers(db: Database, workspaceId: string): Promise<WorkspaceMember[]>;
295
- export declare function removeWorkspaceMember(db: Database, workspaceId: string, subjectId: string): Promise<boolean>;
296
375
  /**
297
376
  * Resolve a managed user email to its user id.
298
377
  *
@@ -311,12 +390,26 @@ export declare function removeWorkspaceMember(db: Database, workspaceId: string,
311
390
  * unknown users are deferred.
312
391
  */
313
392
  export declare function getManagedUserByEmail(db: Database, email: string): Promise<string | null>;
393
+ /**
394
+ * Resolve the safe profile fields organization administrators need to manage
395
+ * their own roster. Embedded deployments can provide the same projection
396
+ * through `userProfileLookup` without exposing their identity store schema.
397
+ */
398
+ export declare function getManagedUserProfilesByIds(db: Database, userIds: readonly string[]): Promise<Array<{
399
+ id: string;
400
+ name: string | null;
401
+ email: string;
402
+ }>>;
314
403
  export declare function deleteWorkspace(db: Database, workspaceId: string): Promise<void>;
315
404
  export type TemporalScheduleCleanupClaim = {
316
405
  id: string;
317
406
  accountId: string;
318
407
  workspaceId: string;
319
408
  temporalScheduleId: string;
409
+ scheduledTaskId: string | null;
410
+ connectorCleanupSubjectId: string | null;
411
+ connectorCleanupSnapshot: unknown | null;
412
+ connectorCleanupCompletedAt: Date | null;
320
413
  claimId: string;
321
414
  attemptCount: number;
322
415
  };
@@ -324,7 +417,7 @@ export type DeleteWorkspaceIfQuiescentResult = {
324
417
  status: "deleted";
325
418
  temporalScheduleCleanups: TemporalScheduleCleanupClaim[];
326
419
  } | {
327
- status: "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "live_sandboxes";
420
+ status: "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes";
328
421
  };
329
422
  /**
330
423
  * Atomically prove a workspace has no live runtime ownership and delete it.
@@ -355,10 +448,16 @@ export declare function settleTemporalScheduleCleanup(db: Database, input: {
355
448
  claimId: string;
356
449
  error?: string | null;
357
450
  }): Promise<boolean>;
451
+ /** Persist the connector half of a combined cleanup before attempting Temporal. */
452
+ export declare function completeTemporalScheduleConnectorCleanup(db: Database, input: {
453
+ id: string;
454
+ claimId: string;
455
+ }): Promise<boolean>;
358
456
  export declare function createApiKey(db: Database, input: {
359
457
  accountId: string;
360
458
  workspaceId?: string | null;
361
459
  name: string;
460
+ description?: string | null;
362
461
  prefix: string;
363
462
  keyHash: string;
364
463
  permissions: Permission[];
@@ -489,6 +588,7 @@ export type ModelCallFact = {
489
588
  pricedCostMicros: number;
490
589
  estimatedProviderCostMicros: number | null;
491
590
  pricingSource: "configured_list_price" | "gateway_reported" | null;
591
+ contextContributions: readonly ModelContextContributionSummary[] | null;
492
592
  occurredAt: Date;
493
593
  recordedAt: Date;
494
594
  };
@@ -510,6 +610,7 @@ export declare function recordModelCallFact(db: Database, input: {
510
610
  pricedCostMicros: number;
511
611
  estimatedProviderCostMicros?: number | null;
512
612
  pricingSource?: "configured_list_price" | "gateway_reported" | null;
613
+ contextContributions?: readonly ModelContextContributionSummary[] | null;
513
614
  inputTokens?: number | null;
514
615
  outputTokens?: number | null;
515
616
  cachedTokens?: number | null;
@@ -632,6 +733,12 @@ export type UpdateScheduledTaskInput = Partial<{
632
733
  variableSetId: string | null;
633
734
  rigId: string | null;
634
735
  metadata: Record<string, unknown>;
736
+ refreshPersonalResourceAuthority: boolean;
737
+ cloneConnectionAuthorityFromRevision: number;
738
+ clonePersonalResourceAuthorityFromRevision: number;
739
+ authorityUpdatedBy: TurnInitiator;
740
+ authorityUpdatedByContext: TurnInitiatorContext;
741
+ authorityUpdatedByActor: AgentSessionCreationActor | null;
635
742
  }>;
636
743
  export type CreatePackInstallationInput = {
637
744
  accountId: string;
@@ -778,6 +885,25 @@ export type PersistProviderOAuthConnectionInput = CreateConnectionInput & {
778
885
  providerPrincipalId: string;
779
886
  requestedConnectionId?: string;
780
887
  requestedConnectionVersion?: number;
888
+ /**
889
+ * Require this exact subject to retain live workspace authority in the same
890
+ * transaction that persists the credential. This is only a consistency
891
+ * fence: the caller must separately prove that the subject is the
892
+ * authenticated managed human before opting in.
893
+ */
894
+ requireLiveUserAuthority?: boolean;
895
+ /** Permission that must remain present while the owner row is locked. */
896
+ requiredLiveUserPermission?: "connections:write";
897
+ /**
898
+ * Permit the canonical managed-human personal-workspace exception when no
899
+ * ordinary membership row exists. The caller must have authenticated that
900
+ * exact human before opting in.
901
+ */
902
+ allowCanonicalPersonalWorkspaceOwner?: boolean;
903
+ /** Keep at most one non-revoked provider principal for this owner/family. */
904
+ exclusiveProviderPrincipalPerOwner?: boolean;
905
+ /** Existing values for these metadata keys survive exact-principal convergence. */
906
+ preserveExistingMetadataKeys?: readonly string[];
781
907
  };
782
908
  export type UpdateSlackBotDocumentDestinationInput = {
783
909
  accountId: string;
@@ -817,6 +943,58 @@ export declare class ConnectionDisconnectGenerationError extends Error {
817
943
  readonly code = "CONNECTION_GENERATION_CHANGED";
818
944
  constructor();
819
945
  }
946
+ export type PersonalGitHubRepositoryPermissions = {
947
+ pull: boolean;
948
+ push: boolean;
949
+ admin: boolean;
950
+ maintain: boolean;
951
+ triage: boolean;
952
+ };
953
+ export type PersonalGitHubSelectedRepositoryRecord = {
954
+ repositoryId: string;
955
+ fullName: string;
956
+ canonicalUrl: string;
957
+ defaultBranch: string;
958
+ visibility: "public" | "private" | "internal";
959
+ private: boolean;
960
+ archived: boolean;
961
+ disabled: boolean;
962
+ permissions: PersonalGitHubRepositoryPermissions;
963
+ selectedAccess: "read" | "write";
964
+ selectionGeneration: number;
965
+ selectedAt: string;
966
+ lastVerifiedAt: string;
967
+ };
968
+ export type PersonalGitHubRepositorySelectionState = {
969
+ connectionAuthorityGeneration: number;
970
+ credentialBindingId: string;
971
+ providerPrincipalId: string;
972
+ selectionGeneration: number;
973
+ repositories: PersonalGitHubSelectedRepositoryRecord[];
974
+ };
975
+ export type PersonalGitHubVerifiedRepositoryInput = Omit<PersonalGitHubSelectedRepositoryRecord, "selectionGeneration" | "selectedAt">;
976
+ export type PersonalGitHubRepositorySelectionMutationInput = {
977
+ accountId: string;
978
+ originWorkspaceId: string;
979
+ subjectId: string;
980
+ connectionId: string;
981
+ expectedConnectionAuthorityGeneration: number;
982
+ expectedSelectionGeneration: number;
983
+ idempotencyKey: string;
984
+ repositories: PersonalGitHubVerifiedRepositoryInput[];
985
+ };
986
+ export declare class PersonalGitHubRepositorySelectionChangedError extends Error {
987
+ readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_CHANGED";
988
+ constructor();
989
+ }
990
+ export declare class PersonalGitHubRepositorySelectionIdempotencyError extends Error {
991
+ readonly code = "PERSONAL_GITHUB_REPOSITORY_IDEMPOTENCY_KEY_REUSED";
992
+ constructor();
993
+ }
994
+ export declare class PersonalGitHubRepositorySelectionUnavailableError extends Error {
995
+ readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_UNAVAILABLE";
996
+ constructor();
997
+ }
820
998
  /** Server-owned verification facts; public schemas expose them read-only and nullable. */
821
999
  export type ConnectionMetadataWithVerification = ConnectionMetadata & {
822
1000
  verifiedInstallAt: string | null;
@@ -994,6 +1172,8 @@ export type RegistryCapabilityCatalogItemInput = {
994
1172
  scopesHint?: string[];
995
1173
  homepageUrl?: string | null;
996
1174
  installUrl?: string | null;
1175
+ /** Curated catalog grouping. Defaults to the registry-wide "integrations". */
1176
+ category?: string | null;
997
1177
  tags?: string[];
998
1178
  metadata?: Record<string, unknown>;
999
1179
  };
@@ -1178,7 +1358,7 @@ export type EnqueueSessionTurnInput = {
1178
1358
  temporalWorkflowId: string;
1179
1359
  source: SessionTurnSource;
1180
1360
  prompt: string;
1181
- turnInstructions?: string | null;
1361
+ modelContext?: string | null;
1182
1362
  resources: ResourceRef[];
1183
1363
  tools: ToolRef[];
1184
1364
  toolsProvided?: boolean;
@@ -1196,15 +1376,12 @@ export type EnqueueSessionTurnInput = {
1196
1376
  /** Steer inserts before all waiting prompts; Send appends after them. */
1197
1377
  placement?: "head" | "tail";
1198
1378
  };
1199
- /**
1200
- * Worker-only turn projection. Host instructions are durable execution input,
1201
- * never part of the public SessionTurn/queue/HTTP contract.
1202
- */
1379
+ /** Worker-only turn projection with causal authority omitted from public APIs. */
1203
1380
  export type SessionTurnForExecution = SessionTurn & {
1204
- turnInstructions: string | null;
1205
1381
  personalConnectionDelegations: McpPersonalConnectionDelegation[];
1206
1382
  /** Worker-only causal authority; never inferred from the current worker. */
1207
1383
  initiatingHumanSubjectId: string | null;
1384
+ scheduledTaskRunId: string | null;
1208
1385
  xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;
1209
1386
  goalSnapshot: SessionGoalSnapshot;
1210
1387
  };
@@ -1251,10 +1428,41 @@ export declare function prepareGeneratedWorkspaceFile(db: Database, input: Prepa
1251
1428
  }>;
1252
1429
  export declare function getFile(db: Database, workspaceId: string, fileId: string): Promise<FileAsset | null>;
1253
1430
  export declare function requireFile(db: Database, workspaceId: string, fileId: string): Promise<FileAsset>;
1431
+ /**
1432
+ * Subject-bound file read for user-visible and model-injection surfaces. The
1433
+ * database predicate returns true for ordinary workspace files, but Drive-
1434
+ * derived bytes require current per-object ACL evidence for every protecting
1435
+ * mapping. Missing/stale/mixed denied mappings therefore look not found.
1436
+ */
1437
+ export declare function requireFileForSubject(db: Database, input: {
1438
+ accountId: string;
1439
+ workspaceId: string;
1440
+ subjectId: string | null;
1441
+ fileId: string;
1442
+ }): Promise<FileAsset>;
1443
+ /**
1444
+ * Resolve a Document's immutable origin File through one database authority
1445
+ * statement. The resolver proves target-workspace Document visibility, live
1446
+ * portable-owner authority, and provider ACL before returning origin metadata;
1447
+ * it never grants generic visibility into the origin workspace's Files.
1448
+ */
1449
+ export declare function resolveDocumentOriginalFileForSubject(db: Database, input: {
1450
+ accountId: string;
1451
+ workspaceId: string;
1452
+ subjectId: string;
1453
+ documentId: string;
1454
+ }): Promise<FileAsset | null>;
1455
+ /** Batch form of requireFileForSubject; unauthorized or missing ids are omitted. */
1456
+ export declare function getFilesForSubject(db: Database, input: {
1457
+ accountId: string;
1458
+ workspaceId: string;
1459
+ subjectId: string | null;
1460
+ fileIds: readonly string[];
1461
+ }): Promise<FileAsset[]>;
1254
1462
  /** One RLS-scoped query for all attachment metadata needed by a model turn. */
1255
1463
  export declare function getFiles(db: Database, workspaceId: string, fileIds: readonly string[]): Promise<FileAsset[]>;
1256
1464
  /** Build the canonical user row with stable attachment refs, never inline bytes. */
1257
- export declare function durableUserHistoryItem(prompt: string, resources: readonly ResourceRef[], annotations?: readonly TimelineAnnotation[]): Record<string, unknown>;
1465
+ export declare function durableUserHistoryItem(prompt: string, resources: readonly ResourceRef[], annotations?: readonly TimelineAnnotation[], modelContext?: string | null, goalSnapshot?: SessionGoalSnapshot): Record<string, unknown>;
1258
1466
  export type RetainedFileArtifact = {
1259
1467
  file: FileAsset;
1260
1468
  uploadStatus: FileUploadStatus | null;
@@ -1485,6 +1693,22 @@ export declare function markStaleRegistryCatalogItems(db: Database, activeKeys:
1485
1693
  }>, importBatchId: string): Promise<number>;
1486
1694
  export declare function upsertCapabilityCatalogItem(db: Database, input: CreateCapabilityCatalogItemInput): Promise<CapabilityCatalogItem>;
1487
1695
  export declare function listCapabilityCatalogItems(db: Database, workspaceId: string): Promise<CapabilityCatalogItem[]>;
1696
+ /**
1697
+ * Declarative OAuth profile carried by a global (registry-imported) catalog
1698
+ * row for an exact MCP URL, or null when no row declares one. Only global
1699
+ * rows are consulted: a workspace-created row must not steer another
1700
+ * workspace's OAuth flow, and the OAuth client applies the profile as a
1701
+ * narrowing constraint over its defaults.
1702
+ *
1703
+ * A stale row's profile still applies deliberately: staleness hides the row
1704
+ * from the browse surface, but dropping its declared fences on staleness
1705
+ * would loosen an ownership or origin constraint. Non-stale rows win when a
1706
+ * duplicate `mcp_url` exists under two provider domains; the remaining id
1707
+ * tie-break is only for determinism. The value is returned raw (whatever the
1708
+ * row carries) so the caller's validation decides how a malformed profile
1709
+ * fails; absence of the key is the only null.
1710
+ */
1711
+ export declare function getGlobalCatalogOAuthProfile(db: Database, workspaceId: string, mcpUrl: string): Promise<unknown | null>;
1488
1712
  export declare function getCapabilityCatalogItem(db: Database, workspaceId: string, capabilityId: string): Promise<CapabilityCatalogItem | null>;
1489
1713
  /**
1490
1714
  * Install one immutable, already-validated Skill through the authoritative
@@ -1509,6 +1733,12 @@ export declare function disableCapabilityInstallation(db: Database, workspaceId:
1509
1733
  export declare function listCapabilityInstallations(db: Database, workspaceId: string): Promise<CapabilityInstallation[]>;
1510
1734
  export declare function getCapabilityInstallation(db: Database, workspaceId: string, capabilityId: string): Promise<CapabilityInstallation | null>;
1511
1735
  export declare function listEnabledMcpCapabilityServers(db: Database, workspaceId: string): Promise<EnabledMcpCapabilityServer[]>;
1736
+ /**
1737
+ * Metadata-only projection of runnable capability MCP server ids. The query
1738
+ * deliberately computes credential-presence booleans in PostgreSQL and never
1739
+ * selects stored header ciphertext or connection-reference contents.
1740
+ */
1741
+ export declare function listEnabledMcpCapabilityServerIds(db: Database, workspaceId: string): Promise<string[]>;
1512
1742
  /**
1513
1743
  * Decrypts an enabled capability MCP's stored credential headers. Returns
1514
1744
  * null when the server has none, and "unavailable" when headers exist but
@@ -1533,6 +1763,14 @@ export declare function createConnection(db: Database, input: CreateConnectionIn
1533
1763
  export declare function persistProviderOAuthConnection(db: Database, input: PersistProviderOAuthConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1534
1764
  export declare function listConnectionsMetadata(db: Database, workspaceId: string, subjectId?: string | null): Promise<ConnectionMetadataWithVerification[]>;
1535
1765
  export declare function getConnectionMetadata(db: Database, workspaceId: string, connectionId: string, subjectId?: string | null): Promise<ConnectionMetadataWithVerification | null>;
1766
+ export declare function getPersonalGitHubRepositorySelectionState(db: Database, input: {
1767
+ accountId: string;
1768
+ originWorkspaceId: string;
1769
+ subjectId: string;
1770
+ connectionId: string;
1771
+ }): Promise<PersonalGitHubRepositorySelectionState | null>;
1772
+ export declare function replacePersonalGitHubRepositorySelections(db: Database, input: PersonalGitHubRepositorySelectionMutationInput): Promise<PersonalGitHubRepositorySelectionState>;
1773
+ export declare function verifyPersonalGitHubRepositorySelections(db: Database, input: PersonalGitHubRepositorySelectionMutationInput): Promise<PersonalGitHubRepositorySelectionState>;
1536
1774
  export declare function updateConnection(db: Database, input: UpdateConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1537
1775
  /**
1538
1776
  * Updates only pre-validated workspace Slack-bot destination metadata while
@@ -1580,6 +1818,11 @@ export type SlackBotUserLink = {
1580
1818
  slackUserId: string;
1581
1819
  subjectId: string;
1582
1820
  linkedBySubjectId: string;
1821
+ /**
1822
+ * The exact Slack interaction id that durably claimed this identity's
1823
+ * one-time onboarding hint, or `null` when the hint has not been shown.
1824
+ */
1825
+ firstTaskHintInteractionId: string | null;
1583
1826
  createdAt: Date;
1584
1827
  updatedAt: Date;
1585
1828
  };
@@ -1610,6 +1853,25 @@ export type SlackInteractionInboxEntry = {
1610
1853
  createdAt: Date;
1611
1854
  updatedAt: Date;
1612
1855
  };
1856
+ export type SlackAppHomeRefresh = {
1857
+ id: string;
1858
+ accountId: string;
1859
+ workspaceId: string;
1860
+ connectionId: string;
1861
+ slackTeamId: string;
1862
+ slackUserId: string;
1863
+ providerEventId: string;
1864
+ providerViewHash: string | null;
1865
+ desiredRevision: number;
1866
+ processedRevision: number;
1867
+ claimHolderId: string | null;
1868
+ claimExpiresAt: Date | null;
1869
+ attemptCount: number;
1870
+ retryAt: Date | null;
1871
+ lastErrorCode: string | null;
1872
+ createdAt: Date;
1873
+ updatedAt: Date;
1874
+ };
1613
1875
  export type SlackInteraction = {
1614
1876
  id: string;
1615
1877
  accountId: string;
@@ -1632,6 +1894,11 @@ export type SlackInteraction = {
1632
1894
  deliveryRetryAt: Date | null;
1633
1895
  deliveryLastErrorCode: string | null;
1634
1896
  ackSlackMessageTs: string | null;
1897
+ /**
1898
+ * Frozen once: whether this interaction's acknowledgement renders the
1899
+ * one-time onboarding hint. `null` means the decision is unresolved.
1900
+ */
1901
+ firstTaskHint: boolean | null;
1635
1902
  progressCount: number;
1636
1903
  terminalDeliveryState: "open" | "completed" | "failed" | "cancelled" | "blocked";
1637
1904
  createdAt: Date;
@@ -1671,9 +1938,63 @@ export type SlackInteractionActionHandle = {
1671
1938
  updatedAt: Date;
1672
1939
  };
1673
1940
  export declare function resolveSlackInstallationRoute(db: Database, slackTeamId: string): Promise<SlackInstallationRoute | null>;
1674
- export declare function saveSlackBotUserLink(db: Database, input: Omit<SlackBotUserLink, "id" | "createdAt" | "updatedAt">): Promise<SlackBotUserLink>;
1941
+ export declare function saveSlackBotUserLink(db: Database, input: Omit<SlackBotUserLink, "id" | "createdAt" | "updatedAt" | "firstTaskHintInteractionId">): Promise<SlackBotUserLink>;
1675
1942
  export declare function getSlackBotUserLink(db: Database, workspaceId: string, connectionId: string, slackUserId: string): Promise<SlackBotUserLink | null>;
1943
+ /**
1944
+ * Resolve, exactly once, whether one Slack interaction's acknowledgement
1945
+ * renders the one-time onboarding hint, and freeze that answer on the
1946
+ * interaction row.
1947
+ *
1948
+ * `slack_bot_post_operations` binds one operation id to one request digest that
1949
+ * covers the message text, so an acknowledgement re-rendered after a crash, a
1950
+ * lost provider response, or a replica race must produce the same bytes or the
1951
+ * ledger rejects it. Rendering therefore reads a frozen fact instead of asking
1952
+ * a mutable question: the first call decides, every later call replays the
1953
+ * stored decision, and unlinking plus relinking the Slack identity cannot flip
1954
+ * an acknowledgement that was already rendered.
1955
+ *
1956
+ * The per-identity claim row is the single source of truth and is replay-stable:
1957
+ * the frozen answer is exactly "this identity's one claim names THIS
1958
+ * interaction". At most one interaction per Slack identity per installation is
1959
+ * therefore granted the hint, whichever resolver wins the claim, and the freeze
1960
+ * is a separate compare-and-set whose losers read back the stored byte rather
1961
+ * than their own recomputed one. This is deliberately not one transaction: the
1962
+ * claim is a home-tenancy row and the freeze is a target-tenancy row, and one
1963
+ * transaction carries one RLS scope. Failure raises instead of degrading to "no
1964
+ * hint": a caller must never bind a post operation to text that depends on an
1965
+ * unresolved answer.
1966
+ */
1967
+ export declare function resolveSlackInteractionFirstTaskHint(db: Database, input: {
1968
+ /** HOME: the installation workspace that owns the identity link. */
1969
+ workspaceId: string;
1970
+ connectionId: string;
1971
+ slackUserId: string;
1972
+ interactionId: string;
1973
+ /**
1974
+ * TARGET: the workspace that owns the interaction row. Defaults to HOME,
1975
+ * which is what every caller means until routing exists.
1976
+ */
1977
+ interactionWorkspaceId?: string;
1978
+ }): Promise<boolean>;
1676
1979
  export declare function deleteSlackBotUserLink(db: Database, workspaceId: string, connectionId: string, slackUserId: string): Promise<boolean>;
1980
+ export declare function enqueueSlackAppHomeRefresh(db: Database, input: Pick<SlackAppHomeRefresh, "accountId" | "workspaceId" | "connectionId" | "slackTeamId" | "slackUserId" | "providerEventId" | "providerViewHash">): Promise<SlackAppHomeRefresh>;
1981
+ export declare function claimSlackAppHomeRefresh(db: Database, claimHolderId: string, claimLeaseMs: number): Promise<SlackAppHomeRefresh | null>;
1982
+ export declare function renewSlackAppHomeRefreshClaim(db: Database, input: {
1983
+ refresh: Pick<SlackAppHomeRefresh, "id" | "accountId" | "workspaceId">;
1984
+ claimHolderId: string;
1985
+ claimLeaseMs: number;
1986
+ }): Promise<boolean>;
1987
+ export declare function settleSlackAppHomeRefresh(db: Database, input: {
1988
+ refresh: Pick<SlackAppHomeRefresh, "id" | "accountId" | "workspaceId" | "desiredRevision">;
1989
+ claimHolderId: string;
1990
+ errorCode?: string | null;
1991
+ }): Promise<boolean>;
1992
+ export declare function releaseSlackAppHomeRefresh(db: Database, input: {
1993
+ refresh: Pick<SlackAppHomeRefresh, "id" | "accountId" | "workspaceId" | "desiredRevision">;
1994
+ claimHolderId: string;
1995
+ errorCode: string;
1996
+ retryAt: Date;
1997
+ }): Promise<boolean>;
1677
1998
  export declare function enqueueSlackInteractionInbox(db: Database, input: Omit<SlackInteractionInboxEntry, "id" | "status" | "claimHolderId" | "claimExpiresAt" | "attemptCount" | "retryAt" | "lastErrorCode" | "reactionContextCheckpoint" | "processedAt" | "createdAt" | "updatedAt">): Promise<{
1678
1999
  inserted: boolean;
1679
2000
  entry: SlackInteractionInboxEntry;
@@ -1696,12 +2017,36 @@ export declare function releaseSlackInteractionInbox(db: Database, input: {
1696
2017
  errorCode: string;
1697
2018
  retryAt: Date;
1698
2019
  }): Promise<boolean>;
1699
- export declare function getOrCreateSlackInteraction(db: Database, input: Omit<SlackInteraction, "id" | "initiatingSlackUserId" | "sessionReservationId" | "sessionId" | "lastDeliveredSessionEventSequence" | "deliveryClaimHolderId" | "deliveryClaimExpiresAt" | "deliveryAttemptCount" | "deliveryRetryAt" | "deliveryLastErrorCode" | "ackSlackMessageTs" | "progressCount" | "terminalDeliveryState" | "createdAt" | "updatedAt"> & {
2020
+ export declare function getOrCreateSlackInteraction(db: Database, input: Omit<SlackInteraction, "id" | "initiatingSlackUserId" | "sessionReservationId" | "sessionId" | "lastDeliveredSessionEventSequence" | "deliveryClaimHolderId" | "deliveryClaimExpiresAt" | "deliveryAttemptCount" | "deliveryRetryAt" | "deliveryLastErrorCode" | "ackSlackMessageTs" | "firstTaskHint" | "progressCount" | "terminalDeliveryState" | "createdAt" | "updatedAt"> & {
1700
2021
  initiatingSlackUserId?: string | null;
1701
2022
  }): Promise<{
1702
2023
  created: boolean;
1703
2024
  interaction: SlackInteraction;
1704
2025
  }>;
2026
+ /**
2027
+ * Connection-scoped thread continuation. `slack_interactions_route_uq` is
2028
+ * `(connection_id, route_key)`, so one Slack thread maps to exactly one
2029
+ * interaction across every workspace this installation can address. The
2030
+ * content-free tenancy probe resolves which workspace that is; the full row is
2031
+ * then read under that workspace's own RLS scope, so nothing is widened.
2032
+ *
2033
+ * `accountId` is the organization the caller is acting for, and the probe is
2034
+ * fenced on it: crossing workspaces within one organization is the whole point,
2035
+ * crossing organizations never is.
2036
+ */
2037
+ export declare function getSlackInteractionByConnectionRoute(db: Database, input: {
2038
+ accountId: string;
2039
+ connectionId: string;
2040
+ routeKey: string;
2041
+ }): Promise<SlackInteraction | null>;
2042
+ /**
2043
+ * Workspace-fenced route lookup.
2044
+ *
2045
+ * This is NOT the thread-continuation read: `slack_interactions_route_uq` is
2046
+ * `(connection_id, route_key)` and therefore connection-global, so a thread that
2047
+ * belongs to another workspace this installation can address is invisible here.
2048
+ * Use `getSlackInteractionByConnectionRoute` for continuation.
2049
+ */
1705
2050
  export declare function getSlackInteractionByRoute(db: Database, workspaceId: string, connectionId: string, routeKey: string): Promise<SlackInteraction | null>;
1706
2051
  export declare function getSlackInteractionById(db: Database, input: {
1707
2052
  accountId: string;
@@ -2028,6 +2373,7 @@ export declare function loadConnectionCredentialForBroker(db: Database, settings
2028
2373
  kind?: ConnectionKind;
2029
2374
  subjectId?: string | null;
2030
2375
  allowSubjectOwned?: boolean;
2376
+ expectedAuthorityGeneration?: number;
2031
2377
  }): Promise<ConnectionCredentialForBroker | null>;
2032
2378
  export declare function workspaceVercelAiGatewayConnectionActive(db: Database, workspaceId: string): Promise<boolean>;
2033
2379
  /** Metadata-only capability revision input; never selects/decrypts the API key. */
@@ -2056,6 +2402,7 @@ export declare function recordConnectionTokenRefresh(db: Database, input: {
2056
2402
  credentialEncrypted: string;
2057
2403
  expiresAt: Date | null;
2058
2404
  grantedScopes?: string[];
2405
+ metadata?: Record<string, unknown>;
2059
2406
  lastRefreshAt: Date;
2060
2407
  subjectId?: string | null;
2061
2408
  }): Promise<boolean>;
@@ -2193,7 +2540,28 @@ export declare function listSocialPosts(db: Database, options: {
2193
2540
  export declare function createScheduledTask(db: Database, input: CreateScheduledTaskInput): Promise<ScheduledTask>;
2194
2541
  export declare function updateScheduledTask(db: Database, workspaceId: string, taskId: string, input: UpdateScheduledTaskInput): Promise<ScheduledTask>;
2195
2542
  export declare function getScheduledTask(db: Database, workspaceId: string, taskId: string): Promise<ScheduledTask | null>;
2543
+ /** Internal delete-recovery lookup; public list/get surfaces hide tombstones. */
2544
+ export declare function getScheduledTaskIncludingDeleted(db: Database, workspaceId: string, taskId: string): Promise<(ScheduledTask & {
2545
+ deletedAt: string | null;
2546
+ }) | null>;
2547
+ /** Task-first deletion lock; call only inside the surrounding lifecycle transaction. */
2548
+ export declare function getScheduledTaskIncludingDeletedForUpdate(db: Database, workspaceId: string, taskId: string): Promise<(ScheduledTask & {
2549
+ deletedAt: string | null;
2550
+ }) | null>;
2196
2551
  export declare function getScheduledTaskPersonalConnectionDelegations(db: Database, workspaceId: string, taskId: string): Promise<McpPersonalConnectionDelegation[]>;
2552
+ /**
2553
+ * Lock and project the exact mutable incident-task authority inside a caller's
2554
+ * dispatch/claim transaction. Returning the frozen personal delegation tuple
2555
+ * from the same row prevents a later task edit from mixing with the task
2556
+ * snapshot used for preflight.
2557
+ */
2558
+ export declare function requireScheduledTaskIncidentAuthorityInTransaction(tx: Database, input: {
2559
+ workspaceId: string;
2560
+ taskId: string;
2561
+ }): Promise<{
2562
+ task: ScheduledTask;
2563
+ personalConnectionDelegations: McpPersonalConnectionDelegation[];
2564
+ }>;
2197
2565
  export declare function getScheduledTaskXaiProviderAccountAuthoritySnapshot(db: Database, workspaceId: string, taskId: string): Promise<XaiProviderAccountAuthoritySnapshotV1>;
2198
2566
  export declare function requireScheduledTask(db: Database, workspaceId: string, taskId: string): Promise<ScheduledTask>;
2199
2567
  export declare class ScheduledTaskTargetConflictError extends Error {
@@ -2219,18 +2587,114 @@ export declare function listScheduledTasks(db: Database, workspaceId: string, li
2219
2587
  export declare function listKnowledgeSourceSyncTasksForConnection(db: Database, workspaceId: string, connectionId: string, pageSize?: number): Promise<Array<ScheduledTask & {
2220
2588
  action: KnowledgeSourceSyncAction;
2221
2589
  }>>;
2222
- export declare function deleteScheduledTask(db: Database, workspaceId: string, taskId: string): Promise<void>;
2590
+ export declare function deleteScheduledTask(db: Database, workspaceId: string, taskId: string, options?: {
2591
+ connectorCleanupSubjectId?: string;
2592
+ connectorCleanupCompleted?: boolean;
2593
+ expectedAuthorityRevision?: number;
2594
+ expectedExecutionDigest?: string;
2595
+ }): Promise<{
2596
+ cleanup: TemporalScheduleCleanupClaim | null;
2597
+ changed: boolean;
2598
+ }>;
2223
2599
  export declare function createScheduledTaskRun(db: Database, input: {
2600
+ runId?: string;
2224
2601
  workspaceId: string;
2225
2602
  taskId: string;
2603
+ /** Exact task snapshot read by the dispatching worker. */
2604
+ taskAuthorityRevision?: number | null;
2605
+ /** Exact task snapshot read by the dispatching worker. */
2606
+ taskExecutionDigest?: string | null;
2226
2607
  triggerType: ScheduledTaskTriggerType;
2227
2608
  /** Stable Temporal workflow/activity producer identity for replay repair. */
2228
2609
  producerKey?: string | null;
2229
2610
  scheduledAt?: Date | null;
2230
2611
  firedAt?: Date;
2612
+ acceptedExecutionSnapshot?: ScheduledTaskRunAcceptedExecutionType | null;
2231
2613
  }): Promise<ScheduledTaskRun>;
2614
+ export declare function getScheduledTaskRunAcceptedExecution(db: Database, input: {
2615
+ workspaceId: string;
2616
+ runId: string;
2617
+ }): Promise<ScheduledTaskRunAcceptedExecutionType | null>;
2618
+ export declare function getScheduledTaskRunByProducerKey(db: Database, input: {
2619
+ workspaceId: string;
2620
+ taskId: string;
2621
+ triggerType: ScheduledTaskTriggerType;
2622
+ producerKey: string;
2623
+ }): Promise<ScheduledTaskRun | null>;
2624
+ export type ScheduledTaskRunPersonalResourceAuthority = {
2625
+ taskId: string;
2626
+ taskAuthorityRevision: number;
2627
+ executionDigest: string;
2628
+ initiatingHumanSubjectId: string;
2629
+ resources: Array<{
2630
+ resourceKind: "variable_set" | "rig";
2631
+ resourceId: string;
2632
+ resourceVersionId: string;
2633
+ selectionSources: string[];
2634
+ authorityId: string;
2635
+ authorityGeneration: number;
2636
+ grantId: string;
2637
+ grantGeneration: number;
2638
+ grantMode: "once" | "session" | "always";
2639
+ }>;
2640
+ };
2641
+ export declare function getScheduledTaskRunPersonalResourceAuthority(db: Database, input: {
2642
+ accountId: string;
2643
+ workspaceId: string;
2644
+ runId: string;
2645
+ }): Promise<ScheduledTaskRunPersonalResourceAuthority | null>;
2646
+ export declare function materializeScheduledTaskReusableSessionFromRun(db: Database, input: {
2647
+ accountId: string;
2648
+ workspaceId: string;
2649
+ taskId: string;
2650
+ runId: string;
2651
+ sessionId: string;
2652
+ sourceTaskAuthorityRevision: number;
2653
+ sourceExecutionDigest: string;
2654
+ }): Promise<number>;
2655
+ export declare function bindScheduledTaskRunSessionInTransaction(tx: Database, input: {
2656
+ accountId: string;
2657
+ workspaceId: string;
2658
+ runId: string;
2659
+ sessionId: string;
2660
+ }): Promise<void>;
2661
+ export declare function getScheduledTaskPersonalResourceAuthoritySubject(db: Database, input: {
2662
+ accountId: string;
2663
+ workspaceId: string;
2664
+ taskId: string;
2665
+ taskAuthorityRevision: number;
2666
+ }): Promise<string | null>;
2667
+ export declare function getScheduledTaskRevisionAuthoritySubject(db: Database, input: {
2668
+ accountId: string;
2669
+ workspaceId: string;
2670
+ taskId: string;
2671
+ taskAuthorityRevision: number;
2672
+ }): Promise<string | null>;
2673
+ export declare function getScheduledTaskRevisionAuthority(db: Database, input: {
2674
+ accountId: string;
2675
+ workspaceId: string;
2676
+ taskId: string;
2677
+ taskAuthorityRevision: number;
2678
+ }): Promise<{
2679
+ subjectId: string;
2680
+ organizationMembershipId: string;
2681
+ membershipAuthorizationRevision: number;
2682
+ } | null>;
2232
2683
  /** Failure settlement must not rewrite a source already committed as dispatched. */
2233
2684
  export declare function markScheduledTaskRunFailedIfQueued(db: Database, workspaceId: string, runId: string, error: string): Promise<void>;
2685
+ export declare function markScheduledTaskRunSkippedIfQueued(db: Database, input: {
2686
+ workspaceId: string;
2687
+ runId: string;
2688
+ sessionId: string;
2689
+ error: string;
2690
+ }): Promise<void>;
2691
+ /** Claim-time stale-authority settlement; no model/tool/sandbox work has started. */
2692
+ export declare function markScheduledTaskRunAuthorityRejectedInTransaction(tx: Database, input: {
2693
+ workspaceId: string;
2694
+ sessionId: string;
2695
+ runId: string;
2696
+ error?: string;
2697
+ }): Promise<void>;
2234
2698
  export declare function updateScheduledTaskRun(db: Database, workspaceId: string, runId: string, input: Partial<{
2235
2699
  status: ScheduledTaskRunStatus;
2236
2700
  sessionId: string | null;
@@ -2246,13 +2710,17 @@ export declare function settleScheduledTaskRunInTransaction(tx: Database, input:
2246
2710
  workspaceId: string;
2247
2711
  runId: string;
2248
2712
  sessionId: string;
2249
- triggerEventId: string;
2250
- status: "dispatched";
2713
+ triggerEventId: string | null;
2714
+ status: "dispatched" | "skipped";
2715
+ error?: string | null;
2251
2716
  }): Promise<void>;
2252
2717
  export declare function listScheduledTaskRuns(db: Database, workspaceId: string, taskId: string, limit?: number): Promise<ScheduledTaskRun[]>;
2253
2718
  export declare function createVariableSet(db: Database, input: {
2254
2719
  accountId: string;
2255
2720
  workspaceId: string;
2721
+ scope?: VariableSet["scope"];
2722
+ subjectId?: string;
2723
+ allowOrganization?: boolean;
2256
2724
  name: string;
2257
2725
  description?: string | null;
2258
2726
  variables?: Array<{
@@ -2260,9 +2728,14 @@ export declare function createVariableSet(db: Database, input: {
2260
2728
  valueEncrypted: string;
2261
2729
  }>;
2262
2730
  }): Promise<VariableSet>;
2263
- export declare function listVariableSets(db: Database, workspaceId: string): Promise<VariableSet[]>;
2264
- export declare function getVariableSet(db: Database, workspaceId: string, variableSetId: string): Promise<VariableSet | null>;
2265
- export declare function getVariableSetByName(db: Database, workspaceId: string, name: string): Promise<VariableSet | null>;
2731
+ export type VariableSetAccessContext = {
2732
+ accountId: string;
2733
+ workspaceId: string;
2734
+ subjectId: string;
2735
+ };
2736
+ export declare function listVariableSets(db: Database, context: VariableSetAccessContext): Promise<VariableSet[]>;
2737
+ export declare function getVariableSet(db: Database, context: VariableSetAccessContext, variableSetId: string): Promise<VariableSet | null>;
2738
+ export declare function getVariableSetByName(db: Database, context: VariableSetAccessContext, name: string, scope?: VariableSet["scope"]): Promise<VariableSet | null>;
2266
2739
  export type VariableSetSecretAuditActor = {
2267
2740
  kind: "subject";
2268
2741
  } | {
@@ -2294,22 +2767,35 @@ export declare function readVariableSetSecretAtomically(db: Database, input: {
2294
2767
  actor: VariableSetSecretAuditActor;
2295
2768
  decrypt: (valueEncrypted: string) => string;
2296
2769
  }): Promise<VariableSetSecret | null>;
2297
- export declare function updateVariableSet(db: Database, workspaceId: string, variableSetId: string, input: {
2770
+ export declare function updateVariableSet(db: Database, context: VariableSetAccessContext, variableSetId: string, input: {
2298
2771
  name?: string;
2299
2772
  description?: string | null;
2773
+ allowOrganization?: boolean;
2300
2774
  }): Promise<VariableSet>;
2301
- export declare function deleteVariableSet(db: Database, workspaceId: string, variableSetId: string): Promise<boolean>;
2302
- export declare function countVariableSets(db: Database, workspaceId: string): Promise<number>;
2775
+ export declare class VariableSetAttachedError extends Error {
2776
+ readonly name = "VariableSetAttachedError";
2777
+ constructor(cause?: unknown);
2778
+ }
2779
+ export declare function deleteVariableSet(db: Database, context: VariableSetAccessContext, variableSetId: string, options?: {
2780
+ allowOrganization?: boolean;
2781
+ }): Promise<boolean>;
2782
+ export declare function countVariableSets(db: Database, context: VariableSetAccessContext, scope?: VariableSet["scope"]): Promise<number>;
2303
2783
  export declare function countScheduledTasksUsingVariableSet(db: Database, workspaceId: string, variableSetId: string): Promise<number>;
2304
2784
  export declare function countActiveSessionsUsingVariableSet(db: Database, workspaceId: string, variableSetId: string): Promise<number>;
2305
2785
  export declare function setVariableSetVariable(db: Database, input: {
2306
2786
  accountId: string;
2307
2787
  workspaceId: string;
2788
+ subjectId: string;
2308
2789
  variableSetId: string;
2309
2790
  name: string;
2310
2791
  valueEncrypted: string;
2792
+ allowOrganization?: boolean;
2311
2793
  }): Promise<VariableSetVariableMetadata>;
2312
- export declare function deleteVariableSetVariable(db: Database, workspaceId: string, variableSetId: string, name: string): Promise<boolean>;
2794
+ export declare function deleteVariableSetVariable(db: Database, input: VariableSetAccessContext & {
2795
+ variableSetId: string;
2796
+ name: string;
2797
+ allowOrganization?: boolean;
2798
+ }): Promise<boolean>;
2313
2799
  export declare class RigChangeTransitionError extends Error {
2314
2800
  readonly changeId: string;
2315
2801
  readonly fromStatus: string;
@@ -2338,14 +2824,22 @@ export type RigVersionContentInput = {
2338
2824
  export declare function createRig(db: Database, input: {
2339
2825
  accountId: string;
2340
2826
  workspaceId: string;
2827
+ scope?: Rig["scope"];
2828
+ subjectId?: string;
2829
+ allowOrganization?: boolean;
2341
2830
  name: string;
2342
2831
  description?: string | null;
2343
2832
  createdBy?: string | null;
2344
2833
  initialVersion?: RigVersionContentInput;
2345
2834
  }): Promise<Rig>;
2346
- export declare function listRigs(db: Database, workspaceId: string): Promise<Rig[]>;
2347
- export declare function getRig(db: Database, workspaceId: string, rigId: string): Promise<Rig | null>;
2348
- export declare function getRigByName(db: Database, workspaceId: string, name: string): Promise<Rig | null>;
2835
+ export type RigAccessContext = {
2836
+ accountId: string;
2837
+ workspaceId: string;
2838
+ subjectId: string;
2839
+ };
2840
+ export declare function listRigs(db: Database, access: string | RigAccessContext): Promise<Rig[]>;
2841
+ export declare function getRig(db: Database, access: string | RigAccessContext, rigId: string): Promise<Rig | null>;
2842
+ export declare function getRigByName(db: Database, access: string | RigAccessContext, name: string, scope?: Rig["scope"]): Promise<Rig | null>;
2349
2843
  export declare function updateRig(db: Database, workspaceId: string, rigId: string, input: {
2350
2844
  name?: string;
2351
2845
  description?: string | null;
@@ -2355,6 +2849,14 @@ export declare function deleteRigIfNoActiveSessions(db: Database, workspaceId: s
2355
2849
  deleted: boolean;
2356
2850
  activeSessionCount: number;
2357
2851
  }>;
2852
+ export declare function updateScopedRig(db: Database, access: RigAccessContext, rigId: string, input: {
2853
+ name?: string;
2854
+ description?: string | null;
2855
+ allowOrganization?: boolean;
2856
+ }): Promise<Rig>;
2857
+ export declare function revokeScopedRig(db: Database, access: RigAccessContext, rigId: string, options?: {
2858
+ allowOrganization?: boolean;
2859
+ }): Promise<void>;
2358
2860
  export declare class ChannelNameConflictError extends Error {
2359
2861
  constructor(name: string);
2360
2862
  }
@@ -2373,14 +2875,21 @@ export declare function getChannel(db: Database, workspaceId: string, channelId:
2373
2875
  export declare function updateChannel(db: Database, workspaceId: string, channelId: string, input: {
2374
2876
  name?: string | undefined;
2375
2877
  description?: string | null | undefined;
2878
+ pinned?: boolean | undefined;
2376
2879
  }): Promise<Channel | null>;
2377
2880
  export declare function deleteChannel(db: Database, workspaceId: string, channelId: string): Promise<boolean>;
2881
+ /**
2882
+ * Replaces the complete project order in one workspace-scoped transaction.
2883
+ * Callers must supply every current project exactly once so a stale drag can
2884
+ * never silently discard a concurrently created project.
2885
+ */
2886
+ export declare function reorderChannels(db: Database, workspaceId: string, channelIds: readonly string[]): Promise<Channel[] | null>;
2378
2887
  export declare function setSessionChannel(db: Database, input: {
2379
2888
  workspaceId: string;
2380
2889
  sessionId: string;
2381
2890
  channelId: string | null;
2382
2891
  }): Promise<boolean>;
2383
- export declare function countRigs(db: Database, workspaceId: string): Promise<number>;
2892
+ export declare function countRigs(db: Database, access: string | RigAccessContext, scope?: Rig["scope"]): Promise<number>;
2384
2893
  export declare function countSessionsUsingRig(db: Database, workspaceId: string, rigId: string): Promise<number>;
2385
2894
  export declare function createRigVersion(db: Database, workspaceId: string, rigId: string, input: RigVersionContentInput, options?: {
2386
2895
  activate?: boolean;
@@ -2416,6 +2925,29 @@ export declare function listRigVersionMonitoringSummaries(db: Database, workspac
2416
2925
  total: number;
2417
2926
  }>;
2418
2927
  export declare function getRigVersion(db: Database, workspaceId: string, rigId: string, versionId: string): Promise<RigVersion | null>;
2928
+ /** Credential-free exact retained Rig metadata under the target workspace's
2929
+ * scoped organization/user authority. Unlike the physical-workspace helpers,
2930
+ * this remains valid for a personal-origin Rig granted into another workspace. */
2931
+ export declare function getScheduledScopedRigVersionMetadata(db: Database, access: RigAccessContext, rigId: string, versionId: string): Promise<{
2932
+ name: string;
2933
+ version: RigVersion;
2934
+ health: RigVerificationHealth;
2935
+ } | null>;
2936
+ export declare function materializeRigVersionForAttempt(db: Database, input: {
2937
+ accountId: string;
2938
+ workspaceId: string;
2939
+ subjectId: string | null;
2940
+ sessionId: string;
2941
+ turnId: string;
2942
+ attemptId: string;
2943
+ executionGeneration: number;
2944
+ }): Promise<{
2945
+ rigName: string;
2946
+ version: RigVersion;
2947
+ } | null>;
2948
+ /** Metadata-only health for one exact frozen rig version. Never reads setup,
2949
+ * variable values, credential material, or the currently active version. */
2950
+ export declare function getRigVersionHealth(db: Database, workspaceId: string, rigId: string, versionId: string): Promise<RigVerificationHealth | null>;
2419
2951
  export declare function getRigVersionById(db: Database, workspaceId: string, versionId: string): Promise<RigVersion | null>;
2420
2952
  export type RigProviderImageBuildClaim = {
2421
2953
  status: "claimed";
@@ -2491,16 +3023,286 @@ export declare function beginRigChangeVerificationAttempt(db: Database, workspac
2491
3023
  startedAt: string;
2492
3024
  allowAlreadyVerifying?: boolean;
2493
3025
  }): Promise<RigChange>;
3026
+ export declare function getScheduledVariableSetExpectedGenerationForAttempt(db: Database, input: {
3027
+ accountId: string;
3028
+ workspaceId: string;
3029
+ /** Actor subject for RLS (a service initiator on pure scheduled turns). */
3030
+ subjectId: string;
3031
+ /** Exact causal human, or null for a pure service attempt (workspace/org sets only). */
3032
+ initiatingHumanSubjectId: string | null;
3033
+ sessionId: string;
3034
+ turnId: string;
3035
+ attemptId: string;
3036
+ executionGeneration: number;
3037
+ variableSetId: string;
3038
+ }): Promise<number | null>;
2494
3039
  /**
2495
3040
  * The ONLY helper that selects value_encrypted. Used exclusively by the worker
2496
3041
  * activity that materializes a sandbox for a run whose session carries an
2497
3042
  * variableSet attachment. Do not call from API routes: values are write-only.
2498
3043
  */
2499
- export declare function getVariableSetValuesForRun(db: Database, workspaceId: string, variableSetId: string): Promise<{
3044
+ /**
3045
+ * Live session authority epoch, for stamping viewer-facing claims (stream
3046
+ * tokens, viewer holders). Identity/epoch only; NULL when the session is not
3047
+ * visible in this workspace.
3048
+ */
3049
+ export declare function getSessionAuthorityEpoch(db: Database, input: {
3050
+ accountId: string;
3051
+ workspaceId: string;
3052
+ sessionId: string;
3053
+ }): Promise<number | null>;
3054
+ /**
3055
+ * ORACLE, NOT AN AUTHORIZATION. It sets `opengeni.subject_id` from its own
3056
+ * argument, so `list_self_organization_memberships`' `42501` guard is satisfied
3057
+ * for whatever subject the caller NAMES: it answers for ANY subject and cannot
3058
+ * establish who the caller is. Passing it a request-derived subject is a
3059
+ * vulnerability. Call it only about a subject you are already entitled to ask
3060
+ * about — one authenticated out of band, or the frozen owner of a delegation
3061
+ * you already hold. The `named` prefix is the warning: you are naming a subject,
3062
+ * not proving you are one.
3063
+ *
3064
+ * When the subject IS the caller, use {@link subjectHasLiveWorkspaceAuthorityInScope}
3065
+ * instead: it refuses to set the subject GUC at all, so the oracle shape is
3066
+ * unrepresentable there. Both exist on purpose — some callers legitimately ask
3067
+ * about a non-caller subject, which the in-scope variant cannot express.
3068
+ *
3069
+ * The authority rule itself lives in that in-scope variant; this is a scope
3070
+ * wrapper over it, so there is one implementation.
3071
+ *
3072
+ * The prior `opengeni.subject_id` is restored before returning, so probing a
3073
+ * named subject cannot leak it into the rest of a caller's transaction.
3074
+ */
3075
+ export declare function namedSubjectHasLiveWorkspaceAuthority(db: Database, input: {
3076
+ accountId: string;
3077
+ workspaceId: string;
3078
+ subjectId: string;
3079
+ }): Promise<boolean>;
3080
+ /**
3081
+ * The ONLY place a Slack request may reach a managed human's personal
3082
+ * workspace. Returns the grant a routed Slack target may act under, or null.
3083
+ *
3084
+ * A Slack webhook has no caller subject: `subjectId` is read out of band from a
3085
+ * durable `slack_bot_user_links` row, whose only writers sit behind a verified
3086
+ * managed-human cookie or a `members:manage` grant. That is why this uses
3087
+ * {@link namedSubjectHasLiveWorkspaceAuthority} rather than the in-scope
3088
+ * variant - the subject was authenticated elsewhere, and this seam is naming
3089
+ * it, not proving it. Callers must therefore never pass a subject taken from a
3090
+ * Slack payload; pass only `link.subjectId`.
3091
+ *
3092
+ * Ordinary membership first, then a derived-and-fenced pointer path (the same
3093
+ * shape as `requirePersonalGitHubCallbackGrant`):
3094
+ *
3095
+ * - `getWorkspaceGrant` is a bare `workspace_memberships` join and is NOT
3096
+ * widened here, because `accessGrantAuthorization` calls it for every
3097
+ * principal kind including API keys and delegated bearers; widening it would
3098
+ * hand a bearer principal personal-workspace access.
3099
+ * - The pointer path accepts only the subject's OWN `personalWorkspaceId` from
3100
+ * an ACTIVE membership in exactly `targetAccountId`, then re-checks live
3101
+ * authority. The workspace id is never taken from a route row or a Slack
3102
+ * payload - it must equal the pointer.
3103
+ * - No Slack branch is ever added to `canonicalManagedCookieContexts`: that
3104
+ * `WeakSet` has exactly one writer, the Better Auth cookie branch of
3105
+ * `resolveAccessContext`, and a Slack-signed webhook can never be in it.
3106
+ *
3107
+ * Slack sessions stay `workspace_shared`: this grant is passed as an ordinary
3108
+ * grant, and `createSessionForRequest` is still called WITHOUT its
3109
+ * `authorization` argument, so Slack privacy remains
3110
+ * `slack_interactions.visibility`.
3111
+ */
3112
+ export declare function resolveSlackTargetAuthority(db: Database, input: {
3113
+ subjectId: string;
3114
+ targetAccountId: string;
3115
+ targetWorkspaceId: string;
3116
+ }): Promise<AccessGrant | null>;
3117
+ /**
3118
+ * Read-only organization tenancy inventory (0285): content-free counts of
3119
+ * every legacy-attribution population the backfill/parity program gates on.
3120
+ * Integers only - no identities, names, keys, or values.
3121
+ */
3122
+ export declare function inventoryOrganizationTenancy(db: Database, input: {
3123
+ organizationId: string;
3124
+ }): Promise<Record<string, unknown>>;
3125
+ /**
3126
+ * How much independent evidence a parity gate carries.
3127
+ *
3128
+ * - `constraint` / `trigger`: the property is already enforced by the physical
3129
+ * schema, so the gate is a shadow verification that the enforcement is still
3130
+ * present and validated - it cannot be the first line of defence.
3131
+ * - `runtime`: nothing in the schema prevents the violation. These are the
3132
+ * gates that carry real evidence about a cutover.
3133
+ */
3134
+ export type TenancyParityGateBasis = "constraint" | "trigger" | "runtime";
3135
+ export interface TenancyParityGateDefinition {
3136
+ readonly id: string;
3137
+ readonly title: string;
3138
+ readonly basis: TenancyParityGateBasis;
3139
+ /** What a violation means, and why it must never resolve to user authority. */
3140
+ readonly rule: string;
3141
+ }
3142
+ export interface TenancyParityGateResult extends TenancyParityGateDefinition {
3143
+ readonly status: "pass" | "fail";
3144
+ readonly violations: number;
3145
+ /** Bounded row identifiers only - never subjects, names, keys, or values. */
3146
+ readonly evidence: readonly string[];
3147
+ readonly evidenceTruncated: boolean;
3148
+ }
3149
+ export interface TenancyParityLaneDefinition {
3150
+ readonly id: string;
3151
+ readonly title: string;
3152
+ /**
3153
+ * `drainable`: a backfill can take it to zero.
3154
+ * `observation`: immutable history, reported over a bounded recent window so
3155
+ * that "the lane stopped being exercised" is still a reachable zero.
3156
+ */
3157
+ readonly kind: "drainable" | "observation";
3158
+ /** The workstream that owns draining this lane, when it is not this one. */
3159
+ readonly owner?: string;
3160
+ }
3161
+ export interface TenancyParityLaneResult extends TenancyParityLaneDefinition {
3162
+ readonly count: number;
3163
+ readonly drained: boolean;
3164
+ }
3165
+ export interface TenancyParityUnverifiable {
3166
+ readonly id: string;
3167
+ readonly title: string;
3168
+ /** Why no honest number exists for this property today. */
3169
+ readonly reason: string;
3170
+ }
3171
+ export interface TenancyParityReport {
3172
+ readonly schemaVersion: 1;
3173
+ readonly organizationId: string;
3174
+ readonly generatedAt: string;
3175
+ readonly evidenceLimit: number;
3176
+ readonly observationWindowDays: number;
3177
+ /** `fail` when any invariant gate has at least one violation. */
3178
+ readonly status: "pass" | "fail";
3179
+ /** Every gate passes AND every compatibility lane is drained. */
3180
+ readonly cutoverReady: boolean;
3181
+ readonly summary: {
3182
+ readonly gates: number;
3183
+ readonly gatesFailed: number;
3184
+ readonly violations: number;
3185
+ readonly lanes: number;
3186
+ readonly lanesUndrained: number;
3187
+ readonly unverifiable: number;
3188
+ };
3189
+ readonly gates: readonly TenancyParityGateResult[];
3190
+ readonly lanes: readonly TenancyParityLaneResult[];
3191
+ readonly unverifiable: readonly TenancyParityUnverifiable[];
3192
+ }
3193
+ /**
3194
+ * Ordered catalog of the organization-tenancy parity gates (phase E). Every id
3195
+ * matches a key emitted by `check_organization_tenancy_parity` (migration
3196
+ * 0298); a gate present here but absent from the seam is reported as a
3197
+ * structural mismatch rather than silently passing.
3198
+ */
3199
+ export declare const TENANCY_PARITY_GATES: readonly TenancyParityGateDefinition[];
3200
+ /**
3201
+ * Compatibility lanes. These are legacy populations, NOT invariant violations:
3202
+ * a non-zero lane blocks a cutover but is not schema corruption.
3203
+ */
3204
+ export declare const TENANCY_PARITY_LANES: readonly TenancyParityLaneDefinition[];
3205
+ /**
3206
+ * Properties phase E names that have no honest measurement today. They are
3207
+ * reported explicitly instead of being emitted as a counter that can never
3208
+ * reach zero.
3209
+ */
3210
+ export declare const TENANCY_PARITY_UNVERIFIABLE: readonly TenancyParityUnverifiable[];
3211
+ /**
3212
+ * Compose the operator-facing parity report from the raw seam output. Pure and
3213
+ * total: an id the seam did not emit is reported as a failing gate with an
3214
+ * explicit structural-mismatch violation rather than silently passing.
3215
+ */
3216
+ export declare function composeTenancyParityReport(raw: Record<string, unknown>, options?: {
3217
+ generatedAt?: string;
3218
+ }): TenancyParityReport;
3219
+ /**
3220
+ * Read-only organization tenancy parity check (0298, phase E). Verifies the
3221
+ * structural tenancy invariants, reports the compatibility lanes, and names the
3222
+ * properties that are currently unverifiable. It never writes, repairs, or
3223
+ * widens anything, and no reported mismatch is resolved toward user authority.
3224
+ */
3225
+ export declare function checkOrganizationTenancyParity(db: Database, input: {
3226
+ organizationId: string;
3227
+ evidenceLimit?: number;
3228
+ observationWindowDays?: number;
3229
+ generatedAt?: string;
3230
+ }): Promise<TenancyParityReport>;
3231
+ /**
3232
+ * Organization-tenancy phase D classification assertion (0291) for Variable Sets, Rigs, and
3233
+ * Connected Machines. Read-only over every resource table: it proves each row
3234
+ * already carries an explicit terminal authority classification and never
3235
+ * rewrites one. Supplying `runKey` additionally records the verdicts durably
3236
+ * through the 0286 tenancy backfill ledger (one receipt per family plus one
3237
+ * append-only unresolved row per resource that could not be proven); the
3238
+ * result reports `ledgerAvailable` so a run that could not record its
3239
+ * obligations is visible rather than silent. A run key may be used once - the
3240
+ * ledger refuses to re-open a settled receipt.
3241
+ */
3242
+ export declare function verifyOrganizationResourceClassification(db: Database, input: {
3243
+ organizationId: string;
3244
+ runKey?: string | null;
3245
+ }): Promise<Record<string, unknown>>;
3246
+ /**
3247
+ * Organization-tenancy phase D session ownership classification (0297). Read-only over
3248
+ * `sessions`: it proves every attributed session points at one live,
3249
+ * internally consistent organization membership, and names a fixed reason code
3250
+ * for every session it refuses to attribute. Supplying `runKey` additionally
3251
+ * records those refusals durably through the tenancy backfill ledger (one
3252
+ * `sessions` receipt plus one append-only unresolved row each); the result
3253
+ * reports `ledgerAvailable` so a run that could not record its obligations is
3254
+ * visible rather than silent. A run key may be used once - the ledger refuses
3255
+ * to re-open a settled receipt.
3256
+ *
3257
+ * It never writes a session row and never infers user authority from
3258
+ * `created_by`, a default workspace, or current workspace access.
3259
+ */
3260
+ export declare function classifyOrganizationSessionOwnership(db: Database, input: {
3261
+ organizationId: string;
3262
+ runKey?: string | null;
3263
+ }): Promise<Record<string, unknown>>;
3264
+ /**
3265
+ * Organization-tenancy phase D session ownership backfill (0297). One bounded, resumable,
3266
+ * idempotent batch of the only two deterministic repairs: a session sitting in
3267
+ * exactly one active membership's personal workspace whose creator subject is
3268
+ * that same membership, and the parent-inheritance closure migration 0225's own
3269
+ * trigger would have produced. `dryRun` defaults to true. Candidates are
3270
+ * claimed with `FOR UPDATE ... SKIP LOCKED`, so concurrent drivers never
3271
+ * contend; keep calling while `moreLikely` is true.
3272
+ */
3273
+ export declare function backfillOrganizationSessionOwnership(db: Database, input: {
3274
+ organizationId: string;
3275
+ limit?: number;
3276
+ dryRun?: boolean;
3277
+ runKey?: string | null;
3278
+ }): Promise<Record<string, unknown>>;
3279
+ export declare function getVariableSetValuesForRun(db: Database, input: {
3280
+ accountId: string;
3281
+ workspaceId: string;
3282
+ variableSetId: string;
3283
+ authority: {
3284
+ kind: "agent_attempt";
3285
+ subjectId: string;
3286
+ sessionId: string;
3287
+ turnId: string;
3288
+ attemptId: string;
3289
+ executionGeneration: number;
3290
+ initiatingHumanSubjectId?: string | null;
3291
+ } | {
3292
+ kind: "session_attach";
3293
+ sessionId: string;
3294
+ /** The authenticated route subject driving the attach (0282); null
3295
+ * records the explicit legacy sentinel `service:session`. */
3296
+ subjectId: string | null;
3297
+ initiatingHumanSubjectId?: string | null;
3298
+ };
3299
+ }): Promise<{
2500
3300
  variableSet: {
2501
3301
  id: string;
2502
3302
  name: string;
2503
3303
  description: string | null;
3304
+ scope: VariableSet["scope"];
3305
+ generation: number;
2504
3306
  };
2505
3307
  values: Record<string, string>;
2506
3308
  } | null>;
@@ -2532,6 +3334,8 @@ export type VariableSetForRun = {
2532
3334
  id: string;
2533
3335
  name: string;
2534
3336
  description: string | null;
3337
+ scope: VariableSet["scope"];
3338
+ generation: number;
2535
3339
  values: Record<string, string>;
2536
3340
  };
2537
3341
  /**
@@ -2548,7 +3352,27 @@ export type VariableSetForRun = {
2548
3352
  * missing key or a deleted variableSet throws (names/ids only in messages) instead
2549
3353
  * of silently running without the secrets the run expects.
2550
3354
  */
2551
- export declare function loadVariableSetForRun(db: Database, settings: Settings, workspaceId: string, variableSetId: string | null): Promise<VariableSetForRun | null>;
3355
+ export declare function loadVariableSetForRun(db: Database, settings: Settings, input: {
3356
+ accountId: string;
3357
+ workspaceId: string;
3358
+ variableSetId: string | null;
3359
+ authority: {
3360
+ kind: "agent_attempt";
3361
+ subjectId: string;
3362
+ sessionId: string;
3363
+ turnId: string;
3364
+ attemptId: string;
3365
+ executionGeneration: number;
3366
+ initiatingHumanSubjectId?: string | null;
3367
+ } | {
3368
+ kind: "session_attach";
3369
+ sessionId: string;
3370
+ /** The authenticated route subject driving the attach (0282); null
3371
+ * records the explicit legacy sentinel `service:session`. */
3372
+ subjectId: string | null;
3373
+ initiatingHumanSubjectId?: string | null;
3374
+ };
3375
+ }): Promise<VariableSetForRun | null>;
2552
3376
  /** @deprecated use loadVariableSetForRun */
2553
3377
  export declare const loadWorkspaceEnvironmentForRun: typeof loadVariableSetForRun;
2554
3378
  /** @deprecated use VariableSetForRun */
@@ -3575,7 +4399,7 @@ export type ConnectorActionInvocation = {
3575
4399
  toolName: string;
3576
4400
  arguments: unknown;
3577
4401
  /** Explicit per-session MCP approval, rather than a connector-policy decision. */
3578
- approvalMode?: "session_mcp";
4402
+ approvalMode?: "session_mcp" | "connector_write";
3579
4403
  };
3580
4404
  export type PrepareConnectorActionApprovalResult = {
3581
4405
  managed: false;
@@ -3597,7 +4421,7 @@ export type BeginConnectorActionExecutionResult = {
3597
4421
  } | {
3598
4422
  allowed: false;
3599
4423
  managed: true;
3600
- reason: "approval_required" | "blocked" | "rejected" | "already_executed" | "uncertain_retry";
4424
+ reason: "approval_required" | "blocked" | "rejected" | "already_executed" | "uncertain_retry" | "not_executed";
3601
4425
  requestId: string;
3602
4426
  actionFingerprint: string;
3603
4427
  };
@@ -3639,6 +4463,23 @@ export declare function upsertConnectorActionPolicy(db: Database, input: {
3639
4463
  policy: typeof schema.connectorActionPolicies.$inferSelect;
3640
4464
  changed: boolean;
3641
4465
  }>;
4466
+ /**
4467
+ * Install a risk-appropriate connector default without overwriting an explicit
4468
+ * user choice that already exists for the same immutable connector action.
4469
+ */
4470
+ export declare function ensureConnectorActionPolicyDefault(db: Database, input: {
4471
+ accountId: string;
4472
+ workspaceId: string;
4473
+ subjectId: string;
4474
+ connectionId: string;
4475
+ serverId: string;
4476
+ toolName: string;
4477
+ actionName: string;
4478
+ policy: ConnectorActionPolicyDecision;
4479
+ }): Promise<{
4480
+ policy: typeof schema.connectorActionPolicies.$inferSelect;
4481
+ changed: boolean;
4482
+ }>;
3642
4483
  export declare function prepareConnectorActionApproval(db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation): Promise<PrepareConnectorActionApprovalResult>;
3643
4484
  export declare function beginConnectorActionExecution(db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation): Promise<BeginConnectorActionExecutionResult>;
3644
4485
  export declare function completeConnectorActionExecution(db: Database, input: {
@@ -3646,7 +4487,7 @@ export declare function completeConnectorActionExecution(db: Database, input: {
3646
4487
  workspaceId: string;
3647
4488
  requestId: string;
3648
4489
  attemptId: string;
3649
- outcome: "completed" | "uncertain";
4490
+ outcome: "completed" | "uncertain" | "not_executed";
3650
4491
  }): Promise<void>;
3651
4492
  /** Read the persisted deployment fallback; process configuration is not policy authority. */
3652
4493
  export declare function getNestedAgentDepthDeploymentPolicy(db: Database): Promise<NestedAgentDepthDeploymentPolicy>;
@@ -3658,12 +4499,16 @@ export declare class SessionIdConflictError extends Error {
3658
4499
  readonly sessionId: string;
3659
4500
  constructor(sessionId: string);
3660
4501
  }
4502
+ export declare class SessionCreateIdempotencyConflictError extends Error {
4503
+ constructor();
4504
+ }
3661
4505
  export type SessionCreateInput = {
3662
4506
  requestedSessionId?: string;
3663
4507
  accountId: string;
3664
4508
  workspaceId: string;
4509
+ visibility?: "user_private" | "workspace_shared";
3665
4510
  initialMessage: string;
3666
- initialTurnInstructions?: string | null;
4511
+ initialModelContext?: string | null;
3667
4512
  resources: ResourceRef[];
3668
4513
  skills?: SessionSkill[];
3669
4514
  tools?: ToolRef[];
@@ -3673,6 +4518,8 @@ export type SessionCreateInput = {
3673
4518
  createdByContext?: TurnInitiatorContext;
3674
4519
  createdByActor?: AgentSessionCreationActor | null;
3675
4520
  model: string;
4521
+ reasoningEffort: ReasoningEffort;
4522
+ latencyMode: LatencyMode;
3676
4523
  sandboxBackend: SandboxBackend;
3677
4524
  variableSetId?: string | null;
3678
4525
  rigId?: string | null;
@@ -3686,8 +4533,16 @@ export type SessionCreateInput = {
3686
4533
  createIdempotencyKey?: string | null;
3687
4534
  sandboxGroupId?: string | null;
3688
4535
  sandboxOs?: SandboxOs;
4536
+ /** Exact accepted generated-session compaction policy; internal lifecycle callers only. */
4537
+ frozenCodexCompactionMode?: Session["codexCompactionMode"];
4538
+ /** Exact accepted root-session depth policy; internal lifecycle callers only. */
4539
+ frozenNestedAgentDepthPolicy?: {
4540
+ effectiveMaxNestedAgentDepth: number;
4541
+ nestedAgentDepthPolicySource: NestedAgentDepthPolicySource;
4542
+ };
3689
4543
  mcpServers?: CreateSessionMcpServerInput[];
3690
4544
  personalConnectionDelegations?: McpPersonalConnectionDelegation[];
4545
+ initialPersonalResourceAttachmentIntent?: PersonalResourceAttachmentIntent | null;
3691
4546
  initialXaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1;
3692
4547
  maxNestedAgentDepthOverride?: number | null;
3693
4548
  allowNestedAgentDepthIncrease?: boolean;
@@ -3716,11 +4571,38 @@ export declare function createSessionWithIdempotencyKeyResult(db: Database, inpu
3716
4571
  * admission transaction and then surfaced as SessionSpawnDeniedDbError;
3717
4572
  * callers that need a structured result use createSessionWithIdempotencyKeyResult.
3718
4573
  */
3719
- export declare function createSessionWithIdempotencyKey(db: Database, input: SessionCreateInput & {
3720
- createIdempotencyKey: string;
3721
- }): Promise<SessionCreateSuccessResult>;
3722
- export declare function getSessionByCreateIdempotencyKey(db: Database, workspaceId: string, createIdempotencyKey: string): Promise<Session | null>;
3723
- export declare function getSession(db: Database, workspaceId: string, sessionId: string): Promise<Session | null>;
4574
+ export declare function createSessionWithIdempotencyKey(db: Database, input: SessionCreateInput & {
4575
+ createIdempotencyKey: string;
4576
+ }): Promise<SessionCreateSuccessResult>;
4577
+ export declare function getSessionByCreateIdempotencyKey(db: Database, workspaceId: string, createIdempotencyKey: string): Promise<Session | null>;
4578
+ export declare function getSession(db: Database, workspaceId: string, sessionId: string): Promise<Session | null>;
4579
+ export type DeleteSessionTreeIfQuiescentResult = {
4580
+ status: "deleted";
4581
+ deletedSessionCount: number;
4582
+ } | {
4583
+ status: "not_found" | "not_root" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes" | "externally_referenced";
4584
+ };
4585
+ /**
4586
+ * Permanently delete one complete root session tree after proving that no
4587
+ * runtime or provider-side owner can still act on it.
4588
+ *
4589
+ * The workspace-control and tree row locks fence new sessions and concurrent
4590
+ * lifecycle changes. Session-owned evidence follows the migration-owned
4591
+ * cascade; immutable workspace-level provenance and independent forks
4592
+ * deliberately retain RESTRICT and surface `externally_referenced` instead of
4593
+ * being orphaned.
4594
+ */
4595
+ export declare function deleteSessionTreeIfQuiescent(db: Database, input: {
4596
+ workspaceId: string;
4597
+ subjectId: string;
4598
+ sessionId: string;
4599
+ /**
4600
+ * Bound the workspace control prefix wait (request-scoped API callers pass
4601
+ * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers.
4602
+ * Exceeding it throws `WorkspaceControlBusyError` before any row is read.
4603
+ */
4604
+ controlLockTimeoutMs?: number;
4605
+ }): Promise<DeleteSessionTreeIfQuiescentResult>;
3724
4606
  export type SessionAuthorityProjection = {
3725
4607
  sessionId: string;
3726
4608
  rootSessionId: string;
@@ -3765,26 +4647,75 @@ export type ListSessionsOptions = {
3765
4647
  limit?: number;
3766
4648
  parentSessionId?: string | null;
3767
4649
  };
3768
- export type SessionListCursor = {
4650
+ export type SessionListSnapshotCursor = {
4651
+ kind: "snapshot";
3769
4652
  snapshotId: string;
3770
4653
  offset: number;
3771
4654
  parentSessionFilter: string;
3772
4655
  search: string | null;
4656
+ archiveMode: "active" | "archived";
4657
+ };
4658
+ export type SessionListKeysetCursor = {
4659
+ kind: "keyset";
4660
+ /** Decimal committed workspace activity revision frozen on page one. */
4661
+ snapshotRevision: string;
4662
+ /** Exact PostgreSQL timestamp text, including microseconds. */
4663
+ sortAt: string;
4664
+ id: string;
4665
+ parentSessionFilter: string;
4666
+ search: string | null;
4667
+ archiveMode: "active" | "archived";
3773
4668
  };
4669
+ export type SessionListCursor = SessionListSnapshotCursor | SessionListKeysetCursor;
3774
4670
  export type ListSessionsForSubjectOptions = ListSessionsOptions & {
3775
4671
  subjectId: string;
3776
4672
  cursor?: SessionListCursor | undefined;
3777
4673
  search?: string | undefined;
3778
4674
  /** Return only the complete personal pin projection; never scan/snapshot ordinary rows. */
3779
4675
  pinsOnly?: boolean | undefined;
3780
- /** Materialize a continuation snapshot. Disable for legacy one-page array reads. */
4676
+ /** List personally archived chats instead of active chats. */
4677
+ archivedOnly?: boolean | undefined;
4678
+ /** Return a continuation cursor. Disable for legacy one-page array reads. */
3781
4679
  materializeSnapshot?: boolean | undefined;
3782
4680
  authorizationScope?: SessionAuthorizationListScope | undefined;
4681
+ /** See {@link PersonalWorkspaceOwnerException}. Absent means "no exception". */
4682
+ personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined;
3783
4683
  };
4684
+ /**
4685
+ * Whether the caller may use the owner-only managed personal-workspace
4686
+ * exception on this request.
4687
+ *
4688
+ * A managed human's personal workspace has NO `workspace_memberships` row
4689
+ * (migration 0219 raises on one), so a bare membership fence denies the one
4690
+ * human who always belongs. The `organization_memberships.personal_workspace_id`
4691
+ * pointer is their whole grant, and
4692
+ * {@link subjectHasLiveWorkspaceAuthorityInScope} is the single resolver for it.
4693
+ *
4694
+ * **This flag is the authorization.** The resolver it gates is not: it answers
4695
+ * "does subject X hold authority here" and establishes nothing about who the
4696
+ * caller is. The exception is for "the canonical managed-cookie (Better Auth)
4697
+ * session" only — "Bearer/delegated principals, API keys, and account or
4698
+ * organization administrators receive no personal-workspace access through that
4699
+ * exception" — and a host-signed delegated bearer chooses its own `subjectId`,
4700
+ * `principalKind`, `metadata.delegated`, and `serviceInitiator` claims, so no
4701
+ * inspection of the grant can carry that distinction. Set this ONLY from
4702
+ * `AccessGrantAuthorization.canonicalManagedHumanSession` (`@opengeni/core`),
4703
+ * which reflects HOW the request authenticated. Omitted/false keeps the
4704
+ * historical bare-membership fence exactly.
4705
+ */
4706
+ export type PersonalWorkspaceOwnerException = boolean;
3784
4707
  export declare class SessionPinVersionConflictError extends Error {
3785
4708
  readonly current: Pick<Session, "pinned" | "pinnedAt" | "pinVersion">;
3786
4709
  constructor(current: Pick<Session, "pinned" | "pinnedAt" | "pinVersion">);
3787
4710
  }
4711
+ export declare class SessionAttentionVersionConflictError extends Error {
4712
+ readonly current: Pick<Session, "unread" | "activelyWorking" | "attentionVersion">;
4713
+ constructor(current: Pick<Session, "unread" | "activelyWorking" | "attentionVersion">);
4714
+ }
4715
+ export declare class SessionArchiveVersionConflictError extends Error {
4716
+ readonly current: Pick<Session, "archived" | "archivedAt" | "archiveVersion">;
4717
+ constructor(current: Pick<Session, "archived" | "archivedAt" | "archiveVersion">);
4718
+ }
3788
4719
  export declare class SessionListCursorError extends Error {
3789
4720
  constructor(message?: string);
3790
4721
  }
@@ -3794,9 +4725,6 @@ export declare class SessionListCursorExpiredError extends Error {
3794
4725
  export declare class SessionListAccessError extends Error {
3795
4726
  constructor(message?: string);
3796
4727
  }
3797
- export declare class SessionListSnapshotLimitError extends Error {
3798
- constructor(message?: string);
3799
- }
3800
4728
  export declare class SessionPinAccessError extends Error {
3801
4729
  constructor(message?: string);
3802
4730
  }
@@ -3818,7 +4746,15 @@ export declare function projectSessionForRelatedAccess(session: Session, access:
3818
4746
  * fixed node/depth budget. `truncated=true` makes every count an explicit lower
3819
4747
  * bound when a deep, wide, overlapping, or cyclic graph reaches that budget.
3820
4748
  */
3821
- export declare function sessionTreeStatsForSessions(db: Database, workspaceId: string, rootIds: string[]): Promise<Map<string, SessionTreeStats>>;
4749
+ export declare function sessionTreeStatsForSessions(db: Database, workspaceId: string, rootIds: string[], subjectId?: string): Promise<Map<string, SessionTreeStats>>;
4750
+ /**
4751
+ * When each given `requires_action` session's own open turn entered that
4752
+ * state: the oldest still-open `requires_action` turn per session. Only the
4753
+ * ids whose current status is `requires_action` should be passed; the lookup
4754
+ * walks `session_turns_workspace_queue_idx` per session and returns no row
4755
+ * for sessions with no such turn.
4756
+ */
4757
+ export declare function sessionRequiresActionSinceForSessions(db: Database, workspaceId: string, sessionIds: readonly string[]): Promise<Map<string, string>>;
3822
4758
  /**
3823
4759
  * Convert the embedding host's complete list scope into a workspace-bound SQL
3824
4760
  * predicate. Root scopes include every descendant through the durable parent
@@ -3826,9 +4762,16 @@ export declare function sessionTreeStatsForSessions(db: Database, workspaceId: s
3826
4762
  * `UNION ALL`) makes legacy cycles terminate without a caller-sized path array.
3827
4763
  */
3828
4764
  export declare function sessionAuthorizationScopeFilter(scope: SessionAuthorizationListScope): SQL;
3829
- export declare const SESSION_LIST_SNAPSHOT_MAX_IDS = 5000;
3830
- export declare const SESSION_LIST_SNAPSHOT_MAX_ACTIVE_PER_SUBJECT = 32;
3831
- /** Opaque, URL-safe cursor encoding for a server-owned activity snapshot. */
4765
+ /**
4766
+ * The reserved slot a session-visibility transition leaves behind when it strips
4767
+ * a now-`user_private` session identity out of another subject's cached page
4768
+ * (migration 0301). Replacing rather than removing the slot keeps snapshot
4769
+ * cardinality and every in-flight cursor offset byte-stable; `gen_random_uuid()`
4770
+ * never emits the nil UUID, so the slot resolves to no session and the hydration
4771
+ * below drops it exactly as it already drops a row RLS hid between pages.
4772
+ */
4773
+ export declare const SESSION_LIST_SNAPSHOT_REDACTED_SESSION_ID = "00000000-0000-0000-0000-000000000000";
4774
+ /** Opaque, URL-safe cursor encoding for bounded session-list pagination. */
3832
4775
  export declare function encodeSessionListCursor(cursor: SessionListCursor): string;
3833
4776
  /** Decode and validate a cursor before it reaches any SQL predicate. */
3834
4777
  export declare function decodeSessionListCursor(value: string): SessionListCursor | null;
@@ -3837,10 +4780,11 @@ export declare function reapExpiredSessionListSnapshots(db: Database, limit?: nu
3837
4780
  /**
3838
4781
  * Server-authoritative member-specific page. Pinned rows are returned separately
3839
4782
  * and omitted from ordinary pages, so list pagination cannot duplicate a
3840
- * session. The first page materializes the complete ordinary activity order in
3841
- * a short-lived, subject-scoped snapshot; continuation cursors carry only that
3842
- * snapshot id and offset, while the page joins live session rows for current
3843
- * lifecycle/title data.
4783
+ * session. New pages use a bounded activity-revision keyset: page one freezes
4784
+ * the committed workspace revision and every continuation reads only `limit +
4785
+ * 1` candidate ids. Legacy short-lived snapshot cursors remain readable during
4786
+ * rolling upgrades, while hydration always joins live rows for current
4787
+ * lifecycle/title and authorization data.
3844
4788
  */
3845
4789
  export declare function listSessionsForSubject(db: Database, workspaceId: string, options: ListSessionsForSubjectOptions): Promise<SessionListResponse>;
3846
4790
  /** Read a session with the caller subject's personal pin projection. */
@@ -3857,6 +4801,34 @@ export declare function setSessionPin(db: Database, input: {
3857
4801
  sessionId: string;
3858
4802
  pinned: boolean;
3859
4803
  expectedVersion?: number | undefined;
4804
+ /** See {@link PersonalWorkspaceOwnerException}. Absent means "no exception". */
4805
+ personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined;
4806
+ }): Promise<Session | null>;
4807
+ /**
4808
+ * Idempotently update one member's explicit follow-up state. Route reads remain
4809
+ * side-effect free: a foreground client acknowledges its exact rendered event
4810
+ * frontier through this mutation, and later durable events remain unread.
4811
+ */
4812
+ export declare function setSessionAttention(db: Database, input: {
4813
+ workspaceId: string;
4814
+ subjectId: string;
4815
+ sessionId: string;
4816
+ unread?: boolean | undefined;
4817
+ acknowledgedThroughSequence?: number | undefined;
4818
+ activelyWorking?: boolean | undefined;
4819
+ expectedVersion?: number | undefined;
4820
+ }): Promise<Session | null>;
4821
+ /**
4822
+ * Archive or restore one root chat for a single member. Archiving also removes
4823
+ * personal pin/follow-up labels so hidden work cannot remain in active rail
4824
+ * sections. Descendants inherit visibility from the archived root at list time.
4825
+ */
4826
+ export declare function setSessionArchive(db: Database, input: {
4827
+ workspaceId: string;
4828
+ subjectId: string;
4829
+ sessionId: string;
4830
+ archived: boolean;
4831
+ expectedVersion?: number | undefined;
3860
4832
  }): Promise<Session | null>;
3861
4833
  export declare function listSessions(db: Database, workspaceId: string, limit?: number): Promise<Session[]>;
3862
4834
  export declare function listSessions(db: Database, workspaceId: string, options?: ListSessionsOptions): Promise<Session[]>;
@@ -3990,6 +4962,15 @@ export type ListSessionEventsOptions = {
3990
4962
  includeClasses?: readonly SessionEventSemanticClass[];
3991
4963
  excludeClasses?: readonly SessionEventSemanticClass[];
3992
4964
  defaultExcludeTypes?: readonly SessionEventType[];
4965
+ /**
4966
+ * Agent-monitoring conversation boundary: omit a human/API `user.message`
4967
+ * whose accepted turn was never claimed (`session_turns.started_at IS NULL`),
4968
+ * whether it is still queued or reached a terminal state before any claim.
4969
+ * The row appears at its own sequence once the turn is claimed. Forensic,
4970
+ * SSE, and REST readers leave this unset so the retained event log stays
4971
+ * exact.
4972
+ */
4973
+ excludeUnclaimedHumanPrompts?: boolean;
3993
4974
  payloadMode?: SessionEventPayloadMode;
3994
4975
  /**
3995
4976
  * Internal exclusive-latest selector. Eligible legacy rows with a null
@@ -4032,6 +5013,8 @@ export declare function listSessionEvents(db: Database, workspaceId: string, ses
4032
5013
  export declare function listSessionEvents(db: Database, workspaceId: string, sessionId: string, after: number, limit?: number): Promise<SessionEvent[]>;
4033
5014
  export declare function listSessionEvents(db: Database, workspaceId: string, sessionId: string, options: ListSessionEventsOptions): Promise<SessionEvent[]>;
4034
5015
  export declare function getSessionEvent(db: Database, workspaceId: string, eventId: string): Promise<SessionEvent | null>;
5016
+ /** Read one durable event under the exact human subject visibility projection. */
5017
+ export declare function getSessionEventForSubject(db: Database, workspaceId: string, subjectId: string, eventId: string): Promise<SessionEvent | null>;
4035
5018
  export declare function listWorkspaceControlEvents(db: Database, workspaceId: string, after?: number, limit?: number): Promise<WorkspaceControlEvent[]>;
4036
5019
  export declare function getWorkspaceControlEvent(db: Database, workspaceId: string, eventId: string): Promise<WorkspaceControlEvent | null>;
4037
5020
  /**
@@ -4108,6 +5091,8 @@ export declare function acceptSessionHumanInputResponse(db: Database, input: {
4108
5091
  requestId: string;
4109
5092
  response: unknown;
4110
5093
  respondedBy: string;
5094
+ /** Bounded responder kind for the parent's resolution notice; derived from `respondedBy` when omitted. */
5095
+ respondedByKind?: ChildRequiresActionRespondedByKind;
4111
5096
  clientEventId?: string | null;
4112
5097
  expireOnly?: boolean;
4113
5098
  }): Promise<AcceptSessionHumanInputResponseResult>;
@@ -4123,6 +5108,43 @@ export declare function getHumanInputResumeForEvent(db: Database, workspaceId: s
4123
5108
  response: HumanInputResponse;
4124
5109
  } | null>;
4125
5110
  export type TurnAttemptFenceRejectReason = "workspace_paused" | "session_paused" | "pending_control" | "active_turn_changed" | "generation_changed" | "attempt_changed" | "turn_terminal" | "not_found";
5111
+ export declare class SessionBackgroundCommandAdoptionFencedError extends Error {
5112
+ readonly reason: TurnAttemptFenceRejectReason;
5113
+ readonly name = "SessionBackgroundCommandAdoptionFencedError";
5114
+ constructor(reason: TurnAttemptFenceRejectReason);
5115
+ }
5116
+ /** Transfer one exact Connected Machine operation from a live turn attempt to
5117
+ * its session. The canonical write fence gives adoption a total order with
5118
+ * Steer, session/workspace Pause, terminal Cancel, and quiescent tree deletion:
5119
+ * an earlier adoption is visible to later control, while earlier control makes
5120
+ * this stale attempt fail before a session-owned row can appear. */
5121
+ export declare function adoptConnectedMachineSessionBackgroundCommand(db: Database, input: {
5122
+ accountId: string;
5123
+ workspaceId: string;
5124
+ sessionId: string;
5125
+ turnId: string;
5126
+ executionGeneration: number;
5127
+ attemptId: string;
5128
+ commandId: string;
5129
+ controlWorkspaceId: string;
5130
+ enrollmentId: string;
5131
+ connectionInstanceId: string;
5132
+ opId: string;
5133
+ command: string;
5134
+ }): Promise<{
5135
+ id: string;
5136
+ workspaceId: string;
5137
+ sessionId: string;
5138
+ provider: "connected_machine" | "managed";
5139
+ state: "exited" | "lost" | "running" | "stopping";
5140
+ commandPreview: string;
5141
+ cancelRequestedAt: string | null;
5142
+ exitCode: number | null;
5143
+ settlementReason: string | null;
5144
+ startedAt: string;
5145
+ settledAt: string | null;
5146
+ updatedAt: string;
5147
+ }>;
4126
5148
  export type InstallOrReadTurnExecutionPolicyForAttemptResult = {
4127
5149
  accepted: true;
4128
5150
  installed: boolean;
@@ -4203,6 +5225,32 @@ export declare function recordPendingSessionToolCallResult(db: Database, input:
4203
5225
  accepted: boolean;
4204
5226
  recorded: boolean;
4205
5227
  }>;
5228
+ export type OpenSuffixInterruptionKind = "human_input" | "approval" | "interaction_intervention";
5229
+ export type OpenSuffixPendingToolCall = {
5230
+ callId: string;
5231
+ callType: string;
5232
+ callItem: Record<string, unknown>;
5233
+ interruptionKind: OpenSuffixInterruptionKind;
5234
+ tiedReasoningItems: Array<Record<string, unknown>>;
5235
+ resultItem: Record<string, unknown> | null;
5236
+ modelToolOutputTruncationTokens: number | null;
5237
+ };
5238
+ /**
5239
+ * Bind unpaired interruption calls and their tied reasoning onto existing
5240
+ * pending receipts. Fail closed when any interruption call is missing.
5241
+ */
5242
+ export declare function attachOpenSuffixToPendingToolCalls(db: Database, input: Omit<PendingSessionToolCallInput, "callId" | "callType" | "callItem"> & {
5243
+ members: Array<{
5244
+ callId: string;
5245
+ interruptionKind: OpenSuffixInterruptionKind;
5246
+ reasoningItems: Array<Record<string, unknown>>;
5247
+ }>;
5248
+ }): Promise<{
5249
+ accepted: boolean;
5250
+ attached: number;
5251
+ }>;
5252
+ /** Turn-scoped interruption suffix rows, including already-settled members. */
5253
+ export declare function listTurnOpenSuffixToolCalls(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise<OpenSuffixPendingToolCall[]>;
4206
5254
  /**
4207
5255
  * Remove completed receipts only after the full SDK call/result batch is
4208
5256
  * durable. Until then every raw result remains available to an attempt-ending
@@ -4760,6 +5808,12 @@ export interface AcquireLeaseInput {
4760
5808
  kind: LeaseHolderKind;
4761
5809
  holderId: string;
4762
5810
  subjectId?: string | null;
5811
+ /** Viewer holders only (0281): the authenticated viewer subject recorded on
5812
+ * the holder row - identity only, never a secret value. */
5813
+ viewerSubjectId?: string;
5814
+ /** Viewer holders only (0281): the session authority epoch observed at
5815
+ * attach, mirrored into the scoped stream token's claims. */
5816
+ viewerAuthorityEpoch?: number;
4763
5817
  backend: string;
4764
5818
  os?: string;
4765
5819
  image?: string | null;
@@ -5374,6 +6428,29 @@ export declare function releaseLeaseHolder(db: Database, input: {
5374
6428
  liveness: SandboxLeaseLiveness;
5375
6429
  refcount: number;
5376
6430
  } | null>;
6431
+ export type LeaseHolderHeartbeatFence = "unsupported_kind" | "lease_missing" | "holder_gone" | "epoch" | "liveness" | "rotation_requested";
6432
+ export type LeaseHolderHeartbeatStatus = {
6433
+ holderAlive: false;
6434
+ leaseExtended: false;
6435
+ fence: "unsupported_kind" | "lease_missing" | "holder_gone";
6436
+ } | {
6437
+ holderAlive: true;
6438
+ leaseExtended: true;
6439
+ fence: null;
6440
+ } | {
6441
+ holderAlive: true;
6442
+ leaseExtended: false;
6443
+ fence: "epoch" | "liveness" | "rotation_requested";
6444
+ };
6445
+ export declare function heartbeatLeaseHolderStatus(db: Database, input: {
6446
+ accountId: string;
6447
+ workspaceId: string;
6448
+ sandboxGroupId: string;
6449
+ kind: LeaseHolderKind;
6450
+ holderId: string;
6451
+ leaseTtlMs: number;
6452
+ expectedEpoch: number;
6453
+ }): Promise<LeaseHolderHeartbeatStatus>;
5377
6454
  export declare function heartbeatLeaseHolder(db: Database, input: {
5378
6455
  accountId: string;
5379
6456
  workspaceId: string;
@@ -5383,6 +6460,37 @@ export declare function heartbeatLeaseHolder(db: Database, input: {
5383
6460
  leaseTtlMs: number;
5384
6461
  expectedEpoch: number;
5385
6462
  }): Promise<boolean>;
6463
+ export type ReinstateTurnLeaseHolderResult = {
6464
+ status: "present" | "reinstated";
6465
+ lease: LeaseSnapshot;
6466
+ } | {
6467
+ status: "lease_missing" | "lease_fenced" | "capture_in_progress" | "reaper_held" | "attempt_fenced";
6468
+ };
6469
+ /**
6470
+ * Defense in depth for the orderly provider-deadline rotation checkpoint: put the
6471
+ * exact canonical turn holder back onto the lease it is still physically using.
6472
+ * The warm capture claim requires exactly this holder, so a holder lost while
6473
+ * the attempt is still the active writer (a stale release, a reap race) would
6474
+ * otherwise silently disable the rotation checkpoint and let the reaper
6475
+ * terminate the box under the running turn.
6476
+ *
6477
+ * Fenced hard: the lease must still be the established epoch and provider
6478
+ * instance, carry no capture/teardown claim and no active reaper hold, and the
6479
+ * attempt must still be the turn's active `claimed`/`running` writer on a
6480
+ * session of this group. A draining lease that passes those fences re-arms to
6481
+ * warm exactly like a late arrival in `acquireLease`; a cold or superseded lease
6482
+ * is never touched. Idempotent: an existing holder is reported `present`.
6483
+ */
6484
+ export declare function reinstateTurnLeaseHolder(db: Database, input: {
6485
+ accountId: string;
6486
+ workspaceId: string;
6487
+ sandboxGroupId: string;
6488
+ sessionId: string;
6489
+ attemptId: string;
6490
+ expectedEpoch: number;
6491
+ expectedInstanceId: string;
6492
+ leaseTtlMs: number;
6493
+ }): Promise<ReinstateTurnLeaseHolderResult>;
5386
6494
  /**
5387
6495
  * HOLDER-LIVENESS touch: refresh ONLY this holder's last_heartbeat_at. The
5388
6496
  * warmup phase of a turn (acquire -> waitForWarm -> establish/cold-restore ->
@@ -5477,9 +6585,9 @@ export declare function confirmDrainCold(db: Database, input: {
5477
6585
  wentCold: boolean;
5478
6586
  }>;
5479
6587
  export declare class SandboxWorkspaceMutationFencedError extends Error {
5480
- readonly code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted";
6588
+ readonly code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" | "authority_unattributed" | "authority_revoked";
5481
6589
  readonly name: string;
5482
- constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted", message: string);
6590
+ constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" | "authority_unattributed" | "authority_revoked", message: string);
5483
6591
  }
5484
6592
  export type SandboxWorkspaceMutationAdmission = {
5485
6593
  id: string;
@@ -5573,7 +6681,7 @@ export declare function retainedProcessReconciliationProof(process: SandboxRetai
5573
6681
  export declare class SandboxRetainedProcessPromotionFencedError extends SandboxWorkspaceMutationFencedError {
5574
6682
  readonly process: SandboxRetainedProcess;
5575
6683
  readonly name = "SandboxRetainedProcessPromotionFencedError";
5576
- constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "admission_fenced", message: string, process: SandboxRetainedProcess);
6684
+ constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "admission_fenced" | "authority_unattributed" | "authority_revoked", message: string, process: SandboxRetainedProcess);
5577
6685
  }
5578
6686
  /**
5579
6687
  * Advance the live workspace's mutation generation before an acknowledged
@@ -5599,6 +6707,11 @@ export declare function advanceWorkspaceGeneration(db: Database, input: {
5599
6707
  captureWaitMs?: number;
5600
6708
  /** Cancel the bounded transition wait without creating an admission. */
5601
6709
  waitSignal?: AbortSignal;
6710
+ /** Observe only time actually spent blocked behind an archive capture. */
6711
+ onCaptureWait?: (observation: {
6712
+ durationMs: number;
6713
+ outcome: "completed" | "failed";
6714
+ }) => void;
5602
6715
  /** Active-routed mutations bind to the exact session pointer. Omitted means
5603
6716
  * an intentional home-provider write outside the routing surface. */
5604
6717
  routeKind?: "home" | "active";
@@ -5607,13 +6720,17 @@ export declare function advanceWorkspaceGeneration(db: Database, input: {
5607
6720
  }): Promise<SandboxWorkspaceMutationAdmission>;
5608
6721
  /** Admit an API/direct mutation under an exact request holder and active route.
5609
6722
  * Direct actors intentionally have no turn identity and can never inherit the
5610
- * attempt-quiescence archive fallback. */
6723
+ * attempt-quiescence archive fallback. `initiatorSubjectId` is the exact
6724
+ * authenticated principal behind the request and is required: it is this
6725
+ * writer's only causal identity, and it is re-proved against the live grant
6726
+ * inside the admission transaction. */
5611
6727
  export declare function advanceWorkspaceGenerationForDirectRequest(db: Database, input: {
5612
6728
  accountId: string;
5613
6729
  workspaceId: string;
5614
6730
  sessionId: string;
5615
6731
  requestId: string;
5616
6732
  holderId: string;
6733
+ initiatorSubjectId: string;
5617
6734
  sandboxGroupId: string;
5618
6735
  expectedEpoch: number;
5619
6736
  expectedInstanceId: string;
@@ -5666,6 +6783,7 @@ export declare function verifyDirectWorkspaceMutationSettlement(db: Database, in
5666
6783
  sessionId: string;
5667
6784
  requestId: string;
5668
6785
  holderId: string;
6786
+ initiatorSubjectId: string;
5669
6787
  sandboxGroupId: string;
5670
6788
  expectedEpoch: number;
5671
6789
  expectedInstanceId: string;
@@ -5700,6 +6818,10 @@ export declare function retainWorkspaceMutationProcess(db: Database, input: {
5700
6818
  key: string;
5701
6819
  binding: ModalCheckpointProviderBinding;
5702
6820
  } | null;
6821
+ backgroundCommand?: {
6822
+ commandId: string;
6823
+ command: string;
6824
+ };
5703
6825
  owner: {
5704
6826
  kind: "turn";
5705
6827
  turnId: string;
@@ -5716,6 +6838,7 @@ export declare function retainWorkspaceMutationProcess(db: Database, input: {
5716
6838
  kind: "direct";
5717
6839
  requestId: string;
5718
6840
  holderId: string;
6841
+ initiatorSubjectId: string;
5719
6842
  sandboxGroupId: string;
5720
6843
  expectedEpoch: number;
5721
6844
  expectedInstanceId: string;
@@ -5731,7 +6854,8 @@ export declare function getRetainedProcess(db: Database, input: {
5731
6854
  processId: string;
5732
6855
  }): Promise<SandboxRetainedProcess | null>;
5733
6856
  /** Claim a bounded, oldest-due batch of active retained processes whose exact
5734
- * owner attempt is closed (or whose direct request already returned). Claim
6857
+ * owner attempt is closed, whose direct request returned, or whose lifecycle
6858
+ * was explicitly transferred to a session background command. Claim
5735
6859
  * expiry only recovers coordination after worker death; it is never provider
5736
6860
  * exit proof. Rows that settle between the global claim and scoped read are
5737
6861
  * deliberately omitted. */
@@ -6087,10 +7211,13 @@ export declare function persistDrainSnapshot(db: Database, input: {
6087
7211
  workspaceArchiveMeta?: never;
6088
7212
  checkpointArtifactId?: never;
6089
7213
  } | {
6090
- /** Base64 provider receipt or tar archive from the verified runtime capture. */
6091
- workspaceArchive: string;
7214
+ /** Base64 provider receipt or tar archive from the verified runtime capture.
7215
+ * Omit when `workspaceArchiveRef` locates object-storage bytes. */
7216
+ workspaceArchive?: string;
6092
7217
  /** Exact descriptor is mandatory for every new publication. */
6093
7218
  workspaceArchiveMeta: SandboxArchiveRevision;
7219
+ /** Object-storage locator for tar bytes. When set, inline bytes are omitted. */
7220
+ workspaceArchiveRef?: WorkspaceArchiveObjectRef | null;
6094
7221
  /** Required for Modal-native descriptors; absent for actual tar archives. */
6095
7222
  checkpointArtifactId?: string | null;
6096
7223
  })): Promise<{
@@ -6122,6 +7249,7 @@ export declare function rotateWorkspaceArchives(input: {
6122
7249
  }): {
6123
7250
  previousArchive: string | null;
6124
7251
  previousArchiveMeta: SandboxArchiveRevision | null;
7252
+ previousArchiveRef: WorkspaceArchiveObjectRef | null;
6125
7253
  };
6126
7254
  /**
6127
7255
  * MID-SESSION /workspace snapshot fold (sandbox-file-persistence). The WARM
@@ -6145,10 +7273,13 @@ export declare function persistWarmSnapshot(db: Database, input: {
6145
7273
  expectedInstanceId: string;
6146
7274
  expectedWorkspaceGeneration: number;
6147
7275
  captureId: string;
6148
- /** base64 of the provider snapshot-ref / tar archive from persistWorkspace(). */
6149
- workspaceArchive: string;
7276
+ /** base64 of the provider snapshot-ref / tar archive from persistWorkspace().
7277
+ * Omit when `workspaceArchiveRef` locates object-storage bytes. */
7278
+ workspaceArchive?: string;
6150
7279
  /** Exact verified archive/tree descriptor produced by the runtime capture. */
6151
7280
  workspaceArchiveMeta: SandboxArchiveRevision;
7281
+ /** Object-storage locator for tar bytes. When set, inline bytes are omitted. */
7282
+ workspaceArchiveRef?: WorkspaceArchiveObjectRef | null;
6152
7283
  checkpointArtifactId?: string | null;
6153
7284
  /** Snapshots newer than this many ms are kept (throttle); 0 = always write. */
6154
7285
  minIntervalMs: number;
@@ -6334,10 +7465,29 @@ export type SandboxKind = (typeof schema.sandboxKindValues)[number];
6334
7465
  export type EnrollmentExposure = (typeof schema.enrollmentExposureValues)[number];
6335
7466
  export type EnrollmentStatus = (typeof schema.enrollmentStatusValues)[number];
6336
7467
  export type EnrollmentOs = (typeof schema.enrollmentOsValues)[number];
7468
+ export type AgentUpdateStatus = (typeof schema.agentUpdateStatusValues)[number];
7469
+ export type EnrollmentAgentUpdateRecord = {
7470
+ operationId: string;
7471
+ status: AgentUpdateStatus;
7472
+ targetVersion: string;
7473
+ expectedBinarySha256: string | null;
7474
+ errorCode: string | null;
7475
+ retryable: boolean;
7476
+ rolledBack: boolean;
7477
+ connectionInstanceId: string;
7478
+ connectionGeneration: number;
7479
+ requestedAt: string;
7480
+ updatedAt: string;
7481
+ completedAt: string | null;
7482
+ };
6337
7483
  export type EnrollmentRecord = {
6338
7484
  id: string;
6339
7485
  accountId: string;
6340
7486
  workspaceId: string;
7487
+ scope: "organization" | "workspace" | "user";
7488
+ generation: number;
7489
+ sandboxId?: string | null;
7490
+ sandboxName?: string | null;
6341
7491
  pubkey: string;
6342
7492
  exposure: EnrollmentExposure;
6343
7493
  hasDisplay: boolean;
@@ -6346,10 +7496,28 @@ export type EnrollmentRecord = {
6346
7496
  * not granted); null when capture is permitted or the machine is headless. */
6347
7497
  desktopUnavailableReason: string | null;
6348
7498
  allowScreenControl: boolean;
7499
+ operationPolicy: {
7500
+ memoryMaxBytes: number | null;
7501
+ memoryHighBytes: number | null;
7502
+ cpuMaxMillicores: number | null;
7503
+ revision: number;
7504
+ updatedAt: string | null;
7505
+ };
6349
7506
  status: EnrollmentStatus;
6350
7507
  credentialGeneration: number;
7508
+ /** Exact live runner instance receiving this machine's control traffic. */
7509
+ connectionInstanceId: string | null;
7510
+ /** Monotonic authority generation, advanced only when a different runner claims. */
7511
+ connectionGeneration: number;
7512
+ /** Server-clock expiry for the live runner claim. */
7513
+ connectionLeaseExpiresAt: string | null;
7514
+ /** Valid competing processes denied while another runner held authority. */
7515
+ connectionDuplicateDeniedCount: number;
7516
+ connectionDuplicateDeniedAt: string | null;
6351
7517
  os: EnrollmentOs;
6352
7518
  arch: string;
7519
+ /** Exact absolute launch root last reported by an authoritative runner Hello. */
7520
+ workspaceRoot: string | null;
6353
7521
  lastSeenAt: string | null;
6354
7522
  /** When the machine announced a clean GoingOffline; the liveness derivation reads
6355
7523
  * an un-cleared marker as offline immediately. NULL ⇒ no goodbye pending. */
@@ -6357,6 +7525,11 @@ export type EnrollmentRecord = {
6357
7525
  /** The typed reason string of the pending clean going-offline (e.g.
6358
7526
  * GOING_OFFLINE_REASON_UPDATE); NULL when there is no un-cleared marker. */
6359
7527
  wentOfflineReason: string | null;
7528
+ agentVersion: string | null;
7529
+ agentBinarySha256: string | null;
7530
+ agentUpdateChannel: "stable" | "beta" | null;
7531
+ agentCapabilities: Record<string, boolean>;
7532
+ agentUpdate: EnrollmentAgentUpdateRecord | null;
6360
7533
  createdAt: string;
6361
7534
  revokedAt: string | null;
6362
7535
  updatedAt: string;
@@ -6368,6 +7541,8 @@ export type SandboxRecord = {
6368
7541
  kind: SandboxKind;
6369
7542
  name: string;
6370
7543
  enrollmentId: string | null;
7544
+ scope?: "organization" | "workspace" | "user";
7545
+ generation?: number;
6371
7546
  createdAt: string;
6372
7547
  updatedAt: string;
6373
7548
  };
@@ -6381,8 +7556,117 @@ export declare function createEnrollment(db: Database, input: {
6381
7556
  os?: EnrollmentOs;
6382
7557
  arch?: string;
6383
7558
  }): Promise<EnrollmentRecord>;
6384
- export declare function getEnrollment(db: Database, workspaceId: string, enrollmentId: string): Promise<EnrollmentRecord | null>;
6385
- export declare function listEnrollments(db: Database, workspaceId: string, options?: {
7559
+ export declare function getEnrollment(db: Database, access: string | {
7560
+ accountId: string;
7561
+ workspaceId: string;
7562
+ subjectId: string;
7563
+ }, enrollmentId: string): Promise<EnrollmentRecord | null>;
7564
+ /** Read an enrollment only while its exact runner claim is live according to
7565
+ * PostgreSQL's clock. Callers receive capability + process identity from one
7566
+ * snapshot and never reinterpret lease time using an API host's wall clock. */
7567
+ export declare function getLiveEnrollmentConnection(db: Database, access: string | {
7568
+ accountId: string;
7569
+ workspaceId: string;
7570
+ subjectId: string;
7571
+ }, enrollmentId: string): Promise<EnrollmentRecord | null>;
7572
+ export declare function assertPersonalMachineForAttempt(db: Database, input: {
7573
+ accountId: string;
7574
+ workspaceId: string;
7575
+ subjectId: string;
7576
+ sessionId: string;
7577
+ turnId: string;
7578
+ attemptId: string;
7579
+ executionGeneration: number;
7580
+ enrollmentId: string;
7581
+ requireActiveSandbox?: boolean;
7582
+ }): Promise<boolean>;
7583
+ /** Resolve one personal Connected Machine's live runner only after the exact
7584
+ * accepted attempt and its immutable snapshot/current grant pass pre-use in the
7585
+ * same transaction and PostgreSQL snapshot. This is the last DB boundary used
7586
+ * immediately before a worker or one-off provider dispatch. */
7587
+ export declare function resolvePersonalMachineConnectionForAttempt(db: Database, input: {
7588
+ accountId: string;
7589
+ workspaceId: string;
7590
+ subjectId: string;
7591
+ sessionId: string;
7592
+ turnId: string;
7593
+ attemptId: string;
7594
+ executionGeneration: number;
7595
+ enrollmentId: string;
7596
+ requireActiveSandbox?: boolean;
7597
+ }): Promise<EnrollmentRecord | null>;
7598
+ export declare function authorizePersonalMachineForAttempt(db: Database, input: {
7599
+ accountId: string;
7600
+ workspaceId: string;
7601
+ subjectId: string;
7602
+ sessionId: string;
7603
+ turnId: string;
7604
+ attemptId: string;
7605
+ executionGeneration: number;
7606
+ enrollmentId: string;
7607
+ requireActiveSandbox?: boolean;
7608
+ }): Promise<boolean>;
7609
+ /** Revision-fenced workspace-operator update of one Connected Machine's optional
7610
+ * command resource policy. NULL remains unrestricted. The active-enrollment check,
7611
+ * CAS, mutation, and audit receipt share one RLS transaction. */
7612
+ export declare function updateEnrollmentOperationPolicy(db: Database, input: {
7613
+ accountId: string;
7614
+ workspaceId: string;
7615
+ enrollmentId: string;
7616
+ subjectId?: string;
7617
+ expectedRevision: number;
7618
+ memoryMaxBytes: number | null;
7619
+ memoryHighBytes: number | null;
7620
+ cpuMaxMillicores?: number | null;
7621
+ }): Promise<EnrollmentRecord | null>;
7622
+ export type EnrollmentConnectionClaim = {
7623
+ claimed: boolean;
7624
+ connectionInstanceId: string | null;
7625
+ connectionGeneration: number;
7626
+ connectionLeaseExpiresAt: string | null;
7627
+ };
7628
+ /**
7629
+ * Claims or renews one enrollment's exact live runner instance under the
7630
+ * enrollment-row lock. A second process holding the same valid bearer is denied
7631
+ * while the current runner heartbeats. Once the lease expires, a successor
7632
+ * advances the generation and receives a different NATS address; the old socket
7633
+ * can no longer receive operations even if its short-lived user JWT has not yet
7634
+ * expired.
7635
+ */
7636
+ export declare function claimEnrollmentConnection(db: Database, input: {
7637
+ workspaceId: string;
7638
+ enrollmentId: string;
7639
+ credentialGeneration: number;
7640
+ connectionInstanceId: string;
7641
+ leaseMs: number;
7642
+ }): Promise<EnrollmentConnectionClaim>;
7643
+ /** Renew only the exact active runner. Stale heartbeats never extend or steal a
7644
+ * successor's lease. */
7645
+ export declare function renewEnrollmentConnection(db: Database, input: {
7646
+ accountId: string;
7647
+ workspaceId: string;
7648
+ enrollmentId: string;
7649
+ connectionInstanceId: string;
7650
+ leaseMs: number;
7651
+ }): Promise<{
7652
+ renewed: boolean;
7653
+ }>;
7654
+ /** Release only the exact active runner. A late goodbye from a fenced process is
7655
+ * ignored and cannot mark its successor offline. */
7656
+ export declare function releaseEnrollmentConnection(db: Database, input: {
7657
+ accountId: string;
7658
+ workspaceId: string;
7659
+ enrollmentId: string;
7660
+ connectionInstanceId: string;
7661
+ reason: string;
7662
+ }): Promise<{
7663
+ released: boolean;
7664
+ }>;
7665
+ export declare function listEnrollments(db: Database, access: string | {
7666
+ accountId: string;
7667
+ workspaceId: string;
7668
+ subjectId: string;
7669
+ }, options?: {
6386
7670
  status?: EnrollmentStatus;
6387
7671
  }): Promise<EnrollmentRecord[]>;
6388
7672
  export type MachineRemovalOutcome = (typeof schema.machineRemovalOperationOutcomeValues)[number];
@@ -6461,6 +7745,8 @@ export declare function clearEnrollmentWentOffline(db: Database, input: {
6461
7745
  accountId: string;
6462
7746
  workspaceId: string;
6463
7747
  enrollmentId: string;
7748
+ /** When present, only the exact still-live runner may clear the marker. */
7749
+ connectionInstanceId?: string;
6464
7750
  }): Promise<{
6465
7751
  cleared: boolean;
6466
7752
  }>;
@@ -6470,6 +7756,8 @@ export declare function setEnrollmentDisplayState(db: Database, input: {
6470
7756
  enrollmentId: string;
6471
7757
  hasDisplay: boolean;
6472
7758
  desktopUnavailableReason: string | null;
7759
+ /** When present, fence the update to the exact still-live runner. */
7760
+ connectionInstanceId?: string;
6473
7761
  }): Promise<{
6474
7762
  updated: boolean;
6475
7763
  }>;
@@ -6478,6 +7766,61 @@ export declare function setEnrollmentOpStreamState(db: Database, input: {
6478
7766
  workspaceId: string;
6479
7767
  enrollmentId: string;
6480
7768
  opStream: boolean;
7769
+ /** When present, fence the update to the exact still-live runner. */
7770
+ connectionInstanceId?: string;
7771
+ }): Promise<{
7772
+ updated: boolean;
7773
+ }>;
7774
+ /** Refresh the exact running agent build/capabilities from an authoritative
7775
+ * process Hello. A pending update becomes succeeded only when the successor
7776
+ * reports BOTH the requested version and the artifact digest selected from the
7777
+ * signed manifest. Merely reaching `restarting` never counts as success. */
7778
+ export declare function setEnrollmentAgentRuntime(db: Database, input: {
7779
+ accountId: string;
7780
+ workspaceId: string;
7781
+ enrollmentId: string;
7782
+ connectionInstanceId: string;
7783
+ agentVersion: string | null;
7784
+ binarySha256: string | null;
7785
+ updateChannel: "stable" | "beta" | null;
7786
+ capabilities: Record<string, boolean>;
7787
+ /** Omitted when an older or malformed Hello did not report a usable root. */
7788
+ workspaceRoot?: string;
7789
+ completedUpdate: {
7790
+ operationId: string;
7791
+ targetVersion: string;
7792
+ binarySha256: string;
7793
+ } | null;
7794
+ }): Promise<{
7795
+ updated: boolean;
7796
+ updateCompleted: boolean;
7797
+ }>;
7798
+ /** Atomically reserve the one process-global update slot on an exact live
7799
+ * runner generation. An in-flight operation is never overwritten. */
7800
+ export declare function beginEnrollmentAgentUpdate(db: Database, input: {
7801
+ accountId: string;
7802
+ workspaceId: string;
7803
+ enrollmentId: string;
7804
+ connectionInstanceId: string;
7805
+ connectionGeneration: number;
7806
+ operationId: string;
7807
+ targetVersion: string;
7808
+ }): Promise<EnrollmentRecord | null>;
7809
+ /** Fold one progress event/dispatch failure into the reserved update. Exact
7810
+ * operation + process authority coordinates fence stale events; monotonic rank
7811
+ * prevents reordered NATS delivery from regressing the UI. */
7812
+ export declare function advanceEnrollmentAgentUpdate(db: Database, input: {
7813
+ accountId: string;
7814
+ workspaceId: string;
7815
+ enrollmentId: string;
7816
+ connectionInstanceId: string;
7817
+ connectionGeneration: number;
7818
+ operationId: string;
7819
+ status: Exclude<AgentUpdateStatus, "requested" | "succeeded">;
7820
+ expectedBinarySha256?: string | null;
7821
+ errorCode?: string | null;
7822
+ retryable?: boolean;
7823
+ rolledBack?: boolean;
6481
7824
  }): Promise<{
6482
7825
  updated: boolean;
6483
7826
  }>;
@@ -6540,6 +7883,8 @@ export declare function finalizeEnrollmentByToken(db: Database, input: {
6540
7883
  export declare function approveDeviceEnrollmentRequest(db: Database, input: {
6541
7884
  accountId: string;
6542
7885
  workspaceId: string;
7886
+ scope?: EnrollmentRecord["scope"];
7887
+ allowOrganization?: boolean;
6543
7888
  requestId: string;
6544
7889
  allowScreenControl: boolean;
6545
7890
  approvedBySubjectId: string;
@@ -6572,7 +7917,11 @@ export declare function createSandbox(db: Database, input: {
6572
7917
  name: string;
6573
7918
  enrollmentId?: string | null;
6574
7919
  }): Promise<SandboxRecord>;
6575
- export declare function getSandbox(db: Database, workspaceId: string, sandboxId: string): Promise<SandboxRecord | null>;
7920
+ export declare function getSandbox(db: Database, access: string | {
7921
+ accountId: string;
7922
+ workspaceId: string;
7923
+ subjectId: string;
7924
+ }, sandboxId: string): Promise<SandboxRecord | null>;
6576
7925
  export declare function listSandboxes(db: Database, workspaceId: string): Promise<SandboxRecord[]>;
6577
7926
  export type ActiveSandboxPointer = {
6578
7927
  activeSandboxId: string | null;
@@ -6593,6 +7942,13 @@ export declare function setActiveSandbox(db: Database, input: {
6593
7942
  sessionId: string;
6594
7943
  targetSandboxId: string | null;
6595
7944
  expectedEpoch: number;
7945
+ subjectId?: string;
7946
+ personalMachineAttempt?: {
7947
+ turnId: string;
7948
+ attemptId: string;
7949
+ executionGeneration: number;
7950
+ initiatingHumanSubjectId: string;
7951
+ };
6596
7952
  workingDir?: string | null;
6597
7953
  }): Promise<{
6598
7954
  swapped: boolean;
@@ -6780,6 +8136,7 @@ export type CreateSessionGoalInput = {
6780
8136
  sessionId: string;
6781
8137
  text: string;
6782
8138
  successCriteria?: string | null;
8139
+ rootConstraints?: string[];
6783
8140
  maxAutoContinuations?: number | null;
6784
8141
  mutationPolicy?: SessionGoalMutationPolicy;
6785
8142
  expectedObjectiveRevision?: number;
@@ -6787,17 +8144,20 @@ export type CreateSessionGoalInput = {
6787
8144
  changeKind?: SessionGoalChangeKind;
6788
8145
  changeRationale?: string;
6789
8146
  sourceProposalId?: string;
8147
+ rollbackOfRevisionId?: string;
6790
8148
  createdBy: SessionGoalCreatedBy;
6791
8149
  };
6792
8150
  export declare function createSessionGoal(db: Database, input: CreateSessionGoalInput): Promise<SessionGoal>;
6793
8151
  export declare function getSessionGoal(db: Database, workspaceId: string, sessionId: string): Promise<SessionGoal | null>;
6794
8152
  export type SessionGoalContinuationProjection = {
6795
8153
  state: "inactive" | "scheduled" | "running" | "blocked" | "invariant_broken";
6796
- reason: "goal_inactive" | "wake_pending" | "continuation_pending" | "human_work_pending" | "goal_turn_running" | "human_turn_running" | "workstream_paused" | "approval_required" | "provider_backpressure" | "session_cancelled" | "system_work_pending" | "missing_obligation";
8154
+ reason: "goal_inactive" | "wake_pending" | "continuation_pending" | "human_work_pending" | "goal_turn_running" | "human_turn_running" | "workstream_paused" | "approval_required" | "provider_backpressure" | "session_cancelled" | "system_work_pending" | "held_for_input" | "backoff_pending" | "missing_obligation";
6797
8155
  wakeRevision: number;
6798
8156
  observedRevision: number;
6799
8157
  nextAttemptAt: string | null;
6800
8158
  lastError: string | null;
8159
+ /** The agent's stated `goal_wait` reason while `held_for_input`; null otherwise. */
8160
+ holdReason: string | null;
6801
8161
  };
6802
8162
  /**
6803
8163
  * Read the goal and its autonomy state from one repeatable Postgres snapshot.
@@ -6823,6 +8183,21 @@ export declare function upsertSessionGoal(db: Database, input: CreateSessionGoal
6823
8183
  goal: SessionGoal;
6824
8184
  replaced: boolean;
6825
8185
  }>;
8186
+ /**
8187
+ * Re-arm one reusable scheduled goal exactly once per admitted run. The receipt,
8188
+ * goal mutation, and timeline fact share the canonical session lock transaction,
8189
+ * so crash recovery cannot reset counters or append goal.set twice.
8190
+ */
8191
+ export declare function upsertScheduledSessionGoalForRun(db: Database, input: {
8192
+ accountId: string;
8193
+ workspaceId: string;
8194
+ sessionId: string;
8195
+ runId: string;
8196
+ text: string;
8197
+ successCriteria?: string | null;
8198
+ maxAutoContinuations?: number | null;
8199
+ mutationPolicy?: SessionGoalMutationPolicy;
8200
+ }): Promise<SessionEvent[]>;
6826
8201
  /**
6827
8202
  * Agent/API goal_set: session sequence ownership, the create-or-replace
6828
8203
  * mutation, and goal.set timeline fact commit together. The session-first lock
@@ -6838,12 +8213,32 @@ export declare function upsertSessionGoalWithEvent(db: Database, input: CreateSe
6838
8213
  events: SessionEvent[];
6839
8214
  }>;
6840
8215
  export declare function listSessionGoalRevisions(db: Database, workspaceId: string, sessionId: string): Promise<SessionGoalRevision[]>;
8216
+ export declare function listSessionGoalRevisionPage(db: Database, workspaceId: string, sessionId: string, options?: {
8217
+ limit: number;
8218
+ before?: string;
8219
+ }): Promise<{
8220
+ revisions: SessionGoalRevision[];
8221
+ hasMore: boolean;
8222
+ nextCursor: string | null;
8223
+ }>;
6841
8224
  export declare function getSessionGoalRevision(db: Database, workspaceId: string, sessionId: string, revisionId: string): Promise<SessionGoalRevision | null>;
8225
+ export declare function rejectSessionGoalRevisionWithEvent(db: Database, input: {
8226
+ accountId: string;
8227
+ workspaceId: string;
8228
+ sessionId: string;
8229
+ revisionId: string;
8230
+ expectedObjectiveRevision: number;
8231
+ rationale: string;
8232
+ }): Promise<{
8233
+ revision: SessionGoalRevision;
8234
+ events: SessionEvent[];
8235
+ replay: boolean;
8236
+ }>;
6842
8237
  /**
6843
8238
  * Low-level semantic goal revision. The established lifecycle version still
6844
8239
  * advances so stale continuation updates are cancelled, while the migration
6845
- * trigger advances the separate objective revision. A semantic rewrite is not
6846
- * execution progress and therefore never resets the no-progress streak.
8240
+ * trigger advances the separate objective revision. A semantic rewrite does
8241
+ * not synthesize or consume another continuation.
6847
8242
  */
6848
8243
  export declare function updateSessionGoal(db: Database, workspaceId: string, sessionId: string, input: {
6849
8244
  text?: string;
@@ -6886,6 +8281,44 @@ export declare function updateSessionGoalWithEvent(db: Database, workspaceId: st
6886
8281
  * revision. The attempt-fenced operation receipt makes a recovered tool call
6887
8282
  * converge on the original event instead of manufacturing progress twice.
6888
8283
  */
8284
+ /**
8285
+ * Column set that retires an agent-declared `goal_wait` hold. Spread into every
8286
+ * goal head mutation (status transition, applied semantic revision, replace) so
8287
+ * newer truth never sits behind an older wait.
8288
+ */
8289
+ export declare const SESSION_GOAL_HOLD_MIN_SECONDS = 30;
8290
+ export declare const SESSION_GOAL_HOLD_MAX_SECONDS: number;
8291
+ /**
8292
+ * Agent `goal_wait`: record that the active goal's next continuation should
8293
+ * wait for child results, a message, a human prompt, or the deadline instead of
8294
+ * materializing immediately after the declaring turn ends.
8295
+ *
8296
+ * The hold is bound to the exact caller turn. The materializer honors it only
8297
+ * while that turn is still the latest finished turn and `now < until`; it
8298
+ * never consumes the wake/observed revision ledger. The receipt, goal
8299
+ * mutation, and `goal.held` timeline fact commit under the canonical goal
8300
+ * event-write prefix (control FOR SHARE -> workspace FOR KEY SHARE -> session
8301
+ * FOR NO KEY UPDATE), never a workspace FOR UPDATE. A replacement attempt
8302
+ * replaying the same target-scoped operation key receives the stored result.
8303
+ */
8304
+ export declare function holdSessionGoalContinuationWithEvent(db: Database, workspaceId: string, sessionId: string, input: {
8305
+ reason: string;
8306
+ untilSeconds: number;
8307
+ command: {
8308
+ accountId: string;
8309
+ actor: Extract<SessionCommandActor, {
8310
+ type: "agent_attempt";
8311
+ }>;
8312
+ operationKey: string;
8313
+ };
8314
+ }): Promise<{
8315
+ goal: SessionGoal;
8316
+ events: SessionEvent[];
8317
+ operationId: string;
8318
+ replay: boolean;
8319
+ holdTurnId: string;
8320
+ untilAt: string;
8321
+ }>;
6889
8322
  export declare function recordSessionGoalProgressWithEvent(db: Database, workspaceId: string, sessionId: string, input: {
6890
8323
  progressNote: string;
6891
8324
  command: {
@@ -6970,7 +8403,7 @@ export type GoalContinuationDecision = {
6970
8403
  decision: "queue";
6971
8404
  } | {
6972
8405
  decision: "paused";
6973
- reason: "no_progress" | "max_auto_continuations" | "limits";
8406
+ reason: "max_auto_continuations" | "limits";
6974
8407
  goal: SessionGoal;
6975
8408
  } | {
6976
8409
  decision: "continue";
@@ -6982,20 +8415,38 @@ export type GoalContinuationDecision = {
6982
8415
  * Core continuation decision, taken in one transaction with the goal row
6983
8416
  * locked. Queued work always wins; any non-terminal turn (queued, running, or
6984
8417
  * requires_action awaiting a human approval) blocks auto-continuation. The
6985
- * no-progress and max-continuation guards mutate counters here only, so a
6986
- * replaying workflow re-reads recorded activity results and never recomputes
6987
- * them.
8418
+ * optional max-continuation guard mutates its counter here only, so a replaying
8419
+ * workflow re-reads recorded activity results and never recomputes it.
6988
8420
  */
6989
8421
  export declare function evaluateGoalContinuation(db: Database, input: {
6990
8422
  workspaceId: string;
6991
8423
  sessionId: string;
6992
8424
  defaultMaxAutoContinuations?: number | null;
6993
- noProgressLimit: number;
6994
8425
  budgetBlocked?: string | null;
6995
8426
  }): Promise<GoalContinuationDecision>;
8427
+ export declare const GOAL_IDLE_BACKOFF_WAKE_REASON = "goal_idle_backoff";
8428
+ /**
8429
+ * Pacing between consecutive no-input goal continuations. `scheduleMs[n - 1]`
8430
+ * (last entry repeats) is the delay before the n-th consecutive continuation,
8431
+ * measured from when the previous continuation turn finished; `maxMs` bounds
8432
+ * every delay. Omitted/null means no backoff (the legacy immediate behavior).
8433
+ */
8434
+ export type GoalIdleBackoffPolicy = {
8435
+ scheduleMs: readonly number[];
8436
+ maxMs: number;
8437
+ };
6996
8438
  export type MaterializeGoalContinuationResult = {
6997
8439
  action: "none" | "queue";
6998
8440
  events: [];
8441
+ } | {
8442
+ action: "held";
8443
+ events: [];
8444
+ holdTurnId: string;
8445
+ holdUntil: Date;
8446
+ } | {
8447
+ action: "deferred";
8448
+ events: [];
8449
+ notBefore: Date;
6999
8450
  } | {
7000
8451
  action: "paused";
7001
8452
  events: SessionEvent[];
@@ -7010,7 +8461,7 @@ export type MaterializeGoalContinuationResult = {
7010
8461
  * Consume one durable goal-wake revision into one continuation obligation.
7011
8462
  *
7012
8463
  * This is deliberately one outer PostgreSQL transaction. The existing locked
7013
- * evaluator runs as a nested savepoint, so its no-progress/counter mutation is
8464
+ * evaluator runs as a nested savepoint, so its counter mutation is
7014
8465
  * rolled back if prompt construction, update/event insertion, metering, or the
7015
8466
  * workflow-wake outbox write fails. Retrying after a lost COMMIT response sees
7016
8467
  * the same stable goal revision and the already-pending update; it never spends
@@ -7022,8 +8473,8 @@ export declare function materializeGoalContinuation(db: Database, input: {
7022
8473
  sessionId: string;
7023
8474
  workflowId: string;
7024
8475
  defaultMaxAutoContinuations?: number | null;
7025
- noProgressLimit: number;
7026
8476
  budgetBlocked?: string | null;
8477
+ idleBackoff?: GoalIdleBackoffPolicy | null;
7027
8478
  policy: {
7028
8479
  model: string;
7029
8480
  reasoningEffort: ReasoningEffort;
@@ -7045,15 +8496,34 @@ export type InitializeSessionStartInput = {
7045
8496
  goal?: {
7046
8497
  text: string;
7047
8498
  successCriteria?: string | null;
8499
+ rootConstraints?: string[];
7048
8500
  maxAutoContinuations?: number | null;
7049
8501
  mutationPolicy?: SessionGoalMutationPolicy;
8502
+ createdBy?: SessionGoalCreatedBy;
7050
8503
  } | null;
7051
8504
  consumeNewSessionDraft?: {
7052
8505
  subjectId: string;
7053
8506
  expectedRevision: number;
8507
+ expectedSnapshot?: NewSessionDraftSnapshot;
8508
+ acceptedSelection?: {
8509
+ channelId: string | null;
8510
+ targetSandboxId: string | null;
8511
+ workingDir: string | null;
8512
+ };
8513
+ } | null;
8514
+ /** Successful create that preserves, rather than consumes, the draft. */
8515
+ rememberNewSessionSelection?: {
8516
+ subjectId: string;
8517
+ acceptedSelection: {
8518
+ channelId: string | null;
8519
+ targetSandboxId: string | null;
8520
+ workingDir: string | null;
8521
+ };
7054
8522
  } | null;
7055
8523
  /** Persist session.created only; realtime will supply the first human turn. */
7056
8524
  deferInitialTurn?: boolean;
8525
+ /** Public status persisted with a deferred session start. Defaults to idle. */
8526
+ deferredStatus?: Extract<SessionStatus, "idle" | "queued">;
7057
8527
  };
7058
8528
  export type InitializeSessionStartResult = {
7059
8529
  events: SessionEvent[];
@@ -7092,6 +8562,13 @@ export type ClaimSessionWorkForAttemptInput = {
7092
8562
  attemptId: string;
7093
8563
  dispatchId: string;
7094
8564
  trigger: SessionWorkTrigger;
8565
+ /** Optional worker-owned mutable-authority fence for pending machine inputs. */
8566
+ validatePendingSystemUpdateAuthority?: (tx: Database, update: SessionSystemUpdate) => Promise<{
8567
+ action: "accept";
8568
+ } | {
8569
+ action: "reject";
8570
+ reason: string;
8571
+ }>;
7095
8572
  };
7096
8573
  export type ClaimSessionWorkForAttemptResult = {
7097
8574
  action: "claimed";
@@ -7237,7 +8714,6 @@ export type SessionWorkPeek = {
7237
8714
  } | {
7238
8715
  kind: "idle";
7239
8716
  };
7240
- /** Read durable session state without reserving a turn-worker slot or mutating it. */
7241
8717
  export declare function peekSessionWork(db: Database, workspaceId: string, sessionId: string): Promise<SessionWorkPeek>;
7242
8718
  export type FailSessionWorkBeforeAttemptClaimInput = {
7243
8719
  accountId: string;
@@ -7315,11 +8791,12 @@ export type ApplySessionTurnSettlementInput = {
7315
8791
  activeTurnId: string | null;
7316
8792
  events: AppendEventInput[];
7317
8793
  /**
7318
- * A mid-turn SDK freeze installed atomically with requires_action. Human
7319
- * input requests are public protocol rows; ordinary approvals remain only in
7320
- * pendingApprovals. No request can become visible without the exact frozen
7321
- * RunState needed to resume it, and no frozen request can miss its status
7322
- * transition/events because all writes share this transaction.
8794
+ * A mid-turn requires_action freeze. Human-input rows and interaction
8795
+ * interventions are public protocol; ordinary approvals remain in
8796
+ * pendingApprovals. Pause attaches the bounded open suffix on
8797
+ * `session_pending_tool_calls` and stores the open-suffix sentinel here.
8798
+ * Resume uses the suffix plus paired history and must not call
8799
+ * `RunState.fromString`.
7323
8800
  */
7324
8801
  runState?: {
7325
8802
  serializedRunState: string;
@@ -7355,6 +8832,7 @@ export type ApplySessionTurnSettlementInput = {
7355
8832
  export type ApplySessionTurnSettlementResult = {
7356
8833
  action: "settled";
7357
8834
  events: SessionEvent[];
8835
+ canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
7358
8836
  recordingMutationApplied: boolean;
7359
8837
  } | {
7360
8838
  action: "stale";
@@ -7369,6 +8847,12 @@ export type ApplySessionTurnSettlementHooks = {
7369
8847
  turnId: string;
7370
8848
  }) => void | Promise<void>) | undefined;
7371
8849
  };
8850
+ export type CanonicalTurnStartupMilestoneReceipt = {
8851
+ milestone: "queue" | "provider_dispatch" | "first_byte";
8852
+ outcome: "completed" | "failed";
8853
+ eventId: string;
8854
+ durationMs: number;
8855
+ };
7372
8856
  /**
7373
8857
  * Atomically append terminal/requires-action truth, update the exact turn, and
7374
8858
  * transition the owning session. A superseded dispatch or closed control gate
@@ -7525,12 +9009,30 @@ export declare function getSessionTurnForAttempt(db: Database, workspaceId: stri
7525
9009
  * the model that actually ran rather than reverting to a stale default.
7526
9010
  */
7527
9011
  export declare function getLatestStartedSessionTurn(db: Database, workspaceId: string, sessionId: string): Promise<SessionTurn | null>;
9012
+ /**
9013
+ * Freeze the effective policy an internal scheduled update would inherit from
9014
+ * an existing session at occurrence admission. The later claim consumes this
9015
+ * exact policy instead of re-reading whichever turn happened to start most
9016
+ * recently in the meantime.
9017
+ */
9018
+ export declare function getScheduledTargetSessionExecution(db: Database, workspaceId: string, sessionId: string, authoritySubjectId?: string | null): Promise<ScheduledTaskRunAcceptedExecutionType["targetSessionExecution"]>;
7528
9019
  export declare function listSessionTurns(db: Database, workspaceId: string, sessionId: string, limit?: number): Promise<SessionTurn[]>;
7529
9020
  export declare function listPendingSessionTurns(db: Database, workspaceId: string, sessionId: string): Promise<SessionTurn[]>;
7530
9021
  export declare function getSessionQueueSnapshot(db: Database, workspaceId: string, sessionId: string): Promise<SessionQueueSnapshot | null>;
7531
- type ChildTerminalResultPayload = Extract<SessionSystemUpdatePayload, {
7532
- type: "child_terminal_result";
9022
+ type ChildLifecycleOutboxPayload = Extract<SessionSystemUpdatePayload, {
9023
+ type: ChildLifecycleSystemUpdateKind;
7533
9024
  }>;
9025
+ /** Derive the bounded responder kind of a human-input/approval resolution. */
9026
+ export declare function childRequiresActionRespondedByKindFor(respondedBy: string, explicit?: ChildRequiresActionRespondedByKind): ChildRequiresActionRespondedByKind;
9027
+ /** The exact kind/payload pair of one child-lifecycle outbox row, correlated for typed re-insert. */
9028
+ export type SessionSystemUpdateOutboxKindPayload = {
9029
+ [Kind in ChildLifecycleSystemUpdateKind]: {
9030
+ kind: Kind;
9031
+ payload: Extract<SessionSystemUpdatePayload, {
9032
+ type: Kind;
9033
+ }>;
9034
+ };
9035
+ }[ChildLifecycleSystemUpdateKind];
7534
9036
  export type SessionSystemUpdateOutboxDelivery = {
7535
9037
  id: string;
7536
9038
  status: "pending" | "delivered";
@@ -7539,15 +9041,17 @@ export type SessionSystemUpdateOutboxDelivery = {
7539
9041
  sourceSessionId: string;
7540
9042
  targetSessionId: string;
7541
9043
  dedupeKey: string;
7542
- kind: "child_terminal_result";
9044
+ kind: ChildLifecycleSystemUpdateKind;
7543
9045
  classification: SystemUpdateClassification;
7544
9046
  sourceId: string;
7545
9047
  summary: string;
7546
- payload: ChildTerminalResultPayload;
9048
+ payload: ChildLifecycleOutboxPayload;
7547
9049
  lineage: Record<string, unknown>;
7548
9050
  personalConnectionDelegations: McpPersonalConnectionDelegation[];
7549
9051
  xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;
7550
9052
  };
9053
+ /** Narrow an outbox row back to its correlated typed kind/payload input variant. */
9054
+ export declare function sessionSystemUpdateOutboxKindPayload(outbox: Pick<SessionSystemUpdateOutboxDelivery, "kind" | "payload">): SessionSystemUpdateOutboxKindPayload;
7551
9055
  /**
7552
9056
  * Read the exact durable parent-update row created by terminal turn settlement.
7553
9057
  * Failure delivery must never upsert this row: settlement owns its payload and
@@ -7654,6 +9158,7 @@ export type AddSessionSystemUpdateInput = {
7654
9158
  lineage?: Record<string, unknown>;
7655
9159
  personalConnectionDelegations?: McpPersonalConnectionDelegation[];
7656
9160
  xaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1;
9161
+ scheduledTaskRunId?: string | null;
7657
9162
  } & SessionSystemUpdateInputVariant;
7658
9163
  export type AddSessionSystemUpdateResult = {
7659
9164
  added: false;
@@ -7668,12 +9173,46 @@ export type AddSessionSystemUpdateResult = {
7668
9173
  temporalWorkflowId: string | null;
7669
9174
  events: SessionEvent[];
7670
9175
  };
9176
+ export type PrepareSessionSystemUpdateSourceResult = {
9177
+ /** Private, bounded, content-free source authority appended before insert. */
9178
+ lineage?: Record<string, unknown>;
9179
+ };
7671
9180
  export declare function addSessionSystemUpdate(db: Database, input: AddSessionSystemUpdateInput): Promise<AddSessionSystemUpdateResult>;
7672
9181
  /**
7673
9182
  * Persist one internal update without fabricating a user prompt or queue row.
7674
9183
  * Dedupe and any producer/outbox mutation commit in the same transaction.
7675
9184
  */
7676
- export declare function addSessionSystemUpdateWithSourceMutation(db: Database, input: AddSessionSystemUpdateInput, mutateSource: (tx: Database, wakeEventId: string | null, updateId: string | null) => Promise<void>): Promise<AddSessionSystemUpdateResult>;
9185
+ export declare function addSessionSystemUpdateWithSourceMutation(db: Database, input: AddSessionSystemUpdateInput, mutateSource: (tx: Database, wakeEventId: string | null, updateId: string | null) => Promise<void>, options?: {
9186
+ /** Runs under the locked session/source transaction before any update/event insert. */
9187
+ prepareSource?: (tx: Database, sessionId: string) => Promise<PrepareSessionSystemUpdateSourceResult | void>;
9188
+ }): Promise<AddSessionSystemUpdateResult>;
9189
+ /**
9190
+ * One durable machine input by id, under the ordinary workspace RLS scope.
9191
+ * The row outlives delivery, so a late bounded projection of an already
9192
+ * announced `system.update.pending` event (Slack notification delivery)
9193
+ * resolves the exact typed notice instead of re-deriving it from the
9194
+ * lossy event preview. Read-only: it never mutates or consumes the update.
9195
+ */
9196
+ export declare function getSessionSystemUpdateById(db: Database, workspaceId: string, sessionId: string, updateId: string): Promise<SessionSystemUpdate | null>;
9197
+ /**
9198
+ * Whether the parent already holds a `child_requires_action_resolved` notice
9199
+ * for one exact blocked boundary. Read-only, under the ordinary workspace RLS
9200
+ * scope, and answered entirely from the PARENT's own rows: the child session is
9201
+ * never read.
9202
+ *
9203
+ * A resolution supersedes a still-pending `child_requires_action` in the same
9204
+ * commit, but a notice already claimed into a parent turn is `delivered` and
9205
+ * keeps that state forever. A late reader (Slack delivery running behind a
9206
+ * widened retry window) therefore cannot decide staleness from `state` alone.
9207
+ * One accepted response advances that exact (child, turn, generation) boundary
9208
+ * - a re-freeze is a new generation and a new notice - so the presence of the
9209
+ * resolution row in any state is the durable "no longer blocked" fact.
9210
+ */
9211
+ export declare function childRequiresActionResolutionExists(db: Database, workspaceId: string, sessionId: string, boundary: {
9212
+ childSessionId: string;
9213
+ childTurnId: string;
9214
+ childTurnGeneration: number;
9215
+ }): Promise<boolean>;
7677
9216
  export declare function listOutstandingSessionSystemUpdates(db: Database, workspaceId: string, sessionId: string): Promise<SessionSystemUpdate[]>;
7678
9217
  /** Internal updates atomically attached when this inference was claimed. */
7679
9218
  export declare function listSessionSystemUpdatesForTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise<SessionSystemUpdate[]>;
@@ -7698,6 +9237,8 @@ export declare function acceptSessionApprovalDecision(db: Database, input: {
7698
9237
  sessionId: string;
7699
9238
  subjectId: string;
7700
9239
  payload: Record<string, unknown>;
9240
+ /** Bounded decider kind for the parent's resolution notice; `human` when omitted. */
9241
+ respondedByKind?: ChildRequiresActionRespondedByKind;
7701
9242
  clientEventId?: string | null;
7702
9243
  interactionIntervention?: {
7703
9244
  interventionId: string;
@@ -7731,6 +9272,7 @@ export declare function expireSessionInteractionIntervention(db: Database, input
7731
9272
  export declare function appendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[]): Promise<{
7732
9273
  events: SessionEvent[];
7733
9274
  accepted: boolean;
9275
+ canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
7734
9276
  }>;
7735
9277
  /**
7736
9278
  * Commit one exact-attempt mutation and its timeline projection together. The
@@ -7741,6 +9283,7 @@ export declare function mutateAndAppendSessionEventsForTurnAttempt(db: Database,
7741
9283
  events: SessionEvent[];
7742
9284
  accepted: boolean;
7743
9285
  mutationApplied: boolean;
9286
+ canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
7744
9287
  }>;
7745
9288
  export type SettleCodemodeOperationWithOutputInput = {
7746
9289
  accountId: string;
@@ -7837,5 +9380,8 @@ export * from "./browser-auth.js";
7837
9380
  export * from "./browser-downloads.js";
7838
9381
  export * from "./attached-browser-devices.js";
7839
9382
  export * from "./interaction-revisions.js";
9383
+ export * from "./interaction-placement-loss.js";
7840
9384
  export * from "./canonical-human-identities.js";
7841
9385
  export * from "./session-tenancy.js";
9386
+ export * from "./governed-learning-activation.js";
9387
+ export * from "./automations.js";