export * from "./billing-credit-notifications"; import { recoverProviderClockAfterDependencyWait, PROVIDER_RECOVERY_SUSPENDED_AT, } from "./provider-recovery-clock"; import { pendingApprovalAccountOwner, SessionApprovalForbiddenError, } from "./personal-connection-approval"; export { continueSessionWaitingWork, getSessionMachineAccess } from "./session-machine-access"; export { canonicalSecretPermissions } from "./canonical-secret-permissions"; import { jsonbNodeCountSql, jsonbPropertyCountSql } from "./jsonb-shape-counts"; import { measureJsonObjectText } from "./json-object-text-measurement"; import { listWorkspaceBackgroundCommandsInScope } from "./session-background-commands"; import { automationRunPresentation } from "./automation-run-presentation"; import { resolveSessionAppActionAuthority } from "./session-admin-access"; export * from "./site-session-access"; export * from "./app-sync"; export * from "./app-webhooks"; export * from "./app-server"; export * from "./site-tool-data"; export * from "./app-package-exports"; export * from "./organization-connectors"; import { organizationConnectorLogin, type OrganizationConnectorRow, } from "./organization-connectors"; import { siteSessionAccessFilter } from "./site-session-access"; import { terminalTurnContentPayload, withTurnUsage } from "./turn-credit-usage"; export { turnUsageByTurn, withTurnUsage } from "./turn-credit-usage"; import { decodeActivityXid, encodeActivityXid, isActivityXidToken, normalizeActivityToken, } from "./session-activity-xid"; import { syncGitHubEventRoutes, wakeScheduledTaskEventSubscriptions } from "./event-triggers"; export { listExhaustedScheduledTasks, retireExhaustedScheduledTask, listScheduledTaskScheduleReconciliations, acknowledgeScheduledTaskScheduleReconciliation, deferScheduledTaskScheduleReconciliation, } from "./scheduled-task-lifecycle"; export * from "./scheduled-task-blockers"; export * from "./session-target"; export * from "./session-resource-removal"; export * from "./session-repository-attach"; import { admitRequestedRepositories } from "./session-resource-removal"; export * from "./github-gateway"; import { isGitHubGatewayApprovalId } from "./github-gateway"; export * from "./active-session-history"; import type { ActiveSessionHistoryFootprint } from "./active-session-history"; export * from "./session-search-records"; export * from "./session-first-request-tools"; export * from "./console-sign-in-audit"; export * from "./model-call-timing"; export * from "./sandbox-stop-notice"; export * from "./turn-timing-profile"; export * from "./turn-timing-profile-store"; export * from "./model-provider-execution-inputs"; export * from "./workspace-model-catalog-inputs"; import { modelCallTimingColumns, modelCallTimingOrNull, type ModelCallTiming, } from "./model-call-timing"; export * from "./human-input-secret-answers"; export * from "./secret-use-approvals"; export * from "./personal-connection-approval"; export * from "./credential-profiles"; export * from "./connected-machine-audience"; export * from "./disconnect-audit"; import { type ActiveSandboxPointer } from "./active-sandbox"; import { ARCHIVED_CHAT_SANDBOX_KEPT_SECONDS, sessionRetentionFromRow } from "./session-archive"; import { sessionQueueIsEmptyInTransaction } from "./empty-session-queue"; import { isProviderCapacityWaitReason, type SubscriptionReconnectAccount, } from "@opengeni/contracts/subscription-capacity-wait"; import { applyPreparedSecretAnswersInTransaction, type PreparedSecretAnswer, } from "./human-input-secret-answers"; import { decideSecretUseApprovalTx, secretUseApprovalsForSessionTx, secretUseApprovalView, type SecretUseApprovalRow, } from "./secret-use-approvals"; import type { VaultDbContext } from "./vaults"; import { browserDeadlineCheckpoint } from "./browser-deadline-checkpoints"; import { BrowserSessionNotFoundError, BrowserSessionOperationConflictError, BrowserSessionStateError, clearSuspendedBrowserSessionController, } from "./browser-sessions"; import { buildOrganizationCodexConnectionTokenResolver, findOrganizationCodexConnection, readOrganizationCodexUsage, } from "./organization-codex-usage"; export * from "./organization-slack-bots"; export * from "./slack-agents"; export * from "./agents"; export * from "./organization-agent-runtime"; import { inheritedSessionOrgAgentInTransaction, orgAgentConfigSharesInstructions, readOrgAgentKeysInTransaction, readOrgAgentVersion, withOrgAgentsVisible, } from "./organization-agent-runtime"; export * from "./organization-agents"; export * from "./organization-agent-compute"; export { WorkspaceNotFoundError } from "./database"; export * from "./slack-agent-proposals"; export * from "./slack-agent-updates"; export * from "./voice-transcription-settlement"; import { connectionMetadataColumns, connectionSubjectVisibility, getConnectionMetadata, listConnectionsMetadata, mapConnectionMetadata, withConnectionSubjectRls, type ConnectionMetadataWithVerification, } from "./connection-metadata"; import { CONNECTION_DISCONNECTED_AUDIT_ACTION, insertDisconnectAuditEventInScope, type DisconnectAuditActor, } from "./disconnect-audit"; export { getConnectionMetadata, getConnectionMetadataByIds, getProviderConnectionHomeWorkspace, listConnectionsMetadata, type ConnectionMetadataWithVerification, } from "./connection-metadata"; export { readCreditPromotionPolicy } from "./credit-promotion-policy"; export * from "./subscription-plans"; export * from "./billing-auto-top-up"; export * from "./card-verification"; export * from "./billing-auto-top-up-notifications"; export { applyCreditLedgerEntry, applyCreditLedgerEntryOnce } from "./credit-ledger"; export { getBillingCustomer } from "./billing-customer"; import { beginPlanCreditSettlement } from "./subscription-plans"; import { readCardVerificationGate, readCardVerificationInTransaction, subjectVerifiedCardInTransaction, } from "./card-verification"; export * from "./subscription-plan-maintenance"; import { byokFeeFunding, chargeBillingOrigin, getBillingBalance, getSpendableCreditBalance, receiptCreatedAt, planPostUseCreditAllocations, readBillingBalance, type CreditUsage, } from "./credit-balances"; import { chainedReceipt, feeDebtRepaid, paidCreditMark } from "./paid-credit"; export { apiSpendableCreditMicros, byokFeeSpendableMicros, chargeBillingOrigin, getBillingBalance, getByokFeeSpendableBalance, getSpendableCreditBalance, spendableCreditMicros, toolCreditUsage, VOICE_CREDIT_USAGE, type CreditUsage, } from "./credit-balances"; import { lockTurnAttemptWriteFenceTx, type TurnAttemptFenceRejectReason, } from "./session-attempt-fence"; export type { TurnAttemptFenceRejectReason } from "./session-attempt-fence"; export { lockTurnAttemptWriteFenceTx } from "./session-attempt-fence"; import type { TurnAttemptEventFenceResult, TurnAttemptFenceResult } from "./session-attempt-fence"; export type SessionEventMutation = ( tx: Database, fence: Projection extends "event" ? TurnAttemptEventFenceResult : TurnAttemptFenceResult, ) => Promise; /** Derive attempt state from the canonical events inserted in this same transaction. */ export type SessionEventProjection = ( tx: Database, fence: TurnAttemptEventFenceResult, events: SessionEvent[], ) => Promise; /** Plain callbacks retain full rows; checkpoints may explicitly request only fence fields. */ export type SessionEventMutationInput = | SessionEventMutation | { rowProjection: "event"; mutate: SessionEventMutation<"event">; project?: SessionEventProjection; }; export { sessionHasToolRouterHistory, sessionsWithToolRouterHistory, } from "./session-tool-router-history"; export { effectiveSessionPolicyQuery } from "./session-execution-policy"; import { BROWSER_WAIT_HOLD_MAX_MS, boundSessionEventPayloadForWrite, CAPABILITY_SETUP_COMPLETED_NAME_MAX_CHARS, capabilitySetupCompletedSummary, type CapabilitySetupContinuationSkipReason, CODEX_CREDENTIAL_POLICY_SNAPSHOT_METADATA_KEY, CONNECTED_COMMAND_CHILD_CLEANUP_NOTICE, parseSecretReference, type SecretReference, ToolReviewContext, WorkspaceModelCompactionThresholdsPatch, WorkspaceRealtimeVoicePatch, cleanStoredSessionTitle, workspaceSettingsAllowCreditModels, readTurnServingPolicyV1, AppShotCapture, classifyPromptCacheWarmMiss, parsePromptCacheObservation, parseModelCallProcessingResidency, modelCallProcessingResidency, type ModelCallProcessingResidencyV1, type PromptCacheCallSample, type PromptCacheDiagnostics, type PromptCacheObservation, resolveSessionUnattended, sessionMetadataUnattended, withSessionUnattendedMetadata, type SessionUnattendedSetting, parseSessionRemovedRepositories, type SessionRemovedRepository, } from "@opengeni/contracts"; import { API_CREDITS_REQUIRED_MESSAGE, WORKSPACE_OWNER_PERMISSIONS } from "@opengeni/contracts"; import { recordToolApproval } from "@opengeni/observability"; import { connectorActionFingerprint } from "./connector-action-fingerprint"; import { resolveConnectorActionPolicy, connectorActionPolicyDecision, connectorActionPoliciesForAccountRoutes, connectorToolPolicyRevision, ConnectorToolPermissionConflictError, withMinimumConnectorDecision, type ResolvedConnectorActionPolicy, } from "./connector-action-policy"; export { resolveConnectorActionPolicy, connectorActionPolicyDecision, projectConnectorToolPermission, connectorActionPoliciesForAccountRoutes, connectorToolPolicyRevision, ConnectorToolPermissionConflictError, withMinimumConnectorDecision, type ResolvedConnectorActionPolicy, } from "./connector-action-policy"; import { agentSelectionNotes, loadInboxExecutionContext, turnHuman, inboxOrigin, } from "./inbox-execution-context"; import { notWaitingForMachineOwnerSql, runnableQueuedTurnExists, sessionMachineOwnerSubject, WAITED_FOR_MACHINE_OWNER_MODEL_CONTEXT, waitsForMachineOwnerSql, } from "./machine-owner-wait"; import { childRequiresActionRouteTx, parentOutboxAuthorityTx, recordedChildNoticeTargetTx, type ChildRequiresActionRoute, } from "./child-outbox-authority"; import { compactionFailureHoldSequenceTx, systemUpdatePendingAfterSequenceSql, } from "./compaction-failure-hold"; export { lockLiveNativeOriginalOriginTx, type ModalNativeLiveOriginScope, type ModalNativeLiveOriginProjection, type ModalNativeLiveOriginResult, } from "./modal-native-live-origin"; export { SubscriptionAccountChangedError } from "./subscription-account-conflict"; export { abandonSubscriptionCapacityWakeDelivery, acquireSubscriptionOperationLease, acquireSubscriptionTurnLease, assertSubscriptionTurnLeaseCurrent, assertSubscriptionOperationLeaseCurrent, claimSubscriptionCapacityWakeDeliveries, createSubscriptionConnection, listSubscriptionConnectionsForPlacement, listDueSubscriptionCapacityWaiters, markSubscriptionCapacityWakeDelivered, observeSubscriptionCapacityWaiterWake, readSubscriptionEffectiveSettings, readSubscriptionSessionBinding, resolveSubscriptionConnectionId, releaseSubscriptionOperationLease, releaseSubscriptionTurnLease, renewSubscriptionOperationLease, renewSubscriptionTurnLease, retrySubscriptionCapacityWakeDelivery, upsertSubscriptionCapacityWaiter, wakeSubscriptionCapacityWaiter, writeSubscriptionSessionBinding, type SubscriptionCapacityWaiter, type SubscriptionCapacityWakeDelivery, type DueSubscriptionCapacityWaiter, type SubscriptionOperationKind, type SubscriptionOperationLease, type SubscriptionOperationLeaseIdentity, type SubscriptionTurnLease, type SubscriptionTurnLeaseIdentity, type SubscriptionSessionBinding, type EffectiveSubscriptionSettingsRow, } from "./subscription-core-repository"; export { assertSubscriptionCoreAcceptedTurn, withSubscriptionCoreAcceptedTurn, type SubscriptionCoreAcceptedTurnAccessResult, type SubscriptionCoreAcceptedTurnIdentity, type SubscriptionCoreRefreshResult, type SubscriptionCorePlacementWorldRequest, type SubscriptionCorePlacementWorldResult, } from "./subscription-core-placement-world"; export { codexSubscriptionAuthorityV2ForAcceptanceInTransaction, codexSubscriptionAuthorityV2ForScheduledTaskInTransaction, persistSubscriptionCodexRefresh, persistSubscriptionCodexRefreshWithPlan, withSubscriptionCoreCodexRefreshLock, withSubscriptionCorePlacementWorld, type SubscriptionCoreCodexRefreshResult, } from "./subscription-core-codex-bindings"; import type { GoalAdmissionPausedReason } from "@opengeni/contracts"; import { accountContactEmail } from "@opengeni/contracts/passkey-only-account"; import { microsoftDynamicsProductForMcpUrl } from "@opengeni/contracts/microsoft-dynamics"; import { SessionAvatar as SessionAvatarSchema, type SessionAvatar } from "@opengeni/contracts"; import { SessionLinkList as SessionLinkListSchema, SessionLink as SessionLinkSchema, SESSION_LINKS_MAX, SessionWaitingOn as SessionWaitingOnSchema, type SessionLink, type SessionWaitingOn, } from "@opengeni/contracts"; import { SubscriptionPersonalAuthorityV2 } from "@opengeni/contracts"; import { subscriptionExecutionAuthorityFromTurn } from "./accepted-subscription-authority"; import { MEETING_SUMMARY_POLICY_ROLE, MEETING_SUMMARY_RECORDING_METADATA_KEY, MEETING_SUMMARY_SUBJECT_ID, MEETING_SUMMARY_TOOLS, } from "./recordings"; export const getScheduledTaskClaudeProviderAccountAuthoritySnapshot = ( db: Database, workspaceId: string, taskId: string, ) => getAcceptedSubscriptionTaskAuthority(db, "claude", workspaceId, taskId); export const getSessionTurnClaudeProviderAccountAuthoritySnapshot = ( db: Database, workspaceId: string, sessionId: string, turnId: string, ) => getAcceptedSubscriptionTurnAuthority(db, "claude", workspaceId, sessionId, turnId); export const getSessionParentClaudeProviderAccountAuthority = ( db: Database, workspaceId: string, childSessionId: string, ) => getAcceptedSubscriptionParentAuthority(db, "claude", workspaceId, childSessionId); import { WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1 } from "@opengeni/contracts"; import { getAcceptedSubscriptionTaskAuthority, getAcceptedSubscriptionTurnAuthority, getAcceptedSubscriptionParentAuthority, sharedPoolSubscriptionAuthoritySnapshotsInTransaction, } from "./accepted-subscription-authority"; export { getScheduledTaskSubscriptionAuthority, receiverCodexSubscriptionAuthorityV2InTransaction, } from "./accepted-subscription-authority"; import { directModelConnectionSpec, isDirectModelId } from "@opengeni/contracts"; import { BYOK_PLATFORM_FEE_TYPE, storedBillingOrigin, type BillingOrigin, } from "@opengeni/contracts"; import { normalizeOrganizationAccessPolicy, type OrganizationAccessPolicy, type UpdateOrganizationApiKeyRequest, } from "@opengeni/contracts"; import { organizationApiKeyAllowsWorkspace, organizationApiKeyPolicyProjection, readOrganizationApiKeyWorkspaceScopes, replaceOrganizationApiKeyWorkspaceScope, validateOrganizationApiKeyWorkspaceScope, } from "./organization-api-key-access"; export { OrganizationApiKeyWorkspaceScopeError } from "./organization-api-key-access"; export * from "./personal-api-keys"; export * from "./organization-privacy-preferences"; export * from "./organization-inference-residency"; export * from "./workspace-content-flow"; import { personalApiKeyAccess } from "./personal-api-keys"; import { effectiveKeyPermissions, insertOrganizationServiceAccount, lockOrganizationServiceAccount, OrganizationServiceAccountRoleError, permissionsBeyondServiceAccountRole, serviceAccountsForKeys, } from "./organization-service-accounts"; export { createOrganizationServiceAccount, deleteOrganizationServiceAccount, effectiveKeyPermissions, getOrganizationServiceAccount, listOrganizationServiceAccounts, OrganizationServiceAccountNotFoundError, OrganizationServiceAccountRoleError, updateOrganizationServiceAccount, } from "./organization-service-accounts"; import { PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS } from "@opengeni/contracts/session-titles"; import { sessionListEntry } from "@opengeni/contracts/session-list-entries"; import { currentSessionAttachmentReadAccess, currentSessionRlsActorInitiatingHumanSubjectId, withoutSessionRlsActor, } from "./database"; import { ambientBillingOrigin, CreditDebitAttribution, creditDebitAttributionMetadata, currentCreditDebitAttribution, } from "./credit-debit-attribution"; import { checkWorkspaceAllowance } from "./usage-allowances"; import { readSessionFileAttachments } from "./session-file-attachments"; export { acceptSessionFileAttachments, readSessionFileAttachments, type SessionAttachmentReadAccess, } from "./session-file-attachments"; import { parseAcceptedMcpAccountBindings, parseConnectionAccountIntent, sessionCreateConnectionSelectionFailure, } from "./mcp-account-bindings"; import { withoutLapsedWorkspaceAccountBindings } from "./lapsed-workspace-account-bindings"; export { SessionCreateConnectionSelectionUnavailableError, parseConnectionAccountIntent, } from "./mcp-account-bindings"; import { childTerminalResultFinalAnswer, childTerminalResultFinalAnswerSequences, childTerminalResultFinalAnswerWithGoalContinuations, type ChildTerminalResultFinalAnswer, SKILL_CATALOG_CONTEXT_PREFIX, SandboxCheckpointSelection, SandboxRecoverySelection, SandboxRecoveryTarget, SandboxRecoveryResponse, SandboxFreshWorkspaceRecovery, SandboxFreshWorkspaceReason, automaticSandboxRecoveryDiscontinuity, freshWorkspaceSandboxRecoveryDiscontinuity, sandboxRecoveryDiscontinuity, type SandboxRecoveryProjection, type SandboxRecoveryRequest, ModalRouterProviderCommand, readSkillCatalogContext, skillCatalogContextItem, REPOSITORY_SKILLS_CONTEXT_PREFIX, readRepositorySkillsContext, repositorySkillsContextItem, WORKSPACE_GOVERNANCE_CONTEXT_PREFIX, WORKSPACE_GOVERNANCE_NONE, readWorkspaceGovernanceContext, workspaceGovernanceContextItem, WORKSPACE_FILESYSTEM_CONTEXT_PREFIX, readWorkspaceFilesystemContext, workspaceFilesystemContextItem, AGENT_INSTRUCTIONS_CONTEXT_PREFIX, agentInstructionsContextItem, agentInstructionsContextText, readAgentInstructionsContext, sameAgentInstructionsContext, sessionTurnSurfaceOrNull, type SessionTurnSurface, } from "@opengeni/contracts"; import { readReasoningConfiguration, reasoningConfigurationItem, type ConfigurationEffort, } from "@opengeni/codex"; export { getSessionAttemptMcpApprovalPolicies } from "./session-mcp-approval"; import { settleExitedWorkerAdmissions } from "./exited-worker-admissions"; import { crashedWorkerOrphanAdmissionSql, sessionAttemptPendingWritersSql, sessionMayAwaitQuiescenceSql, sessionPendingWriterAttemptIdsSql, sessionQuiescenceCandidateAttemptIdsSql, } from "./session-attempt-writers"; import { childRecentTurnOutcomesSql, childLifecycleEvidenceCandidatesSql, completeMeaningfulSessionEventSql, meaningfulSessionEventSql, } from "./session-meaningful-events"; import { boundedChildLifecycleEvidence, logicalChildReadEvent, historicalChildReadItems, historicalChildReadMatches, } from "./child-read-reconciliation"; import { createRetryFailedSessionInTransaction } from "./session-retry"; import { WorkspaceArtifactNotFoundError } from "./workspace-artifacts"; export { SessionRetryConflictError, getSessionRetryReceiptInTransaction } from "./session-retry"; import { retainedProviderCommandPersistence as retainedProviderCommandState } from "./retained-provider-commands"; export const retryFailedSessionInTransaction = createRetryFailedSessionInTransaction( sessionEffectiveSandboxRecoveryBlocked, ); export * from "./codex-plan-entitlement"; export * from "./subscription-core-codex"; export * from "./subscription-core-codex-apps"; export * from "./subscription-core-codex-compat"; export type { CodexAccountStatus, CodexRotationSettings, EffectiveCodexSubscriptionSource, WorkspaceCodexSubscriptionMode, WorkspaceCodexSubscriptionSource, } from "./codex-account-types"; export * from "./subscription-core-codex-operations"; export * from "./subscription-core-codex-requests"; export * from "./subscription-core-codex-connections"; export * from "./subscription-core-codex-catalog"; export * from "./subscription-settings"; export { readSubscriptionCoreFunding, readSubscriptionCoreReadiness, } from "./subscription-core/funding-readiness"; // The provider-parameterized runtimes, reachable by provider binding (design // 5.3, SuperGrok track X1a; this supersedes 5.1.3's "the package index exports // none of the provider-parameterized entry points"). A binding of a provider // missing from the registry fails closed at every entry point. export { subscriptionCoreTurns, readSubscriptionCoreTurnModel, type SubscriptionCoreCredential, type SubscriptionCoreLeaseRef, type SubscriptionCorePlacement, type SubscriptionCorePlacementRequest, } from "./subscription-core/turns"; export { subscriptionCoreRequests, type SubscriptionCoreRequestOutcome, } from "./subscription-core/requests"; export { subscriptionCoreSettlement, type SubscriptionCoreSettlement, } from "./subscription-core/settlement"; export { listSubscriptionCoreServingConnections, subscriptionCoreConnectionAllowlist, subscriptionCoreConnectionAllowsModel, subscriptionCoreWorkspaceReady, type SubscriptionCoreServingConnection, } from "./subscription-core/catalog"; export { SubscriptionCoreError } from "./subscription-core/errors"; export * from "./subscription-usage-pool"; export type { SubscriptionCoreProvider } from "./subscription-core/provider"; export { buildSubscriptionCoreTurnTokenResolver } from "./subscription-core/turn-token-resolver"; export * from "./subscription-core-xai-adapter"; export * from "./subscription-core-xai"; // Claude usage, readiness and admission on the core (design 5.3, Claude // track C2a); every caller reads the Claude provider route first. export * from "./subscription-core-claude-usage"; export * from "./subscription-core-claude-reads"; export * from "./subscription-core-claude-limit-resets"; // Provider-neutral operations outside chat (media, transcription, realtime, // usage and catalog probes), bound per provider by the caller. export { subscriptionCoreOperations, type SubscriptionCoreFetch, type SubscriptionCoreOperationLeaseRef, type SubscriptionCoreOperationScope, } from "./subscription-core/operations"; export { subscriptionCoreOperationConnections, type SubscriptionCoreConnectionToken, type SubscriptionCoreOperationCandidate, type SubscriptionCoreUsageProbe, } from "./subscription-core/operation-connections"; // The provider-neutral administration a provider's routes run over on the // core (SuperGrok track X2b; the Claude track reuses it with its binding). export { readSubscriptionCoreWorkspaceView, renameSubscriptionCoreConnection, setSubscriptionCoreAllocator, setSubscriptionCorePrimary, setSubscriptionCoreRotation, type SubscriptionCoreConnectionReach, type SubscriptionCoreConnectionRow, type SubscriptionCoreWake, type SubscriptionCoreWorkspaceView, } from "./subscription-core/administration"; export { disconnectSubscriptionCoreConnection, resolveSubscriptionCoreRouteConnectionId, type SubscriptionCoreConnectRefusal, type SubscriptionCoreDisconnectAudit, type SubscriptionCoreDisconnectOutcome, } from "./subscription-core/connections"; // Account administration a request proved without an organization membership // (configured access key, account-scoped key, signed delegation). export { withSubscriptionAccountAdministrators, type SubscriptionAccountAdministratorResolver, type SubscriptionAccountAdministratorStamp, } from "./subscription-core/account-administrator"; import { setSubscriptionAdministrationSubject } from "./subscription-core/account-administrator"; export * from "./subscription-core-xai-compat"; export * from "./subscription-core-claude-adapter"; export * from "./subscription-core-claude"; export * from "./subscription-core-claude-compat"; // Live usage reads outside a workspace pool: an organization administrator's // and a personal connection owner's (design 5.3). export { subscriptionCoreAdministeredConnections, SUBSCRIPTION_CORE_ADMINISTERED_READ_TIMEOUT_MS, type SubscriptionCoreAdministeredJoinedFetch, type SubscriptionCoreAdministeredProbeDeps, type SubscriptionCoreAdministeredScope, } from "./subscription-core/administered-connections"; // A person's own personal connections outside placement: stored status for // status reads and the live re-read of a stored exhaustion (design 5.3). export { listOwnSubscriptionCoreConnections, subscriptionCorePersonalConnections, type OwnSubscriptionCoreConnection, type SubscriptionCorePersonalConnection, } from "./subscription-core/personal-connections"; import { listSubscriptionCoreCodexServingConnections, subscriptionCoreCodexConnectionAllowlist, } from "./subscription-core-codex-catalog"; import { listSubscriptionCoreCodexPersonalAccountsInTransaction, projectSubscriptionCoreCodexWorkspace, type SubscriptionCoreCodexWake, } from "./subscription-core-codex-compat"; export { pinSubscriptionCoreSessionCodexAccount } from "./subscription-core-codex-compat"; export * from "./scheduled-task-access"; export { buildSlackApiRateLimiter } from "./slack-api-rate-limits"; export { admitMcpConnectionRateLimit } from "./mcp-connection-rate-limits"; export * from "./scheduled-human-wait"; import { CODEX_CAPACITY_RECOVERY_KEY, readCodexCapacityRecovery, codexFalseResumptionBackoffMs, clearCodexCapacityRecovery, SUBSCRIPTION_CORE_WAIT_EXHAUSTED_CODES, } from "./codex-capacity-recovery"; import { projectSessionAdmissionBlock, type SessionAdmissionFence, StoredSessionAdmissionBlock, } from "./session-admission-block"; export type { SessionAdmissionFence, StoredSessionAdmissionBlock } from "./session-admission-block"; import { SessionMessageSearchRequest, type SessionMessageSearchResponse, } from "@opengeni/contracts"; import { ResolvedAgentConfig } from "@opengeni/contracts"; import { scanSessionMessages } from "./session-message-search"; import { excludeUnclaimedHumanPromptEventFilter } from "./session-prompt-visibility"; import { withDatabaseStatementTimeout } from "./database"; import { withPoolWakeServiceScopeInTransaction } from "./subscription-session-access"; import { readSubscriptionSessionBinding as readCoreSessionBinding, recordSubscriptionCoreRateLimitResetInTransaction, } from "./subscription-core-repository"; import { wakeSubscriptionCoreCapacityWaiters, type SubscriptionCoreWakeScope, } from "./subscription-core/waiters"; import { capacityWaitCandidateProviders } from "./subscription-core/waiter-candidates"; export { chooseSubscriptionCoreSessionAccount, readSubscriptionCoreSessionAccountChoice, readSubscriptionPersonPreferences, writeSubscriptionPersonPreferences, SUBSCRIPTION_CORE_ACCOUNT_CHOICE_EVENT, type SubscriptionCoreAccountChoiceRefusal, type SubscriptionCoreChoosableConnection, type SubscriptionCoreChoiceProviders, type SubscriptionCoreProviderWake, type SubscriptionCoreSessionAccountChoice, type SubscriptionCoreSessionChoiceOutcome, type SubscriptionCoreSessionChoiceResult, type SubscriptionPersonPreferences, } from "./subscription-core/session-choice"; import type { SubscriptionCoreProviderWake } from "./subscription-core/session-choice"; import { SUBSCRIPTION_CORE_CODEX_PROVIDER } from "./subscription-core-codex-provider"; import type { SubscriptionCoreWake } from "./subscription-core/administration"; export { EMPTY_SUBSCRIPTION_AUTHORITY_V2, copySubscriptionAuthorityCompatInTransaction, coreSubscriptionAuthorityV2ForAcceptanceInTransaction, coreSubscriptionAuthorityV2ForScheduledTaskInTransaction, subscriptionAuthorityV2OrEmpty, type SubscriptionAuthorityCarrier, } from "./subscription-core-acceptance-authority"; import { copySubscriptionAuthorityCompatInTransaction, coreSubscriptionAuthorityV2ForAcceptanceInTransaction, coreSubscriptionAuthorityV2ForScheduledTaskInTransaction, subscriptionAuthorityV2OrEmpty, subscriptionAuthorityCompatForCarriersInTransaction, } from "./subscription-core-acceptance-authority"; export { SessionMessageSearchCursorError } from "./session-message-search"; export * from "./artifact-catalog"; export * from "./site-data"; export * from "./app-activity-events"; export * from "./sidebar-layouts"; export * from "./site-publishing"; export { withSiteRuntimeAdmission } from "./site-runtime-admission"; export * from "./site-platform"; export * from "./insights-site-usage"; export * from "./scheduled-slack-bot-messages"; export * from "./organization-signup-use-cases"; export * from "./site-sql"; export * from "./usage-analytics"; export * from "./slack-file-uploads"; import { grantWorkspaceAccess } from "./workspace-membership-access"; export { grantWorkspaceAccess, insertWorkspaceMembershipIfAbsent, listWorkspaceMembers, } from "./workspace-membership-access"; import { codexSelectionDiagnostics } from "./codex-selection-diagnostics"; export { codexSelectionDiagnostics } from "./codex-selection-diagnostics"; import { z } from "zod"; import { latestStartedSessionTurnQuery, withEffectiveSessionPolicy, withSessionListModelPolicy, } from "./session-execution-policy"; import { updateModelConnectionAccess as updateModelConnectionAccessPolicy, type ModelConnectionAccess, type ModelConnectionTarget, } from "./model-connection-access"; export { assertModelConnectionAllowsTurn, modelAllowedByConnections, type ClaudeCoreModelRestrictions, type ConnectionModelRestrictions, } from "./workspace-model-connection-access"; import type { ClaudeCoreModelRestrictions } from "./workspace-model-connection-access"; import { assertModelConnectionAllowsTurn, getWorkspaceConnectionModelRestrictions as resolveWorkspaceConnectionModelRestrictions, } from "./workspace-model-connection-access"; export * from "./model-connection-access"; export { SubscriptionCoreAccessInvalidError, SubscriptionCoreAccessMoveRequiredError, SubscriptionCoreAccessPeopleUnlistableError, SubscriptionCoreAccessPersonNotInOrganizationError, SubscriptionCoreAccessWorkspaceNotAdministeredError, type SubscriptionCoreAccess, } from "./subscription-core/access"; import { createHash, randomUUID } from "node:crypto"; import { SCHEDULED_HUMAN_WAIT_TIMEOUT_CLIENT_EVENT_PREFIX, scheduledRunHumanWaitsInRlsContext, } from "./scheduled-human-wait"; import { appendGoalReportRequirements, goalReportRequirements, GOAL_REPORT_REQUIREMENTS_KEY, } from "./session-goal-reports"; import { verifyGoalReportDeliveries, type ReportArtifactActor } from "./session-goal-reports"; export { recordNativeDocumentInspection } from "./session-goal-reports"; import { type SessionGoalReportRequirement, type SessionGoalReportDelivery, } from "@opengeni/contracts"; import { lockSkillPublication } from "./skill-publication"; import { StoredSessionSkills, readSkillMetadata, withBundledSkillSelectionMetadata, bundledSkillSelectionFromMetadata, storedBundledSkillSelectionIdentity, type BundledSkillId, type SkillRecord, } from "@opengeni/contracts"; import { applySkillLifecycle, confirmSkillHumanResponse, assertSkillReadAttempt, listSkillRecords, skillFilesContentHash, } from "./skills"; import { releaseOrphanedSkillHeads, type SkillSourceReleaseReceipt } from "./skill-source-release"; import type { SkillActor, SkillWriteReceipt } from "@opengeni/contracts"; import { isDeepStrictEqual } from "node:util"; export * from "./connect-attempts"; export * from "./external-identities"; export * from "./external-identity-links"; export * from "./connection-setup-authority"; export * from "./external-link-work"; import { inheritExternalLinkTurnAuthority, captureScheduledExternalLinkTurnAuthority, cloneExternalLinkTaskAuthority, getExternalLinkTurnAuthorization, externalLinkWorkSnapshotIsLive, } from "./external-link-work"; import { SESSION_GOAL_PROGRESS_MAX_BYTES, SESSION_GOAL_RATIONALE_MAX_BYTES, SESSION_GOAL_ROOT_CONSTRAINT_MAX_BYTES, SESSION_GOAL_ROOT_CONSTRAINTS_MAX_BYTES, SESSION_GOAL_ROOT_CONSTRAINTS_MAX_ITEMS, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, SESSION_GOAL_TEXT_MAX_BYTES, SESSION_SYSTEM_UPDATE_WAKE_CLASS, SessionNotificationPostedPayload, ToolAuthNeededPayload, connectionCardNotice, SessionSystemUpdateKind as SessionSystemUpdateKindSchema, isChildLifecycleSystemUpdateKind, type ChildLifecycleSystemUpdateKind, type ChildRequiresActionResolvedOutcome, type ChildRequiresActionRespondedByKind, ModelContextContributionSummaries, ListWorkspaceMemberCandidatesResponse, OrganizationMember, WorkspaceMember as WorkspaceMemberContract, SessionGoalSnapshot, AUTOMATIC_SESSION_TITLE_FALLBACK, ScheduledTaskRunAcceptedExecution, ConnectionAccountSelectionDiagnostic, ScheduledTaskDegradedAccounts, ScheduledTaskAdmissionRefusal, WORK_CLAIM_DISCOVERY_DEFAULT_LIMIT, WORK_CLAIM_DISCOVERY_LIMIT, WORK_DISCOVERY_QUERY_MAX_CHARS, WORK_DISCOVERY_RECENT_HOURS_MAX, WorkClaimDiscoverySummary as WorkClaimDiscoverySummarySchema, WorkDiscoveryMatch as WorkDiscoveryMatchSchema, WorkClaimNamespace, WorkClaimSubjectType, WorkClaimCanonicalKey, SessionStatus as SessionStatusSchema, SessionGoalRootConstraintsWrite, normalizeSessionGoalRootConstraints, normalizeAutomaticSessionTitle, normalizeWorkClaimCanonicalKey, normalizeWorkClaimNamespace, sessionVisibilityToPublic, sessionGoalUtf8Bytes, } from "@opengeni/contracts"; import { cancelUnacceptedVideoGenerationsForToolCallsInTransaction, markVideoGenerationAcceptedInTransaction, markVideoGenerationTerminalUpdateInTransaction, } from "./video-generation"; import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilityInstallationStatus, CapabilityKind, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileStatus, FileUploadStatus, FirstPartyMcpToolName, HumanInputAnswer, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExport, HostEventExportBatch, HostLifecycleFactExport, HostLifecycleFactExportBatch, HostUsageExport, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, OrganizationMember as OrganizationMemberType, WorkspaceMemberCandidate, McpPersonalConnectionDelegation, McpConnectionAccountBinding, ConnectionAccountIntent, ModelContextContributionSummary, Permission, PersonalResourceAttachmentIntent, PrivateScheduledTaskSummary, ResourceRef, SandboxBackend, SandboxOs, ScheduledTask, ScheduledTaskAction, ScheduledTaskActionKind, ScheduledTaskAgentConfig, ScheduledTaskOverlapPolicy, ScheduledTaskRun, ScheduledTaskRunAcceptedExecution as ScheduledTaskRunAcceptedExecutionType, ScheduledTaskRunMode, ScheduledTaskRunStatus, ScheduledTaskScheduleSpec, ScheduledTaskStatus, ScheduledTaskTriggerType, SlackInstallationBinding, Session, EventSourceKind, SessionAutomationWaitSummary, SessionAgentAccess, SessionAgentAccessViewer, SessionAuthorizationListScope, SessionScopeSubjectId, SessionMemoryScope, SessionListResponse, SessionListTotals, SiteConversationGroup, SessionListEntryResponse, SessionListLatestTurn, SessionTenancyPublicProjection, SessionEvent, SessionEventPayloadMode, SessionEventReadDirection, SessionEventSemanticClass, SessionEventType, SessionGoal, SessionGoalChangeKind, SessionGoalCreatedBy, SessionGoalMutationPolicy, SessionGoalRevision, SessionGoalStatus, SessionHumanInputRequest, LineageNode, SessionMcpApprovalPolicy, SessionMcpApprovalPolicyTarget, SessionBackgroundCommand, SessionSkill, SessionMcpServerMetadata, SessionStatus, SessionToolPolicy, SessionTurn, SessionQueueSnapshot, SessionMcpQueueSummary, SessionSystemUpdate, SessionSystemUpdateKind, SessionSystemUpdateState, SystemUpdateClassification, SessionTurnSource, SessionTurnStatus, TurnInitiator, TurnInitiatorContext, SocialConnection, SocialConnectionStatus, SocialPost, SocialProvider, ToolRef, ReasoningEffort, UsageEvent, Workspace, WorkspaceMember, WorkspaceControlEvent, WorkspaceMemoryPromptMode, Channel, OrganizationComputeReach, Rig, RigProviderImage, RigProviderImages, RigVersion, RigVerificationHealth, RigChange, RigChangeKind, RigChangeStatus, RigCheck, NativeSnapshotDescriptor, TarWorkspaceArchiveDescriptor, WorkspaceArchiveDescriptor, ModalCheckpointProviderBinding, SandboxProviderContinuityRecovery, WorkClaimDiscoverySummary, WorkClaimSubjectFilter, WorkDiscoveryProjection, } from "@opengeni/contracts"; import { closePrivateSessionCreateCapability, openPrivateChildSessionCreateCapability, openPrivateSessionCreateCapability, } from "./session-tenancy"; import { completeCodemodeOperationInTransaction, failCodemodeOperationInTransaction, } from "./codemode-operations"; import { adoptCodemodeApproval } from "./codemode-approvals"; import { cancelTurnInteractionInterventionsInTransaction, type InteractionRequestCurrentTarget, InteractionRequestRefusedError, InteractionResourceStateError, persistAttemptInteractionInterventionInTransaction, resolveInteractionInterventionInTransaction, settleSessionMaintenanceInTransaction, } from "./browser-auth"; import { DEFAULT_FIRST_PARTY_MCP_TOOLS, McpPersonalConnectionDelegations, SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS, backendForNativeSnapshotProvider, canonicalModalCheckpointProviderBinding, decodeNativeSnapshotRef, OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD, SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND, parseWorkspaceArchiveDescriptor, parseWorkspaceArchiveObjectRef, validateWorkspaceArchiveObjectRef, workspaceArchivePayloadPresent, omitInlineWorkspaceArchiveWhenObjectRefPresent, type WorkspaceArchiveObjectRef, stableJson, MODEL_ATTACHMENT_REFS_FIELD, MODEL_ATTACHMENT_CONVERTED_IMAGE_FORMATS, MODEL_ATTACHMENT_CONVERTED_IMAGE_FORMATS_FIELD, MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION, MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION_FIELD, MODEL_TIMELINE_ANNOTATIONS_FIELD, TimelineAnnotations, renderUserMessageContentForModel, MESSAGE_TIME_ZONE_METADATA_KEY, messageTimeZoneFromTurnMetadata, normalizeMessageTimeZone, OPENING_TOOLS_METADATA_KEY, openingToolsFromTurnMetadata, SessionMcpApprovalPolicy as SessionMcpApprovalPolicySchema, RequestHumanInteractionToolInput, WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1, XaiProviderAccountAuthoritySnapshotV1, ClaudeProviderAccountAuthoritySnapshotV1, PersonalResourceAttachmentSummary, type TimelineAnnotation, } from "@opengeni/contracts"; import { approvalIdentifier, McpElicitationApprovalRequest, McpElicitationContent, resolveMcpElicitationContent, boundWorkspaceControlEvent, workspaceControlUtf8Bytes, SESSION_EVENT_RAW_DELTA_TYPES, SESSION_EVENT_PRESENTED_TOOL_LEAVES, SESSION_EVENT_APP_ACTION_CALL_LEAF, SESSION_EVENT_APP_ACTION_ID_SPACE, SESSION_EVENT_PRESENTED_APP_ACTION_NAMES, SESSION_EVENT_BOOKKEEPING_STEP_TYPES, SESSION_EVENT_CONTENT_STEP_TYPES, SESSION_EVENT_CLIENT_EVENT_ID_MAX_BYTES, SESSION_EVENT_DUPLICATE_REASON_MAX_BYTES, SESSION_EVENT_ENVELOPE_MAX_BYTES, SESSION_EVENT_TYPE_MAX_BYTES, resolveSessionEventTypeFilters, capabilityCatalogItemIsTrustedForExposure, latencyModeForMetadata, metadataWithTurnExecutionPolicyV1, metadataWithCodexCredentialPolicySnapshotV1, readCodexCredentialPolicySnapshotV1, readTurnExecutionPolicyV1, reasoningEffortForMetadata, resolveWorkspaceCodexCompactionDefault, type LatencyMode, resolveWorkspaceMemoryEnabled, resolveWorkspaceMemoryPromptMode, RigChange as RigChangeContract, RigProviderImage as RigProviderImageContract, SessionGoal as SessionGoalContract, SessionSystemUpdatePayload, renderSessionSystemUpdateBatch, sessionSystemUpdateBatchHistoryItem, HostEventExport as HostEventExportContract, HostEventExportBatch as HostEventExportBatchContract, HostExportConsumerId, HostLifecycleFactExport as HostLifecycleFactExportContract, HostLifecycleFactExportBatch as HostLifecycleFactExportBatchContract, HostUsageExport as HostUsageExportContract, HostUsageExportBatch as HostUsageExportBatchContract, OPENGENI_HOST_EXPORT_SCHEMA_REVISION, HumanInputQuestion as HumanInputQuestionContract, canonicalSkillReviewQuestion, secretUseApprovalDecisionSummary, secretUseApprovalHumanInput, secretUseApprovalIdFromQuestionId, secretUseApprovalQuestionId, SECRET_USE_APPROVAL_DECISIONS, type SecretUseApprovalDecision, SubmitHumanInputResponseRequest, TurnExecutionPolicyV1, OPENROUTER_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, OPENROUTER_CREDENTIAL_OPERATION_ID_METADATA_KEY, OPPER_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, OPPER_CREDENTIAL_OPERATION_ID_METADATA_KEY, VERCEL_AI_GATEWAY_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, VERCEL_AI_GATEWAY_CREDENTIAL_OPERATION_ID_METADATA_KEY, } from "@opengeni/contracts"; import { environmentsEncryptionKeyBytes, paidSandboxPlanLimit, sandboxPlanTierUnpaid, UNPAID_SANDBOX_PLAN_TIERS, SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS, SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS, WORKSPACE_OPENROUTER_CONNECTION_DOMAIN, WORKSPACE_OPENROUTER_CONNECTION_ROLE, WORKSPACE_ELEVENLABS_CONNECTION_DOMAIN, WORKSPACE_ELEVENLABS_CONNECTION_ROLE, WORKSPACE_OPPER_CONNECTION_DOMAIN, WORKSPACE_OPPER_CONNECTION_ROLE, VERCEL_AI_GATEWAY_CONNECTION_DOMAIN, VERCEL_AI_GATEWAY_CONNECTION_ROLE, type SandboxFleetLimits, type SandboxPlanLimit, type SandboxPlanLimits, type Settings, } from "@opengeni/config"; import { SandboxTransitionWaitBudget } from "./sandbox-transition-wait"; import { normalizeWorkspaceMembershipPermissions } from "./workspace-membership-permissions"; import { canonicalSecretPermissions } from "./canonical-secret-permissions"; import { accountPermissionsForOrganizationRole, allAccountPermissions, } from "./organization-role-permissions"; import { canonicalizePersistedHistoryItem, CodexAppsCredentialUnavailable, omitOutputOnlyHistoryItemFields, isCodexBilledModel, type CodexFetch, } from "@opengeni/codex"; // Re-exported so consumers get the whole codex-billed detection surface (the pure // prefix test + the credential-aware predicates below) from a single import. export { isCodexBilledModel } from "@opengeni/codex"; import { and, asc, desc, eq, exists, getTableColumns, gt, gte, inArray, isNotNull, ilike, isNull, lt, lte, ne, notInArray, or, Param, sql, type SQL, type SQLWrapper, } from "drizzle-orm"; import { anyOf } from "./sql-arrays"; import { unionAll, type PgTransactionConfig } from "drizzle-orm/pg-core"; import { getLiveSessionAttemptTurn } from "./live-session-attempt"; import { contextForCausalTurn, contextWithFrozenCredentialRestrictions, creatorColumns, frozenInitiatorForCommandActor, frozenScheduledOccurrenceInitiator, humanTurnSenderLabel, initiatorColumns, initiatorFromStorage, UNATTRIBUTED_LEGACY_INITIATOR, type FrozenTurnInitiator, } from "./turn-initiator"; export { frozenInitiatorForCommandActor, sameTurnSender, type FrozenTurnInitiator, } from "./turn-initiator"; import { decryptEnvironmentValue, encryptEnvironmentValue } from "./environment-crypto"; import { fromPostgresLosslessJson, fromPostgresLosslessText, isStoredVerbatimAsLosslessJsonString, LOSSLESS_CONTENT_CODEC_VERSION, toPostgresLosslessText, withLosslessContentWriteVersion, } from "./lossless-json"; import { withBoundSessionEventPayloads } from "./session-event-write-bounds"; export { isStoredVerbatimAsLosslessJsonString, LOSSLESS_TEXT_PREFIX, toPostgresLosslessJson, } from "./lossless-json"; import { projectSessionMcpProgressText, projectSessionTextPrefix, sessionTextStoragePrefixChars, SESSION_MCP_PROGRESS_STORAGE_CHARS, sessionMcpProgressScalarIsEncodedSql, } from "./session-mcp-progress"; import { seedNewSessionDraftInTransaction, rememberNewSessionSelectionInTransaction, type NewSessionDraftSnapshot, } from "./new-session-drafts"; import { isRetryableDatabaseTransportFailure, nestedErrorRecords, nestedPostgresSqlState, runIdempotentPersistenceTransaction, safeDatabaseErrorFacts, SessionEventPersistenceError, type IdempotentPersistenceTransactionOptions, } from "./persistence-errors"; export { DatabaseTransactionError } from "./persistence-errors"; import { assertCapabilityComponentVersionCanChange, effectiveCapabilityOwnerSql, lockCapabilityComponentIdentity, } from "./capability-components"; import { closePendingSessionToolCallsInTransaction, consumeSettledPendingToolCallsForCompletedTurnInTransaction, settleInterruptedCodemodeCallsInTransaction, historyCallId, historyItemType, TOOL_RESULT_TYPE_BY_CALL_TYPE, } from "./session-tool-call-settlement"; import { readSessionHistoryToolIdentityPage } from "./session-history-tool-identities"; import { assertAgentCommandAuthorityInTransaction, canonicalSessionCommandHash, closeSessionTurnAttemptInTransaction, evaluateSessionControl, evaluateSessionControls, evaluateSessionDiscoveryControls, evaluateSessionWriteAdmissionControl, lockSessionEventWriteRows, boundedLockStep, workspaceControlLockBudget, workspaceControlRequestLockTimeoutMs, lockWorkspaceInferenceControl, mutateSessionControlInTransaction, registerInternalUpdateWakeInTransaction, registerSessionWorkflowWakeInTransaction, SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS, registerSessionTurnAttemptClaim, reserveSessionCommandReceipt, serializeEffectiveSessionControl, type SessionDiscoveryControl, type SessionCommandActor, SessionControlConflictError, SessionControlInvariantError, updateSessionCommandReceiptResult, type SessionTurnAttemptOutcome, type WorkspaceControlRow, } from "./session-control"; import { ensureManagedHumanPersonalWorkspace } from "./managed-human-provisioning"; import { sessionRealtimeIsActiveInTransaction, settleExpiredSessionRealtimeInTransaction, } from "./session-realtime"; import { insertConnectedMachineSessionBackgroundCommandInTransaction, backgroundCommandResultOutputInTransaction, boundedSessionBackgroundCommandReason, insertManagedSessionBackgroundCommandInTransaction, settleClaimedConnectedMachineBackgroundCommandWithMutation, settleConnectedMachineSessionBackgroundCommandWithMutation, settleSessionBackgroundCommandForRetainedProcessInTransaction, unobservableRetainedProcessOutcomeSql, UNREACHABLE_MACHINE_STOP_REQUESTER, type ConnectedMachineBackgroundCommandClaim, type ConnectedMachineBackgroundCommandProof, type ConnectedCommandOutputReceipt, getSessionBackgroundCommand, recordConnectedMachineBackgroundCommandProof, recordConnectedCommandOutputConsumption, } from "./session-background-commands"; import { isSessionRealtimeDelegationTurnMetadata, projectSessionRealtimeDelegationProgressInTransaction, projectSessionRealtimeDelegationTerminalInTransaction, } from "./session-realtime-ledger"; import { mirrorSessionRealtimeContextInTransaction, renderRealtimeHumanInputRequestContext, renderRealtimeHumanInputResponseContext, } from "./session-realtime-mirror"; import { listSessionRealtimeContinuityEntriesInTransaction, type SessionRealtimeContinuityEntry, } from "./session-realtime-context"; import * as schema from "./schema"; import { boundedChildProgressNote, buildChildRequiresActionPayload, childLifecycleNoticesEnabled, childProgressDedupeKey, childProgressSummary, childRequiresActionDedupeKey, childRequiresActionResolvedDedupeKey, childRequiresActionResolvedSummary, childRequiresActionSummary, childWaitingCapacityDedupeKey, childWaitingCapacitySummary, humanInputQuestionIsPersonOnly, } from "./child-lifecycle-notices"; import { CAPACITY_WAIT_NOTICE_KEY, CAPACITY_WAIT_PARENT_NOTICE_KEY, capacityWaitAttention, capacityWaitNoticeMarker, capacityWaitNoticeNeedsRestating, capacityWaitNoticeWithdrawal, capacityWaitNotificationPayload, readCapacityWaitNotice, subscriptionCapacityWaitNeedsAction, subscriptionCapacityWaitReasonText, withoutCapacityWaitNotice, } from "./capacity-wait-attention"; import { codeSearchDeploymentPolicyForCreate } from "./code-search-policy"; import { resolveSessionCodeSearchEnabled, type CodeSearchDeploymentPolicy, } from "@opengeni/contracts/code-search"; import { autoResumeGoalPausedByCapInTransaction, SESSION_GOAL_CAP_PAUSED_REASON, SESSION_GOAL_CONTINUATION_EPOCH_RESET, SESSION_GOAL_SUPPRESSION_CLEARED, type SessionGoalAutoResumedByExternalInput, } from "./session-goal-pacing"; type SessionEventInsertWithPayload = typeof schema.sessionEvents.$inferInsert & { payload: unknown; }; import { AGENT_VISIBLE_MEMORY_STATUSES, hashMemoryText, isMemoryTextTooLong, MEMORY_VISIBLE_RECORD_CAP, MEMORY_BLOCK_RECORD_LIMIT, MEMORY_TEXT_MAX_CHARS, MEMORY_NEAR_DUP_COSINE_THRESHOLD, MEMORY_NEAR_DUP_NEIGHBORS, MEMORY_SEARCH_DEFAULT_LIMIT, MEMORY_SEARCH_MAX_LIMIT, normalizeMemoryText, renderWorkspaceMemoryBlock, memoryTextForStorage, WORKSPACE_MEMORY_BLOCK_EMPTY, memoryReadScopesForAgentScope, memoryWriteScopeForAgentScope, normalizeMemoryScope, type MemoryAgentScope, type MemoryBlockRecord, type MemoryScopeSpec, } from "./memory-domain"; export { sql as dbSql } from "drizzle-orm"; export * from "./child-lifecycle-notices"; export * from "./child-terminal-wake-repair"; export type { QuiescenceReceiptWakeRepairCursor } from "./quiescence-receipt-wake-repair"; export { QUIESCENCE_REPAIR_CLOSE_GRACE_SECONDS, QUIESCENCE_REPAIR_WAKE_QUIET_SECONDS, } from "./quiescence-receipt-wake-repair"; import { repairMissingQuiescenceReceiptWakesWith, type QuiescenceReceiptWakeRepairCursor, } from "./quiescence-receipt-wake-repair"; export * from "./maintenance-work-probes"; export { configureCodeSearchDeploymentPolicy } from "./code-search-policy"; export * from "./session-control"; import { createArchivedSessionImportPersistence } from "./archived-session-imports"; export { ArchivedSessionImportError, assertSessionIsNotImported, canonicalArchivedSessionImportHash, archivedSessionImportFileIds, getArchivedSessionImportId, type ArchivedSessionImportErrorCode, } from "./archived-session-imports"; export const { importArchivedSession, appendArchivedSessionEvents } = createArchivedSessionImportPersistence({ createSessionWithIdempotencyKeyResult, getFilesForSubject, getSession, getWorkspaceGrant, isCreateConflict: (error) => error instanceof SessionCreateIdempotencyConflictError, isCreateUnavailable: (error) => error instanceof SessionCreateIdempotencyUnavailableError, }); export * from "./session-model-settings"; export * from "./capacity-wait-attention"; export * from "./capacity-wait-release"; export * from "./session-queue-commands"; export { WAITED_FOR_MACHINE_OWNER_MODEL_CONTEXT } from "./machine-owner-wait"; export * from "./session-realtime"; export * from "./session-realtime-context"; export * from "./session-realtime-ledger"; export * from "./session-realtime-billing"; export * from "./new-session-drafts"; export * from "./workspace-instruction-policies"; export * from "./company-profile"; export * from "./company-profile-agent-policy"; export * from "./company-profile-agent-admin"; export * from "./workspace-learning-policy"; export * from "./usage-allowances"; export * from "./governed-learning-evaluator"; export * from "./slack-task-policy"; export * from "./preference-registry"; export * from "./skills"; export * from "./organization-shared-workspaces"; export * from "./learning-refusals"; export * from "./session-tool-results"; export type { SkillSourceReleaseReceipt } from "./skill-source-release"; export { SkillSourceRemovalAuthorityError } from "./skill-source-release"; export * from "./memory-governance"; export * from "./memory-slack-delivery"; export * from "./scoped-knowledge"; export * from "./company-brain"; export * from "./company-brain-governed-writes"; export * from "./company-brain-context-selection"; export * from "./task-notes"; export * from "./session-share-links"; export * from "./work-claims"; export * from "./managed-human-provisioning"; export * from "./managed-user-setup"; export * from "./signup-network"; export * from "./verified-signup-trial-switch"; export * from "./managed-auth-new-signups-switch"; export * from "./nango-integrations"; export * from "./organization-membership-backfill"; export * from "./connection-tenancy-backfill"; export * from "./generated-images"; export * from "./model-call-credit-holds"; export * from "./slack-user-link-access"; export * from "./slack-routing"; export * from "./slack-routing-personal-workspace"; import { probeSlackInteractionTenancy } from "./slack-routing"; import { namedSubjectPersonalWorkspaceId } from "./slack-routing-personal-workspace"; export * from "./workspace-membership-permissions"; export * from "./video-generation"; export * from "./session-title-operations"; export * from "./user-resource-authority"; import { acceptTurnPersonalResourceAttachmentInTransaction } from "./user-resource-authority"; export * from "./connection-authority"; export { interruptedToolCallResult } from "./session-tool-call-settlement"; export { decryptEnvironmentValue, encryptEnvironmentValue } from "./environment-crypto"; export { loadIntegrationOAuthPendingState, storeIntegrationOAuthPendingState, consumeIntegrationOAuthPendingState, } from "./integration-oauth-pending-states"; export * from "./workspace-integrations"; export * from "./native-push"; export * from "./agent-calls"; export * from "./inbox"; export * from "./vaults"; export * from "./persistence-errors"; export * from "./runtime-posture"; export * from "./capability-integrations"; export * from "./integration-bindings"; import { IntegrationChangeRequiresAdminError } from "./integration-bindings"; export * from "./integration-facets"; export * from "./insights"; export * from "./insights-model-bundle"; export * from "./insights-usage-bundle"; export * from "./insights-unified"; export * from "./sandbox-viewer-only-drain"; export * from "./sandbox-fleet-limits"; import { lockSandboxUnpaidFleet, sandboxUnpaidFleetAvailable, readSandboxFleetPressure, readSandboxUnpaidFleet, readSandboxUnpaidFleetBoxSecondsToday, type SandboxFleetPressure, type SandboxUnpaidFleetCounts, } from "./sandbox-fleet-limits"; import { VIEWER_ONLY_OPEN_SESSION_STATUSES } from "./sandbox-viewer-only-drain"; export * from "./organization-membership-lifecycle"; import { assertActiveManagedHumanOrganizationMembership, getOrganizationAdministrationOverview, } from "./organization-membership-lifecycle"; // Deliberately NOT `export *`: `accountIdInRlsScope` is an internal convenience // for seams already inside an RLS scope, and publishing it would put a helper // that trivially satisfies the in-scope resolver's consistency check on the // public surface of a non-private package. export { rlsSubjectIdOrEmpty, subjectHasLiveWorkspaceAuthorityInScope, } from "./workspace-authority"; import { accountIdInRlsScope, rlsSubjectIdOrEmpty, subjectHasLiveWorkspaceAuthorityInScope, } from "./workspace-authority"; import { managedPersonalWorkspacePermissions } from "./personal-workspace-permissions"; import { joinedWorkspaceIsNotPersonal, membershipOutsidePersonalWorkspace, } from "./personal-workspace-membership"; export { PERSONAL_WORKSPACE_EXTERNAL_SOURCE } from "./personal-workspace-membership"; export { memoryTextForStorage } from "./memory-domain"; // Re-exported so external consumers can `import { migrate } from "@opengeni/db"`. // The `@opengeni/db/migrate` subpath stays available too (internal callers + the // db:migrate script use it). Re-exporting does NOT run migrate.ts's // `import.meta.main` block — that only fires when migrate.ts is the entry. export { migrate, runMigrations } from "./migrate"; // Step I SDK entry points for the embedded topology: a host drives migration + // role provisioning over an explicit admin connection + target schema. Importing // these does NOT run the modules' `import.meta.main` CLI blocks. export { provisionRoles, type ProvisionResult, type ProvisionRolesOptions, } from "./provision-roles"; // Workspace Memory V1 pure domain surface (gates, render, canonical prompt text). export * from "./memory-domain"; export * from "./model-catalog"; export * from "./billing-subscription-operations"; import { dbBindingFor, isTransactionHandle, rawRows, retryRlsPersistence, retryWorkspacePersistence, retrySessionActivityRls, rlsContextForWorkspace, setRlsContext, setSubjectRlsContext, withAccountRls, withDatabaseQueryCancellation, withRlsContext, withRestoredSessionActivityRlsContext, withSessionActivityRlsContext, withSessionActivitySavepoint, withSessionRlsActorContext, withWorkspaceRls, withWorkspaceSessionActivityRls, withWorkspaceSubjectRls, withWorkspaceSubjectSessionActivityRls, withWorkspaceUsageLock, WorkspaceNotFoundError, type Database, type SessionActivityDatabase, } from "./database"; export { createDb, sessionListChangesFor, databasePoolOptions, databaseReconnectBackoffSeconds, DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS, DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS, MAX_DATABASE_POOL_TIMER_SECONDS, defaultDatabasePreparedStatements, isTransactionHandle, registerDbBinding, retrySessionActivityRls, rlsContextForWorkspace, rlsStrategyFor, setRlsContext, setSubjectRlsContext, withAccountRls, withDatabaseQueryCancellation, 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"; export { currentSessionRlsActorIdentityKey, currentSessionRlsActorContext, currentSiteViewerRlsContext, withSiteViewerRlsContext, currentSessionRlsActorInitiatingHumanSubjectId, withSessionRlsActorContext, } from "./database"; export { withDatabaseTimingObserver, type DatabaseTimingObservation } from "./database-timing"; export { DATABASE_AUTHENTICATION_FAILURE_SQLSTATE, DATABASE_AUTHENTICATION_MAX_ATTEMPTS, DATABASE_CREDENTIAL_LOG_INTERVAL_MS, DATABASE_CREDENTIAL_METRICS, DATABASE_CREDENTIAL_STALE_FAILURE_GRACE_MS, DATABASE_LOGIN_ATTEMPT, databaseCredentialEventAttributes, databaseCredentialEventMessage, databaseLoginAttemptOf, databasePasswordFileOptions, databasePasswordFileOptionsFromEnvironment, rotatingDatabasePasswordFor, databaseUrlPassword, databaseUrlUser, isDatabaseAuthenticationFailure, logDatabaseCredentialEvent, observeDatabaseCredentialEvents, RotatingDatabasePassword, tagDatabaseLoginAttempt, withDatabaseAuthenticationRetry, type DatabaseAuthenticationRefusal, type DatabaseCredentialEvent, type DatabaseCredentialEventListener, type DatabaseCredentialExhaustion, type DatabaseCredentialObserver, type DatabaseCredentialPosition, type DatabasePasswordFiles, type RotatingDatabasePasswordOptions, } from "./database-credentials"; export type { SessionListChangeSource, SessionListDatabaseChange, SessionListNotification, } from "./session-list-notifications"; export { notifyActorDraftChanged } from "./session-list-notifications"; export { BROKERED_CREDENTIAL_SHAPE_HINT, brokeredCredentialBundleProblem, normalizedCredentialHeaders, } from "./connection-token-resolver"; import { type CodexAuthDeps } from "./codex-token-resolver"; import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, refreshOAuthConnectionCredential as refreshOAuthConnectionCredentialCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions, } from "./connection-token-resolver"; import { resolveAcceptedConnectionUse } from "./connection-authority"; function parsedPersonalConnectionDelegations( value: unknown, context: string, ): McpPersonalConnectionDelegation[] { const parsed = McpPersonalConnectionDelegations.safeParse(value); if (!parsed.success) { throw new Error(`Invalid personal MCP delegation snapshot at ${context}`); } return parsed.data.map((delegation) => ({ ...delegation })); } /** A resolver offered a compaction turn a personal account its person may not lend. */ class CompactionConnectionAccountRefusal extends Error { constructor() { super("Personal connection owner does not match the compacted turn's person"); this.name = "CompactionConnectionAccountRefusal"; } } /** * Why a compaction turn runs without connection accounts, for the worker to * report. Only the error's class and SQLSTATE are kept, never its message. */ function unresolvedConnectionAccountsRecord( error: unknown, failure: "resolution_failed" | "acceptance_refused" = "resolution_failed", ): { reason: "owner_mismatch" | "resolution_failed" | "acceptance_refused"; errorName?: string; sqlState?: string; } { if (error instanceof CompactionConnectionAccountRefusal) return { reason: "owner_mismatch" }; const errorName = error instanceof Error && /^[A-Za-z0-9_$]{1,64}$/.test(error.name) ? error.name : undefined; const sqlState = nestedPostgresSqlState(error) ?? undefined; return { reason: failure, ...(errorName ? { errorName } : {}), ...(sqlState ? { sqlState } : {}), }; } /** * Whether accepted work runs under a credential restriction (for example * developer setup). Work continuing it may not borrow its connection * authority. Unreadable policy counts as restricted. */ function carriesCredentialRestriction(initiatorContext: unknown, metadata: unknown): boolean { if ( initiatorContext && typeof initiatorContext === "object" && Object.prototype.hasOwnProperty.call(initiatorContext, "credentialRestriction") ) { return true; } try { const policy = readTurnExecutionPolicyV1(metadata); return policy.kind === "valid" && policy.policy.credentialRestriction !== undefined; } catch { return true; } } /** Raised when a durable session tool-policy write lost its version fence. */ export class SessionToolPolicyVersionConflictError extends Error { readonly code = "SESSION_TOOL_POLICY_CONFLICT"; constructor(readonly currentVersion: number) { super("The session tool policy changed in another client"); this.name = "SessionToolPolicyVersionConflictError"; } } export type NestedAgentDepthPolicySource = "session" | "workspace" | "deployment" | "default"; export type SessionDepthPolicy = { rootSessionId: string; nestedAgentDepth: number; maxNestedAgentDepthOverride: number | null; effectiveMaxNestedAgentDepth: number; nestedAgentDepthPolicySource: NestedAgentDepthPolicySource; nestedAgentDepthPolicySessionId: string | null; }; export type SessionSpawnDenialCode = | "nested_agent_depth_exceeded" | "nested_agent_depth_override_forbidden"; export type SessionSpawnDenial = { id: string; accountId: string; workspaceId: string; parentSessionId: string | null; rootSessionId: string | null; currentDepth: number; attemptedDepth: number; effectiveMaxNestedAgentDepth: number; requestedMaxNestedAgentDepthOverride: number | null; policySource: NestedAgentDepthPolicySource; policySessionId: string | null; subjectId: string | null; code: SessionSpawnDenialCode; idempotencyKey: string | null; createdAt: string; }; export type NestedAgentDepthDeploymentPolicy = { maxNestedAgentDepth: number; policySource: "deployment" | "default"; }; export type DbSession = Session & SessionDepthPolicy; export type SessionCreateSuccessResult = { denied: false; session: DbSession; created: boolean; }; export type SessionCreateDeniedResult = { denied: true; created: false; denial: SessionSpawnDenial; }; export type SessionCreateResult = SessionCreateSuccessResult | SessionCreateDeniedResult; /** Thrown only after a denied create transaction has committed its evidence. */ export class SessionSpawnDeniedDbError extends Error { constructor(readonly denial: SessionSpawnDenial) { super(denial.code); this.name = "SessionSpawnDeniedDbError"; } } // --------------------------------------------------------------------------- // Durable host export // --------------------------------------------------------------------------- export type HostExportKind = "session_event" | "usage_event" | "lifecycle_fact"; /** * A leased row did not satisfy this consumer build's export contract. Only * bounded schema diagnostics are retained here; the source payload is never * copied into the error. The lease can therefore be failed visibly, or an * operator can re-claim it with a known token and explicitly dead-letter the * reported head cursor. */ export class HostExportPayloadError extends Error { override readonly name = "HostExportPayloadError"; constructor( readonly kind: HostExportKind, readonly consumerId: string, readonly leaseToken: string, readonly cursor: string, readonly schemaIssues: string[], ) { super( `Host export ${kind} cursor ${cursor} failed schema validation: ${schemaIssues.join("; ")}`, ); } } export type HostExportConsumerStatus = { exportKind: HostExportKind; consumerId: string; checkpoint: string; enabled: boolean; consecutiveFailures: number; nextAttemptAt: string; lastError: string | null; lastErrorAt: string | null; blockedAt: string | null; leaseExpiresAt: string | null; maxCursor: string; pendingCount: string; unassignedCount: string; prunedThrough: string; }; type HostExportRow = { consumer_id: string; export_kind: HostExportKind; checkpoint: string | number | bigint; lease_token: string; lease_through: string | number | bigint; export_cursor: string | number | bigint; source_id: string; // Null only for lifecycle facts (person-level, or organization-level facts). account_id: string | null; workspace_id: string | null; session_id: string | null; root_session_id: string | null; turn_id: string | null; turn_generation: number | null; turn_attempt_id: string | null; session_sequence: number | null; client_event_id: string | null; turn_association: string | null; duplicate_of_event_id: string | null; duplicate_reason: string | null; event_type: string; idempotency_key: string; initiator: unknown; initiator_context: unknown; origin: string | null; surface: string | null; model_provider: string | null; tool_family: string | null; payload: unknown; payload_codec_version: number | null; occurred_at: Date | string; source_recorded_at: Date | string; }; type HostExportClaimRow = Omit< HostExportRow, "root_session_id" | "payload_codec_version" | "surface" | "model_provider" | "tool_family" >; type HostExportClaimSidecarRow = { export_cursor: string | number | bigint; root_session_id: string | null; payload_codec_version: number | null; }; type HostExportClaimAnalyticsSidecarRow = { export_cursor: string | number | bigint; surface: string | null; model_provider: string | null; tool_family: string | null; }; function hostExportCursor(value: string | number | bigint): string { return BigInt(value).toString(); } function hostExportTimestamp(value: Date | string): string { return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); } function validateHostExportKind(kind: HostExportKind): void { if (kind !== "session_event" && kind !== "usage_event" && kind !== "lifecycle_fact") { throw new Error(`Unknown host export kind: ${kind}`); } } function validateHostExportIdentity(kind: HostExportKind, consumerId: string): void { validateHostExportKind(kind); HostExportConsumerId.parse(consumerId); } /** * Enable a named consumer. This call deliberately requires a database handle * authenticated as the separately provisioned host-export role; the ordinary * tenant-scoped app role cannot execute this cross-workspace API. */ export async function registerHostExportConsumer( db: Database, input: { kind: HostExportKind; consumerId: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); await db.execute(sql` select opengeni_host_export.register_host_export_consumer( ${input.kind}, ${input.consumerId} ) `); } export async function disableHostExportConsumer( db: Database, input: { kind: HostExportKind; consumerId: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); await db.execute(sql` select opengeni_host_export.disable_host_export_consumer( ${input.kind}, ${input.consumerId} ) `); } /** * Permanently remove a quiesced consumer and release its retention floor. * Unlike disable, re-registering this name later starts at the retained floor. */ export async function retireHostExportConsumer( db: Database, input: { kind: HostExportKind; consumerId: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); await db.execute(sql` select opengeni_host_export.retire_host_export_consumer( ${input.kind}, ${input.consumerId} ) `); } export async function claimHostExportBatch( db: Database, input: { kind: "session_event"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }, ): Promise; export async function claimHostExportBatch( db: Database, input: { kind: "usage_event"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }, ): Promise; export async function claimHostExportBatch( db: Database, input: { kind: "lifecycle_fact"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }, ): Promise; export async function claimHostExportBatch( db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }, ): Promise; export async function claimHostExportBatch( db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const rows = await db.transaction(async (tx) => { const transaction = tx as unknown as Database; const claimedRows = await rawRows( transaction, sql` select * from opengeni_host_export.claim_host_export_batch( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid, ${input.leaseHolderId}, ${input.leaseSeconds ?? 60}, ${input.limit ?? 100}, ${input.maxBytes ?? 1_048_576} ) `, ); if (claimedRows.length === 0) return null; const claimedFirst = claimedRows[0]!; if ( claimedRows.some( (row) => row.consumer_id !== claimedFirst.consumer_id || row.export_kind !== claimedFirst.export_kind || row.lease_token !== claimedFirst.lease_token || hostExportCursor(row.checkpoint) !== hostExportCursor(claimedFirst.checkpoint) || hostExportCursor(row.lease_through) !== hostExportCursor(claimedFirst.lease_through), ) ) { throw new Error("Host export claim returned inconsistent batch metadata"); } const sidecars = await rawRows( transaction, sql` select * from opengeni_host_export.host_export_claim_sidecars( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid ) `, ); const sidecarByExportCursor = new Map( sidecars.map((row) => [hostExportCursor(row.export_cursor), row]), ); const analyticsSidecars = await rawRows( transaction, sql` select * from opengeni_host_export.host_export_claim_analytics_sidecars( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid ) `, ); const analyticsByExportCursor = new Map( analyticsSidecars.map((row) => [hostExportCursor(row.export_cursor), row]), ); const materializedRows = claimedRows.map((row): HostExportRow => { const cursor = hostExportCursor(row.export_cursor); const sidecar = sidecarByExportCursor.get(cursor); if (!sidecar) { throw new Error(`Host export sidecar lookup omitted leased cursor ${cursor}`); } const analytics = analyticsByExportCursor.get(cursor); if (!analytics) { throw new Error(`Host export analytics sidecar lookup omitted leased cursor ${cursor}`); } return { ...row, root_session_id: sidecar.root_session_id, payload_codec_version: sidecar.payload_codec_version, surface: analytics.surface, model_provider: analytics.model_provider, tool_family: analytics.tool_family, }; }); return materializedRows; }); if (!rows) return null; const first = rows[0]!; if (input.kind === "session_event") { const events = rows.map((row): HostEventExport => { const parsed = HostEventExportContract.safeParse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, cursor: hostExportCursor(row.export_cursor), idempotencyKey: row.idempotency_key, accountId: row.account_id, workspaceId: row.workspace_id, rootSessionId: row.root_session_id, initiator: row.initiator, initiatorContext: row.initiator_context, origin: row.origin, surface: row.surface, modelProvider: row.model_provider, toolFamily: row.tool_family, event: { id: row.source_id, workspaceId: row.workspace_id, sessionId: row.session_id, sequence: row.session_sequence, type: row.event_type, payload: fromPostgresLosslessJson(row.payload, row.payload_codec_version), occurredAt: hostExportTimestamp(row.occurred_at), clientEventId: row.client_event_id, turnId: row.turn_id, turnGeneration: row.turn_generation, turnAttemptId: row.turn_attempt_id, turnAssociation: row.turn_association, duplicateOfEventId: row.duplicate_of_event_id, duplicateReason: row.duplicate_reason, }, }); if (!parsed.success) { throw hostExportPayloadError(input, row, parsed.error.issues); } return parsed.data; }); return HostEventExportBatchContract.parse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, consumerId: first.consumer_id, leaseToken: first.lease_token, checkpoint: hostExportCursor(first.checkpoint), throughCursor: hostExportCursor(first.lease_through), events, }); } if (input.kind === "lifecycle_fact") { const facts = rows.map((row): HostLifecycleFactExport => { const payload = row.payload && typeof row.payload === "object" && !Array.isArray(row.payload) ? (row.payload as Record) : {}; const initiator = row.initiator && typeof row.initiator === "object" && !Array.isArray(row.initiator) ? (row.initiator as Record) : null; const parsed = HostLifecycleFactExportContract.safeParse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, cursor: hostExportCursor(row.export_cursor), idempotencyKey: row.idempotency_key, accountId: row.account_id, workspaceId: row.workspace_id, fact: { id: row.source_id, type: row.event_type, attribute: payload.attribute ?? null, subjectKind: payload.subjectKind, subjectId: initiator?.subjectId ?? null, occurredAt: hostExportTimestamp(row.occurred_at), }, }); if (!parsed.success) { throw hostExportPayloadError(input, row, parsed.error.issues); } return parsed.data; }); return HostLifecycleFactExportBatchContract.parse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, consumerId: first.consumer_id, leaseToken: first.lease_token, checkpoint: hostExportCursor(first.checkpoint), throughCursor: hostExportCursor(first.lease_through), events: facts, }); } const events = rows.map((row): HostUsageExport => { const parsed = HostUsageExportContract.safeParse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, cursor: hostExportCursor(row.export_cursor), accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, rootSessionId: row.root_session_id, turnId: row.turn_id, turnAttemptId: row.turn_attempt_id, initiator: row.initiator, initiatorContext: row.initiator_context, origin: row.origin, surface: row.surface, modelProvider: row.model_provider, usage: row.payload, }); if (!parsed.success) { throw hostExportPayloadError(input, row, parsed.error.issues); } return parsed.data; }); return HostUsageExportBatchContract.parse({ schemaRevision: OPENGENI_HOST_EXPORT_SCHEMA_REVISION, consumerId: first.consumer_id, leaseToken: first.lease_token, checkpoint: hostExportCursor(first.checkpoint), throughCursor: hostExportCursor(first.lease_through), events, }); } function hostExportPayloadError( input: { kind: HostExportKind; consumerId: string; leaseToken: string }, row: HostExportRow, issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>, ): HostExportPayloadError { const schemaIssues = issues.slice(0, 8).map((issue) => { const path = issue.path.map(String).join(".") || "envelope"; return `${path}: ${issue.message}`.slice(0, 240); }); return new HostExportPayloadError( input.kind, input.consumerId, input.leaseToken, hostExportCursor(row.export_cursor), schemaIssues.length > 0 ? schemaIssues : ["invalid envelope"], ); } export async function acknowledgeHostExportBatch( db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const [row] = await rawRows<{ checkpoint: string | number | bigint }>( db, sql` select opengeni_host_export.ack_host_export_batch( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid ) as checkpoint `, ); if (!row) throw new Error("Host export acknowledgement returned no checkpoint"); return hostExportCursor(row.checkpoint); } export async function failHostExportBatch( db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; error: string; maxFailures?: number; }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const [row] = await rawRows<{ failures: number }>( db, sql` select opengeni_host_export.fail_host_export_batch( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid, ${toPostgresLosslessText(input.error)}, ${input.maxFailures ?? 20}, ${LOSSLESS_CONTENT_CODEC_VERSION} ) as failures `, ); if (!row) throw new Error("Host export failure settlement returned no result"); return Number(row.failures); } export async function deadLetterHostExportHead( db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; cursor: string; reason: string; }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const cursor = hostExportCursor(input.cursor); const [row] = await rawRows<{ checkpoint: string | number | bigint }>( db, sql` select opengeni_host_export.dead_letter_host_export_head( ${input.kind}, ${input.consumerId}, ${input.leaseToken}::uuid, ${cursor}::bigint, ${input.reason} ) as checkpoint `, ); if (!row) throw new Error("Host export dead-letter settlement returned no checkpoint"); return hostExportCursor(row.checkpoint); } export async function resumeHostExportConsumer( db: Database, input: { kind: HostExportKind; consumerId: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); await db.execute(sql` select opengeni_host_export.resume_host_export_consumer( ${input.kind}, ${input.consumerId} ) `); } export async function rewindHostExportConsumer( db: Database, input: { kind: HostExportKind; consumerId: string; checkpoint: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const checkpoint = hostExportCursor(input.checkpoint); await db.execute(sql` select opengeni_host_export.rewind_host_export_consumer( ${input.kind}, ${input.consumerId}, ${checkpoint}::bigint ) `); } export async function pruneHostExportOutbox( db: Database, input: { kind: HostExportKind; graceSeconds?: number; limit?: number }, ): Promise { validateHostExportKind(input.kind); const [row] = await rawRows<{ deleted: number }>( db, sql` select opengeni_host_export.prune_host_export_outbox( ${input.kind}, ${input.graceSeconds ?? 3600}, ${input.limit ?? 1000} ) as deleted `, ); return Number(row?.deleted ?? 0); } export async function getHostExportConsumerStatus( db: Database, input: { kind: HostExportKind; consumerId: string }, ): Promise { validateHostExportIdentity(input.kind, input.consumerId); const [row] = await rawRows<{ export_kind: HostExportKind; consumer_id: string; checkpoint: string | number | bigint; enabled: boolean; consecutive_failures: number; next_attempt_at: Date | string; last_error: string | null; last_error_codec_version: number | null; last_error_at: Date | string | null; blocked_at: Date | string | null; lease_expires_at: Date | string | null; max_cursor: string | number | bigint; pending_count: string | number | bigint; unassigned_count: string | number | bigint; pruned_through: string | number | bigint; }>( db, sql` select status.*, sidecar.last_error_codec_version from opengeni_host_export.host_export_consumer_status( ${input.kind}, ${input.consumerId} ) status left join lateral opengeni_host_export.host_export_consumer_status_sidecar( ${input.kind}, ${input.consumerId} ) sidecar on true `, ); if (!row) return null; const optionalTimestamp = (value: Date | string | null): string | null => value === null ? null : hostExportTimestamp(value); return { exportKind: row.export_kind, consumerId: row.consumer_id, checkpoint: hostExportCursor(row.checkpoint), enabled: row.enabled, consecutiveFailures: Number(row.consecutive_failures), nextAttemptAt: hostExportTimestamp(row.next_attempt_at), lastError: row.last_error === null ? null : fromPostgresLosslessText(row.last_error, row.last_error_codec_version), lastErrorAt: optionalTimestamp(row.last_error_at), blockedAt: optionalTimestamp(row.blocked_at), leaseExpiresAt: optionalTimestamp(row.lease_expires_at), maxCursor: hostExportCursor(row.max_cursor), pendingCount: hostExportCursor(row.pending_count), unassignedCount: hostExportCursor(row.unassigned_count), prunedThrough: hostExportCursor(row.pruned_through), }; } export type DocumentIndexAuthority = { authorityKind: DocumentAuthorityKind; authorityWorkspaceId: string | null; authoritySubjectId: string | null; }; /** * Read the immutable authority tuple used by document indexing compatibility. * The database capability returns no document content and independently * verifies that this transaction already carries the exact account/workspace * RLS context. It is intentionally subject-free so a historical three-field * Temporal payload can recover a personal document's frozen subject without * weakening ordinary document visibility. */ export async function resolveDocumentIndexAuthority( db: Database, input: { accountId: string; workspaceId: string; documentId: string }, ): Promise { const rows = await rawRows<{ authority_kind: string; authority_workspace_id: string | null; authority_subject_id: string | null; }>( db, sql` select authority_kind, authority_workspace_id, authority_subject_id from opengeni_private.resolve_document_index_authority( ${input.accountId}, ${input.workspaceId}, ${input.documentId} ) `, ); const row = rows[0]; if (!row) return null; if ( row.authority_kind !== "organization" && row.authority_kind !== "workspace" && row.authority_kind !== "personal" ) { throw new Error(`Stored document authority kind is invalid: ${row.authority_kind}`); } return { authorityKind: row.authority_kind, authorityWorkspaceId: row.authority_workspace_id, authoritySubjectId: row.authority_subject_id, }; } /** A Workspace owner's permissions; shared with the API key creator rule. */ export const allWorkspacePermissions: Permission[] = [...WORKSPACE_OWNER_PERMISSIONS]; export { managedPersonalWorkspacePermissions }; /** * Resolve the synthetic personal-workspace grant for a subject whose human * identity was authenticated out of band (for example, in HMAC-signed OAuth * state). This is intentionally narrower than ordinary access resolution: * the requested workspace must still be the subject's current personal * workspace pointer and its organization membership must remain active. */ export async function resolveNamedManagedPersonalWorkspaceGrant( db: Database, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { const personalWorkspaceId = await namedSubjectPersonalWorkspaceId(db, { accountId: input.accountId, subjectId: input.subjectId, }); if (personalWorkspaceId !== input.workspaceId) return null; const live = await namedSubjectHasLiveWorkspaceAuthority(db, input); if (!live) return null; return { workspaceId: input.workspaceId, accountId: input.accountId, subjectId: input.subjectId, permissions: managedPersonalWorkspacePermissions, principalKind: "human_session", }; } /** * Whether this turn's app actions can change the workspace's settings right * now: the turn may make changes (full access, or each change confirmed by the * person who sent it), its access includes workspace:admin, and the person it * acts as still holds the grant the settings routes accept (workspace:admin * here, or ownership of this Personal workspace). The route still decides. */ export async function turnCanChangeWorkspaceSettings( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string }, ): Promise { return (await turnWorkspaceSettingsAccess(db, input)) !== null; } /** * How this turn's app actions can change the workspace's settings: "confirm" * when each change waits for the person's yes in the chat, "full_access" when * changes run straight away, or null when they can't change them. */ export async function turnWorkspaceSettingsAccess( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string }, ): Promise<"confirm" | "full_access" | null> { const authority = await resolveSessionAppActionAuthority(db, input); if (authority.kind === "unavailable" || authority.kind === "read_only") return null; if (authority.kind === "confirm" && !authority.permissions.includes("workspace:admin")) { return null; } const { subjectId } = authority; const allowed = await withWorkspaceSubjectRls(db, input.workspaceId, subjectId, async (tx) => { const membership = await getWorkspaceGrant(tx, subjectId, input.workspaceId); if (membership?.accountId === input.accountId) { return membership.permissions.includes("workspace:admin"); } return ( subjectId.startsWith("user:") && (await resolveNamedManagedPersonalWorkspaceGrant(tx, { ...input, subjectId })) !== null ); }); return allowed ? authority.kind : null; } export { allAccountPermissions } from "./organization-role-permissions"; export type BootstrapWorkspaceInput = { accountExternalSource: string; accountExternalId: string; accountName: string; workspaceExternalSource: string; workspaceExternalId: string; workspaceName: string; subjectId: string; subjectLabel?: string; accountPermissions?: Permission[]; workspacePermissions?: Permission[]; }; function samePermissionSet(left: unknown, right: readonly Permission[]): boolean { if (!Array.isArray(left) || left.length !== right.length) return false; const normalized = normalizeWorkspaceMembershipPermissions(left); return ( normalized.length === left.length && right.every((permission) => normalized.includes(permission)) ); } export async function bootstrapWorkspace( db: Database, input: BootstrapWorkspaceInput, ): Promise { return await db.transaction(async (tx) => { let [account] = await tx .select() .from(schema.managedAccounts) .where( and( eq(schema.managedAccounts.externalSource, input.accountExternalSource), eq(schema.managedAccounts.externalId, input.accountExternalId), ), ) .limit(1); if (!account) { [account] = await tx .insert(schema.managedAccounts) .values({ name: input.accountName, externalSource: input.accountExternalSource, externalId: input.accountExternalId, }) .onConflictDoUpdate({ target: [schema.managedAccounts.externalSource, schema.managedAccounts.externalId], set: { name: input.accountName, updatedAt: new Date(), }, }) .returning(); } else if (account.name !== input.accountName) { [account] = await tx .update(schema.managedAccounts) .set({ name: input.accountName, updatedAt: new Date() }) .where(eq(schema.managedAccounts.id, account.id)) .returning(); } if (!account) { throw new Error("Failed to bootstrap account"); } let [workspace] = await tx .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.externalSource, input.workspaceExternalSource), eq(schema.workspaces.externalId, input.workspaceExternalId), eq(schema.workspaces.accountId, account.id), ), ) .limit(1); if (!workspace) { [workspace] = await tx .insert(schema.workspaces) .values({ accountId: account.id, name: input.workspaceName, externalSource: input.workspaceExternalSource, externalId: input.workspaceExternalId, }) .onConflictDoUpdate({ target: [ schema.workspaces.accountId, schema.workspaces.externalSource, schema.workspaces.externalId, ], set: { name: input.workspaceName, updatedAt: new Date(), }, }) .returning(); } else if (workspace.name !== input.workspaceName) { [workspace] = await tx .update(schema.workspaces) .set({ name: input.workspaceName, updatedAt: new Date() }) .where(eq(schema.workspaces.id, workspace.id)) .returning(); } if (!workspace) { throw new Error("Failed to bootstrap workspace"); } await setRlsContext(tx as unknown as Database, { accountId: workspace.accountId, workspaceId: workspace.id, }); const [workspaceControl] = await tx .select({ workspaceId: schema.workspaceInferenceControls.workspaceId }) .from(schema.workspaceInferenceControls) .where(eq(schema.workspaceInferenceControls.workspaceId, workspace.id)) .limit(1); if (!workspaceControl) { await tx .insert(schema.workspaceInferenceControls) .values({ workspaceId: workspace.id, accountId: workspace.accountId }) .onConflictDoNothing(); } const workspacePermissions = input.workspacePermissions ?? allWorkspacePermissions; const [membership] = await tx .select() .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, workspace.id), eq(schema.workspaceMemberships.subjectId, input.subjectId), ), ) .limit(1); const subjectLabel = input.subjectLabel ?? null; if (!membership) { await tx .insert(schema.workspaceMemberships) .values({ accountId: account.id, workspaceId: workspace.id, subjectId: input.subjectId, subjectLabel, role: "owner", permissions: workspacePermissions, }) .onConflictDoUpdate({ target: [schema.workspaceMemberships.subjectId, schema.workspaceMemberships.workspaceId], set: { subjectLabel, role: "owner", permissions: workspacePermissions, updatedAt: new Date(), }, }); } else if ( membership.accountId !== account.id || membership.subjectLabel !== subjectLabel || membership.role !== "owner" || !samePermissionSet(membership.permissions, workspacePermissions) ) { await tx .update(schema.workspaceMemberships) .set({ accountId: account.id, subjectLabel, role: "owner", permissions: workspacePermissions, updatedAt: new Date(), }) .where(eq(schema.workspaceMemberships.id, membership.id)); } if ( input.accountExternalSource === "opengeni:local" && input.accountExternalId === "default" && input.subjectId === "dev" ) { await setRlsContext(tx as unknown as Database, { accountId: account.id, workspaceId: null, }); await setSubjectRlsContext(tx as unknown as Database, input.subjectId); await ensureManagedHumanPersonalWorkspace(tx as unknown as Database, { accountId: account.id, subjectId: input.subjectId, }); } // Access refreshes must retain workspaces created or granted after the // default workspace. Restore account-scoped RLS before listing them. await setRlsContext(tx as unknown as Database, { accountId: workspace.accountId, workspaceId: null, }); const memberships = await tx .select({ membership: schema.workspaceMemberships, workspace: schema.workspaces, }) .from(schema.workspaceMemberships) .innerJoin( schema.workspaces, eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id), ) .where( and( eq(schema.workspaceMemberships.subjectId, input.subjectId), joinedWorkspaceIsNotPersonal(), ), ) .orderBy(desc(schema.workspaces.createdAt)); return { mode: input.accountExternalSource === "opengeni:local" ? "local" : "configured", subjectId: input.subjectId, ...(input.subjectLabel ? { subjectLabel: input.subjectLabel } : {}), accountGrants: [ { accountId: account.id, subjectId: input.subjectId, ...(input.subjectLabel ? { subjectLabel: input.subjectLabel } : {}), role: "owner", permissions: input.accountPermissions ?? allAccountPermissions, // Same shape as managed grants, so clients show the organization's // real name instead of an id fragment. metadata: { accountName: account.name }, }, ], workspaceGrants: memberships.map((row) => ({ workspaceId: row.workspace.id, accountId: row.workspace.accountId, subjectId: input.subjectId, ...(input.subjectLabel ? { subjectLabel: input.subjectLabel } : {}), permissions: normalizeWorkspaceMembershipPermissions(row.membership.permissions), ...(input.accountExternalSource === "opengeni:local" ? { principalKind: "human_session" as const } : input.accountExternalSource === "opengeni:configured" ? { principalKind: "configured_key" as const } : {}), })), defaultAccountId: account.id, defaultWorkspaceId: workspace.id, }; }); } export async function ensureManagedAccessForUser( db: Database, input: { userId: string; email: string; name: string; emailVerified?: boolean; provisionFallbackOrganization?: boolean; bindPendingInvitations?: boolean; }, ): Promise { return (await ensureManagedAccessForUserWithOrganizationMemberships(db, input)).accessContext; } export type ManagedAccessProvisioningResult = { accessContext: AccessContext; organizationMemberships: ManagedOrganizationMembershipProjection[]; }; async function projectManagedOrganizationAccess( db: Database, input: { subjectId: string; subjectLabel: string; organizationMemberships: OrganizationMemberType[]; userId: string; }, ): Promise { const activeOrganizationMemberships = input.organizationMemberships.flatMap( (organizationMembership) => organizationMembership.status === "active" && organizationMembership.personalWorkspaceId !== null ? [ { ...organizationMembership, status: "active" as const, personalWorkspaceId: organizationMembership.personalWorkspaceId, }, ] : [], ); if (activeOrganizationMemberships.length === 0) { const organizationId = input.organizationMemberships[0]?.organizationId; if (organizationId) { await setRlsContext(db, { accountId: organizationId, workspaceId: null }); await assertActiveManagedHumanOrganizationMembership(db, { accountId: organizationId, subjectId: input.subjectId, }); } throw new Error("Inactive managed organization unexpectedly passed active membership"); } const defaultAccountId = activeOrganizationMemberships[0]!.organizationId; const finalAccountId = activeOrganizationMemberships.at(-1)!.organizationId; // The authority tables below are non-RLS: every join is explicitly limited to // the subject and the active organization ids just returned by the canonical // membership helper. The default organization's account-scoped privacy row // (0918: Personal workspaces off lands people in a shared workspace) rides // in the same read under that organization's scope. await setRlsContext(db, { accountId: defaultAccountId, workspaceId: null }); const rows = await db .select({ accountId: schema.managedAccounts.id, accountName: schema.managedAccounts.name, workspaceId: schema.workspaces.id, permissions: schema.workspaceMemberships.permissions, defaultPersonalWorkspacesEnabled: sql`( select privacy.personal_workspaces_enabled from ${schema.organizationPrivacyPreferences} privacy where privacy.account_id = ${defaultAccountId}::uuid )`, preferredDefaultWorkspaceId: sql`( select legacy.id from ${schema.workspaces} legacy join ${schema.managedAccounts} fallback on fallback.id = legacy.account_id where fallback.id = ${defaultAccountId}::uuid and fallback.external_source = 'better-auth:user' and fallback.external_id = ${input.userId} and legacy.external_source = 'better-auth:user' and legacy.external_id = ${`${input.userId}:default`} limit 1 )`, }) .from(schema.managedAccounts) .leftJoin( schema.workspaceMemberships, and( eq(schema.workspaceMemberships.accountId, schema.managedAccounts.id), eq(schema.workspaceMemberships.subjectId, input.subjectId), // The Personal grant below comes from the pointer, never a row there. membershipOutsidePersonalWorkspace(), ), ) .leftJoin( schema.workspaces, and( eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id), eq(schema.workspaceMemberships.accountId, schema.workspaces.accountId), ), ) .where( inArray( schema.managedAccounts.id, activeOrganizationMemberships.map((row) => row.organizationId), ), ) .orderBy(desc(schema.workspaces.createdAt)); // Preserve the final scope of the old per-organization loop. if (finalAccountId !== defaultAccountId) { await setRlsContext(db, { accountId: finalAccountId, workspaceId: null }); } const defaultPersonalWorkspacesEnabled = rows[0]?.defaultPersonalWorkspacesEnabled ?? true; const workspaceGrants: AccessGrant[] = []; for (const organizationMembership of activeOrganizationMemberships) { workspaceGrants.push( ...rows .filter( (row) => row.accountId === organizationMembership.organizationId && row.workspaceId !== null, ) .map((row) => ({ workspaceId: row.workspaceId!, accountId: row.accountId, subjectId: input.subjectId, subjectLabel: input.subjectLabel, permissions: normalizeWorkspaceMembershipPermissions(row.permissions), principalKind: "human_session" as const, })), ); } for (const organizationMembership of activeOrganizationMemberships) { if ( !workspaceGrants.some( (grant) => grant.workspaceId === organizationMembership.personalWorkspaceId, ) ) { workspaceGrants.push({ workspaceId: organizationMembership.personalWorkspaceId, accountId: organizationMembership.organizationId, subjectId: input.subjectId, subjectLabel: input.subjectLabel, permissions: managedPersonalWorkspacePermissions, principalKind: "human_session", }); } } const organizationNameById = new Map(rows.map((row) => [row.accountId, row.accountName])); const defaultPersonalWorkspaceId = activeOrganizationMemberships[0]!.personalWorkspaceId; // Rows are newest first, so the last shared grant is the organization's oldest. const defaultSharedWorkspaceId = defaultPersonalWorkspacesEnabled ? undefined : [...workspaceGrants] .reverse() .find( (grant) => grant.accountId === defaultAccountId && grant.workspaceId !== defaultPersonalWorkspaceId, )?.workspaceId; const defaultWorkspaceId = workspaceGrants.find( (grant) => grant.accountId === defaultAccountId && grant.workspaceId === rows[0]?.preferredDefaultWorkspaceId, )?.workspaceId ?? defaultSharedWorkspaceId ?? defaultPersonalWorkspaceId; return { accessContext: { mode: "managed", subjectId: input.subjectId, subjectLabel: input.subjectLabel, accountGrants: activeOrganizationMemberships.map((organizationMembership) => ({ accountId: organizationMembership.organizationId, subjectId: input.subjectId, subjectLabel: input.subjectLabel, role: organizationMembership.role, permissions: accountPermissionsForOrganizationRole(organizationMembership.role), metadata: { accountName: organizationNameById.get(organizationMembership.organizationId) ?? null, }, })), workspaceGrants, defaultAccountId, defaultWorkspaceId, }, organizationMemberships: activeOrganizationMemberships.map((organizationMembership) => ({ id: organizationMembership.id, organizationId: organizationMembership.organizationId, status: "active" as const, personalWorkspaceId: organizationMembership.personalWorkspaceId, })), }; } export async function ensureManagedAccessForUserWithOrganizationMemberships( db: Database, input: { userId: string; email: string; name: string; emailVerified?: boolean; provisionFallbackOrganization?: boolean; bindPendingInvitations?: boolean; }, ): Promise { const subjectId = `user:${input.userId}`; const subjectLabel = accountContactEmail(input.email) || input.name; return await db.transaction(async (tx) => { const txDb = tx as unknown as Database; await setSubjectRlsContext(txDb, subjectId); if (input.emailVerified === true && input.bindPendingInvitations !== false) { await rawRows( txDb, sql`select bind_pending_organization_invitations_for_verified_email( ${subjectId}::text, ${input.email}::text )`, ); } const [existingOrganizationMembershipResult] = await rawRows<{ result: unknown; }>(txDb, sql`select list_self_organization_memberships(${subjectId}) as result`); const existingOrganizationMemberships = OrganizationMember.array().parse( existingOrganizationMembershipResult?.result ?? [], ); if (existingOrganizationMemberships.some((membership) => membership.status === "active")) { return await projectManagedOrganizationAccess(txDb, { subjectId, subjectLabel, organizationMemberships: existingOrganizationMemberships, userId: input.userId, }); } if ( existingOrganizationMemberships.some( (membership) => membership.status === "suspended" || membership.status === "revoked", ) ) { return { accessContext: { mode: "managed", subjectId, subjectLabel, accountGrants: [], workspaceGrants: [], defaultAccountId: null, defaultWorkspaceId: null, }, organizationMemberships: [], }; } const [pendingInvitationResult] = await rawRows<{ result: boolean }>( txDb, sql`select has_pending_organization_invitation_for_subject( ${subjectId}::text ) as result`, ); if (pendingInvitationResult?.result === true) { return { accessContext: { mode: "managed", subjectId, subjectLabel, accountGrants: [], workspaceGrants: [], defaultAccountId: null, defaultWorkspaceId: null, }, organizationMemberships: [], }; } if (input.provisionFallbackOrganization === false) { return { accessContext: { mode: "managed", subjectId, subjectLabel, accountGrants: [], workspaceGrants: [], defaultAccountId: null, defaultWorkspaceId: null, }, organizationMemberships: [], }; } const accountName = input.name || input.email; let [account] = await tx .select() .from(schema.managedAccounts) .where( and( eq(schema.managedAccounts.externalSource, "better-auth:user"), eq(schema.managedAccounts.externalId, input.userId), ), ) .limit(1); if (!account) { [account] = await tx .insert(schema.managedAccounts) .values({ name: accountName, externalSource: "better-auth:user", externalId: input.userId, }) .onConflictDoUpdate({ target: [schema.managedAccounts.externalSource, schema.managedAccounts.externalId], // The insert race may converge here, but later access refreshes must // never turn one-shot signup intent into an organization rename. set: { updatedAt: new Date() }, }) .returning(); } if (!account) { throw new Error("Failed to ensure managed account"); } await setRlsContext(tx as unknown as Database, { accountId: account.id, workspaceId: null, }); await setSubjectRlsContext(tx as unknown as Database, subjectId); let [defaultWorkspace] = await tx .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.externalSource, "better-auth:user"), eq(schema.workspaces.externalId, `${input.userId}:default`), eq(schema.workspaces.accountId, account.id), ), ) .limit(1); if (!defaultWorkspace) { [defaultWorkspace] = await tx .insert(schema.workspaces) .values({ accountId: account.id, name: "Default workspace", slug: "default", externalSource: "better-auth:user", externalId: `${input.userId}:default`, }) .onConflictDoUpdate({ target: [ schema.workspaces.accountId, schema.workspaces.externalSource, schema.workspaces.externalId, ], // Preserve a later administrator rename on legacy fallback workspaces. set: { updatedAt: new Date() }, }) .returning(); } if (!defaultWorkspace) { throw new Error("Failed to ensure default workspace"); } await setRlsContext(tx as unknown as Database, { accountId: defaultWorkspace.accountId, workspaceId: defaultWorkspace.id, }); const [workspaceControl] = await tx .select({ workspaceId: schema.workspaceInferenceControls.workspaceId }) .from(schema.workspaceInferenceControls) .where(eq(schema.workspaceInferenceControls.workspaceId, defaultWorkspace.id)) .limit(1); if (!workspaceControl) { await tx .insert(schema.workspaceInferenceControls) .values({ workspaceId: defaultWorkspace.id, accountId: defaultWorkspace.accountId, }) .onConflictDoNothing(); } // The remainder lists every membership in the account, so restore account- // scoped RLS after the exact-workspace control-row insert. await setRlsContext(tx as unknown as Database, { accountId: defaultWorkspace.accountId, workspaceId: null, }); const [membership] = await tx .select() .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, defaultWorkspace.id), eq(schema.workspaceMemberships.subjectId, subjectId), ), ) .limit(1); if (!membership) { await tx .insert(schema.workspaceMemberships) .values({ accountId: account.id, workspaceId: defaultWorkspace.id, subjectId, subjectLabel, role: "owner", permissions: allWorkspacePermissions, }) .onConflictDoUpdate({ target: [schema.workspaceMemberships.subjectId, schema.workspaceMemberships.workspaceId], set: { subjectLabel, role: "owner", permissions: allWorkspacePermissions, updatedAt: new Date(), }, }); } else if ( membership.accountId !== account.id || membership.subjectLabel !== subjectLabel || membership.role !== "owner" || !samePermissionSet(membership.permissions, allWorkspacePermissions) ) { await tx .update(schema.workspaceMemberships) .set({ accountId: account.id, subjectLabel, role: "owner", permissions: allWorkspacePermissions, updatedAt: new Date(), }) .where(eq(schema.workspaceMemberships.id, membership.id)); } await ensureManagedHumanPersonalWorkspace(tx as unknown as Database, { accountId: account.id, subjectId, }); // Keep persisted legacy grants first so defaultWorkspaceId and callers that // still select the first grant preserve the existing default workspace. // The personal grant is derived only after the lifecycle capability returns // the exact active membership pointer; no workspace_memberships row is // created, so no administrator or secondary principal gains ambient access. await setRlsContext(tx as unknown as Database, { accountId: account.id, workspaceId: null, }); await setSubjectRlsContext(tx as unknown as Database, subjectId); const memberships = await tx .select({ membership: schema.workspaceMemberships, workspace: schema.workspaces, }) .from(schema.workspaceMemberships) .innerJoin( schema.workspaces, eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id), ) .where( and( eq(schema.workspaceMemberships.subjectId, subjectId), eq(schema.workspaceMemberships.accountId, account.id), eq(schema.workspaces.accountId, account.id), joinedWorkspaceIsNotPersonal(), ), ) .orderBy(desc(schema.workspaces.createdAt)); const workspaceGrants: AccessGrant[] = memberships.map((row) => ({ workspaceId: row.workspace.id, accountId: row.workspace.accountId, subjectId, subjectLabel, permissions: normalizeWorkspaceMembershipPermissions(row.membership.permissions), principalKind: "human_session", })); const [organizationMembershipResult] = await rawRows<{ result: unknown }>( tx, sql`select list_self_organization_memberships(${subjectId}) as result`, ); const projectedOrganizationMemberships = OrganizationMember.array().parse( organizationMembershipResult?.result ?? [], ); const inactiveOrganizationIds = new Set( projectedOrganizationMemberships .filter((organizationMembership) => organizationMembership.status !== "active") .map((organizationMembership) => organizationMembership.organizationId), ); for (let index = workspaceGrants.length - 1; index >= 0; index -= 1) { if (inactiveOrganizationIds.has(workspaceGrants[index]!.accountId)) { workspaceGrants.splice(index, 1); } } const activeOrganizationMemberships = projectedOrganizationMemberships.flatMap( (organizationMembership) => organizationMembership.status === "active" && organizationMembership.personalWorkspaceId !== null ? [ { ...organizationMembership, status: "active" as const, personalWorkspaceId: organizationMembership.personalWorkspaceId, }, ] : [], ); for (const organizationMembership of activeOrganizationMemberships) { if (organizationMembership.organizationId === account.id) continue; await setRlsContext(tx as unknown as Database, { accountId: organizationMembership.organizationId, workspaceId: null, }); const persistedOrganizationMemberships = await tx .select({ membership: schema.workspaceMemberships, workspace: schema.workspaces, }) .from(schema.workspaceMemberships) .innerJoin( schema.workspaces, eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id), ) .where( and( eq(schema.workspaceMemberships.subjectId, subjectId), eq(schema.workspaceMemberships.accountId, organizationMembership.organizationId), eq(schema.workspaces.accountId, organizationMembership.organizationId), joinedWorkspaceIsNotPersonal(), ), ) .orderBy(desc(schema.workspaces.createdAt)); for (const row of persistedOrganizationMemberships) { if (workspaceGrants.some((grant) => grant.workspaceId === row.workspace.id)) continue; workspaceGrants.push({ workspaceId: row.workspace.id, accountId: row.workspace.accountId, subjectId, subjectLabel, permissions: normalizeWorkspaceMembershipPermissions(row.membership.permissions), principalKind: "human_session", }); } } for (const organizationMembership of activeOrganizationMemberships) { if ( !workspaceGrants.some( (grant) => grant.workspaceId === organizationMembership.personalWorkspaceId, ) ) { workspaceGrants.push({ workspaceId: organizationMembership.personalWorkspaceId, accountId: organizationMembership.organizationId, subjectId, subjectLabel, permissions: managedPersonalWorkspacePermissions, principalKind: "human_session", }); } } const organizationAccounts = await tx .select({ id: schema.managedAccounts.id, name: schema.managedAccounts.name, }) .from(schema.managedAccounts) .where( inArray( schema.managedAccounts.id, activeOrganizationMemberships.map((activeMembership) => activeMembership.organizationId), ), ); const organizationNameById = new Map( organizationAccounts.map((organization) => [organization.id, organization.name]), ); return { accessContext: { mode: "managed", subjectId, subjectLabel, accountGrants: activeOrganizationMemberships.map((organizationMembership) => ({ accountId: organizationMembership.organizationId, subjectId, subjectLabel, role: organizationMembership.role, permissions: accountPermissionsForOrganizationRole(organizationMembership.role), metadata: { accountName: organizationNameById.get(organizationMembership.organizationId) ?? null, }, })), workspaceGrants, defaultAccountId: account.id, defaultWorkspaceId: defaultWorkspace.id, }, organizationMemberships: activeOrganizationMemberships.map((organizationMembership) => ({ id: organizationMembership.id, organizationId: organizationMembership.organizationId, status: "active" as const, personalWorkspaceId: organizationMembership.personalWorkspaceId, })), }; }); } export async function getWorkspace(db: Database, workspaceId: string): Promise { const [row] = await db .select() .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if (!row) return null; // Bootstrap metadata is not RLS-protected. It does not by itself establish // that the complete workspace is readable in the caller's database scope. return await withWorkspaceRls(db, row.id, async (scopedDb) => { const control = await readWorkspaceControlProjection(scopedDb, row.id); if (!control) return null; return mapWorkspace(row, control, await readWorkspaceKindProjection(scopedDb, row)); }); } /** * Only a workspace's settings, as {@link getWorkspace} maps them: one read * instead of its three, for callers that need nothing else. Null when the * workspace is absent or not visible. */ export async function getWorkspaceSettings( db: Database, workspaceId: string, ): Promise | null> { const [row] = await db .select({ settings: schema.workspaces.settings }) .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); return row ? ((row.settings ?? {}) as Record) : null; } export async function getManagedAccount( db: Database, accountId: string, ): Promise { const [row] = await db .select() .from(schema.managedAccounts) .where(eq(schema.managedAccounts.id, accountId)) .limit(1); return row ? mapAccount(row) : null; } export async function requireWorkspace(db: Database, workspaceId: string): Promise { const workspace = await getWorkspace(db, workspaceId); if (!workspace) { throw new Error(`Workspace not found: ${workspaceId}`); } return workspace; } export async function listWorkspacesForSubject( db: Database, subjectId: string, limit = 100, ): Promise { const rows = await db .select({ workspace: schema.workspaces }) .from(schema.workspaceMemberships) .innerJoin(schema.workspaces, eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id)) .where( and(eq(schema.workspaceMemberships.subjectId, subjectId), joinedWorkspaceIsNotPersonal()), ) .orderBy(desc(schema.workspaces.createdAt)) .limit(limit); return await mapWorkspaceProjections(db, rows, async (row) => mapWorkspace( row.workspace, await workspaceControlProjection(db, row.workspace.id), await workspaceKindProjection(db, row.workspace), ), ); } /** * Complete organization-workspace inventory for an account-scoped caller. * Personal workspaces are excluded by the canonical organization-membership * pointer through one narrowly granted set-based database capability; the * public projection is therefore safely emitted as the current wire value * `kind: "shared"`. */ export async function listSharedWorkspacesForAccount( db: Database, accountId: string, ): Promise { const rows = await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => { return await scopedDb .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.accountId, accountId), sql`${schema.workspaces.id} in ( select workspace_id from list_organization_workspace_ids(${accountId}::uuid) )`, ), ) .orderBy(desc(schema.workspaces.createdAt)); }); return await mapWorkspaceProjections(db, rows, async (row) => mapWorkspace(row, await workspaceControlProjection(db, row.id), "shared"), ); } /** Ids of the organization's shared workspaces, newest first; no projections. */ export async function listOrganizationWorkspaceIds( db: Database, accountId: string, limit = 200, ): Promise { const rows = await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => scopedDb .select({ id: schema.workspaces.id }) .from(schema.workspaces) .where( and( eq(schema.workspaces.accountId, accountId), sql`${schema.workspaces.id} in ( select workspace_id from list_organization_workspace_ids(${accountId}::uuid) )`, ), ) .orderBy(desc(schema.workspaces.createdAt)) .limit(limit), ); return rows.map((row) => row.id); } export async function countWorkspacesForAccount(db: Database, accountId: string): Promise { const [{ count } = { count: 0 }] = await db .select({ count: sql`count(*)::int`, }) .from(schema.workspaces) .where(eq(schema.workspaces.accountId, accountId)); return Number(count); } export async function createWorkspace( db: Database, input: { accountId: string; name: string; slug?: string | null; externalSource?: string | null; externalId?: string | null; agentInstructions?: string | null; maxWorkspacesPerAccount?: number | null; }, ): Promise { return await db.transaction(async (tx) => { const transaction = tx as unknown as Database; if (workspaceLimitConfigured(input.maxWorkspacesPerAccount)) { await setRlsContext(transaction, { accountId: input.accountId, workspaceId: null }); } await acquireWorkspaceLimitLock(transaction, input.accountId, input.maxWorkspacesPerAccount); await assertWorkspaceCapacity(transaction, input.accountId, input.maxWorkspacesPerAccount); const [row] = await tx .insert(schema.workspaces) .values({ accountId: input.accountId, name: input.name, slug: input.slug ?? null, externalSource: input.externalSource ?? null, externalId: input.externalId ?? null, agentInstructions: input.agentInstructions ?? null, }) .returning(); if (!row) { throw new Error("Failed to create workspace"); } await setRlsContext(transaction, { accountId: row.accountId, workspaceId: row.id, }); await tx.insert(schema.workspaceInferenceControls).values({ workspaceId: row.id, accountId: row.accountId, }); return mapWorkspace( row, { state: "active", revision: 0, reason: null, changedBy: null, changedAt: null, }, "shared", ); }); } export class WorkspaceExternalIdentityConflictError extends Error { constructor() { super("External workspace identity is already in use"); this.name = "WorkspaceExternalIdentityConflictError"; } } export async function findWorkspaceByExternalIdentity( db: Database, input: { accountId: string; externalSource: string; externalId: string; }, ): Promise { const [row] = await db .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.externalSource, input.externalSource), eq(schema.workspaces.externalId, input.externalId), eq(schema.workspaces.accountId, input.accountId), ), ) .limit(1); if (!row) return null; const kind = await workspaceKindProjection(db, row); return mapWorkspace(row, await workspaceControlProjection(db, row.id), kind); } export class WorkspaceLimitExceededError extends Error { constructor(readonly limit: number) { super(`Workspace limit reached (${limit})`); this.name = "WorkspaceLimitExceededError"; } } function workspaceLimitConfigured(limit: number | null | undefined): limit is number { return limit !== null && limit !== undefined; } async function acquireWorkspaceLimitLock( db: Database, accountId: string, limit: number | null | undefined, ): Promise { if (!workspaceLimitConfigured(limit)) return; await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`workspace-limit:${accountId}`}, 0))`, ); } async function assertWorkspaceCapacity( db: Database, accountId: string, limit: number | null | undefined, ): Promise { if (!workspaceLimitConfigured(limit)) return; const [{ count } = { count: 0 }] = await db .select({ count: sql`count(*)::int` }) .from(schema.workspaces) .where(eq(schema.workspaces.accountId, accountId)); if (Number(count) >= limit) { throw new WorkspaceLimitExceededError(limit); } } /** * Create an organization workspace exactly once for a stable external tenant * identity. The organization-scoped unique index is the concurrency arbiter. A replay never * mutates presentation fields supplied by the original create. */ export async function ensureWorkspaceByExternalIdentity( db: Database, input: { accountId: string; externalSource: string; externalId: string; name: string; slug?: string | null; agentInstructions?: string | null; maxWorkspacesPerAccount?: number | null; }, ): Promise<{ workspace: Workspace; created: boolean }> { return await db.transaction(async (tx) => { const transaction = tx as unknown as Database; await setRlsContext(transaction, { accountId: input.accountId, workspaceId: null }); await acquireWorkspaceLimitLock(transaction, input.accountId, input.maxWorkspacesPerAccount); const [existingBeforeCreate] = await tx .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.externalSource, input.externalSource), eq(schema.workspaces.externalId, input.externalId), eq(schema.workspaces.accountId, input.accountId), ), ) .limit(1); if (existingBeforeCreate) { if (existingBeforeCreate.accountId !== input.accountId) { throw new WorkspaceExternalIdentityConflictError(); } const kind = await workspaceKindProjection(transaction, existingBeforeCreate); if (kind !== "shared") { throw new WorkspaceExternalIdentityConflictError(); } return { workspace: mapWorkspace( existingBeforeCreate, await workspaceControlProjection(transaction, existingBeforeCreate.id), kind, ), created: false, }; } await assertWorkspaceCapacity(transaction, input.accountId, input.maxWorkspacesPerAccount); const [inserted] = await tx .insert(schema.workspaces) .values({ accountId: input.accountId, name: input.name, slug: input.slug ?? null, externalSource: input.externalSource, externalId: input.externalId, agentInstructions: input.agentInstructions ?? null, }) .onConflictDoNothing({ target: [ schema.workspaces.accountId, schema.workspaces.externalSource, schema.workspaces.externalId, ], }) .returning(); if (inserted) { await setRlsContext(transaction, { accountId: inserted.accountId, workspaceId: inserted.id, }); await tx.insert(schema.workspaceInferenceControls).values({ workspaceId: inserted.id, accountId: inserted.accountId, }); return { workspace: mapWorkspace( inserted, { state: "active", revision: 0, reason: null, changedBy: null, changedAt: null, }, "shared", ), created: true, }; } const [existing] = await tx .select() .from(schema.workspaces) .where( and( eq(schema.workspaces.externalSource, input.externalSource), eq(schema.workspaces.externalId, input.externalId), eq(schema.workspaces.accountId, input.accountId), ), ) .limit(1); if (!existing || existing.accountId !== input.accountId) { throw new WorkspaceExternalIdentityConflictError(); } const kind = await workspaceKindProjection(transaction, existing); if (kind !== "shared") { throw new WorkspaceExternalIdentityConflictError(); } return { workspace: mapWorkspace( existing, await workspaceControlProjection(transaction, existing.id), kind, ), created: false, }; }); } /** * Create one shared workspace through the direct managed-human organization * control plane. Organization authority is rechecked inside the lifecycle * function, the operation id is replay-safe, and no operational * workspace_memberships row is created for the actor. */ export async function createOrganizationSharedWorkspace( db: Database, input: { organizationId: string; actorSubjectId: string; name: string; slug?: string | null; agentInstructions?: string | null; operationId: string; }, ): Promise { return await db.transaction(async (tx) => { const txDb = tx as unknown as Database; return await withRlsContext( txDb, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); const [result] = await rawRows<{ result: { workspaceId?: unknown } }>( scopedDb, sql`select create_organization_shared_workspace( ${input.organizationId}::uuid, ${input.actorSubjectId}, ${input.name}, ${input.slug ?? null}, ${input.agentInstructions ?? null}, ${input.operationId}::uuid ) as result`, ); const workspaceId = result?.result?.workspaceId; if (typeof workspaceId !== "string") { throw new Error("Organization shared-workspace creation returned no workspace id"); } return await requireWorkspace(scopedDb, workspaceId); }, ); }); } export class WorkspaceMemberManagementError extends Error { constructor( readonly code: | "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN", ) { super(code); this.name = "WorkspaceMemberManagementError"; } } /** * Add or update one human workspace member under the same organization fence * used by suspension, offboarding, organization-level grants, and removals. * The SECURITY DEFINER candidate check runs after the fence is held, so a * concurrent lifecycle transition cannot invalidate authority between the * check and the membership write. */ export async function upsertWorkspaceMemberAsWorkspaceManager( db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; targetSubjectId: string; mode: "add" | "update"; subjectLabel?: string; role: string; permissions: Permission[]; }, ): Promise { await db.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended( ${`organization-membership:${input.accountId}`}, 0 ))`, ); await assertWorkspaceMemberManagementCandidate(tx, input); if (input.targetSubjectId === input.actorSubjectId) { throw new WorkspaceMemberManagementError("WORKSPACE_MEMBER_SELF_UPDATE"); } if (!input.targetSubjectId.startsWith("user:")) { throw new WorkspaceMemberManagementError("WORKSPACE_MEMBER_NOT_FOUND"); } const roster = await tx .select({ subjectId: schema.workspaceMemberships.subjectId, permissions: schema.workspaceMemberships.permissions, }) .from(schema.workspaceMemberships) .where(eq(schema.workspaceMemberships.workspaceId, input.workspaceId)) .orderBy(asc(schema.workspaceMemberships.id)) .for("update"); const target = roster.find((member) => member.subjectId === input.targetSubjectId); if (input.mode === "add" && target) { throw new WorkspaceMemberManagementError("WORKSPACE_MEMBER_ALREADY_EXISTS"); } if (input.mode === "update" && !target) { throw new WorkspaceMemberManagementError("WORKSPACE_MEMBER_NOT_FOUND"); } const administers = (permissions: unknown): boolean => { const normalized = normalizeWorkspaceMembershipPermissions(permissions); return normalized.includes("workspace:admin") || normalized.includes("members:manage"); }; if ( target && administers(target.permissions) && !administers(input.permissions) && !roster.some( (member) => member.subjectId !== input.targetSubjectId && administers(member.permissions), ) ) { throw new WorkspaceMemberManagementError("WORKSPACE_MEMBER_LAST_ADMIN"); } await grantWorkspaceAccess(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.targetSubjectId, ...(input.subjectLabel !== undefined ? { subjectLabel: input.subjectLabel } : {}), role: input.role, permissions: input.permissions, }); }); } /** Prove workspace-scoped management and same-organization active membership. */ export async function assertWorkspaceMemberManagementCandidate( db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; targetSubjectId: string; }, ): Promise { await withWorkspaceSubjectRls(db, input.workspaceId, input.actorSubjectId, async (scopedDb) => { await scopedDb.execute(sql`select assert_workspace_member_management_candidate( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.actorSubjectId}, ${input.targetSubjectId} )`); }); } /** List active same-organization humans who do not already have workspace access. */ export async function listWorkspaceMemberManagementCandidates( db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; }, ): Promise { return await withWorkspaceSubjectRls( db, input.workspaceId, input.actorSubjectId, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select list_workspace_member_management_candidates( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.actorSubjectId} ) as result`, ); return ListWorkspaceMemberCandidatesResponse.parse({ members: row?.result ?? [], }).members; }, ); } async function withOrganizationSharedWorkspaceAdministration( db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; }, operation: (scopedDb: Database) => Promise, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); await scopedDb.execute(sql`select assert_organization_shared_workspace_administrator( ${input.organizationId}::uuid, ${input.workspaceId}::uuid, ${input.actorSubjectId} )`); return await operation(scopedDb); }, ); } /** * Organization control-plane metadata update for one shared workspace. This * capability never creates a workspace membership or an operational grant for * the actor; the database excludes every Personal workspace before mutation. */ export async function updateOrganizationSharedWorkspace( db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; name?: string; slug?: string | null; agentInstructions?: string | null; }, ): Promise { return await withOrganizationSharedWorkspaceAdministration( db, input, async (scopedDb) => await updateWorkspace(scopedDb, input.workspaceId, { ...(input.name !== undefined ? { name: input.name } : {}), ...(input.slug !== undefined ? { slug: input.slug } : {}), ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), }), ); } /** Same authority as metadata administration, preserving the canonical * workspace-settings merge and inference-control lock path. */ export async function updateOrganizationSharedWorkspaceSettings( db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; patch: Record; }, ): Promise { return await withOrganizationSharedWorkspaceAdministration( db, input, async (scopedDb) => await updateWorkspaceSettings(scopedDb, input.workspaceId, input.patch), ); } /** Assign or update one active organization member in one shared workspace. */ export async function upsertOrganizationSharedWorkspaceMember( db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; targetOrganizationMembershipId: string; subjectLabel?: string | null; role?: string; permissions: Permission[]; requireExisting: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select upsert_organization_shared_workspace_member( ${input.organizationId}::uuid, ${input.workspaceId}::uuid, ${input.actorSubjectId}, ${input.targetOrganizationMembershipId}::uuid, ${input.subjectLabel ?? null}, ${input.role ?? null}, ${JSON.stringify(input.permissions)}::jsonb, ${input.requireExisting} ) as result`, ); return WorkspaceMemberContract.parse(row?.result); }, ); } export async function updateWorkspace( db: Database, workspaceId: string, input: { name?: string; slug?: string | null; agentInstructions?: string | null; }, ): Promise { const [row] = await db .update(schema.workspaces) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.slug !== undefined ? { slug: input.slug } : {}), ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), updatedAt: new Date(), }) .where(eq(schema.workspaces.id, workspaceId)) .returning(); if (!row) { throw new Error(`Workspace not found: ${workspaceId}`); } return mapWorkspace( row, await workspaceControlProjection(db, workspaceId), await workspaceKindProjection(db, row), ); } // Deep-merge (top-level) a settings patch into workspaces.settings, atomically. // jsonb `||` overwrites matching keys and preserves unknown ones, so a newer // setting a caller doesn't know about survives the write. export async function updateWorkspaceSettings( db: Database, workspaceId: string, patch: Record, options: { /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; } = {}, ): Promise { const { modelCompactionThresholds, realtimeVoice, ...ordinaryPatch } = patch; const thresholds = modelCompactionThresholds === undefined ? undefined : WorkspaceModelCompactionThresholdsPatch.parse(modelCompactionThresholds); const voiceByModel = realtimeVoice === undefined ? undefined : WorkspaceRealtimeVoicePatch.parse(realtimeVoice); // Merge each exact-model key inside the SQL update, not a read/modify/write // in the API: simultaneous edits to different models must both survive. A // null model value removes that model's key. const mergeByModel = ( settings: ReturnType, key: "modelCompactionThresholds" | "realtimeVoice", values: Record | undefined, ) => values === undefined ? settings : sql`jsonb_set((${settings}), ${`{${key}}`}::text[], jsonb_strip_nulls((case when jsonb_typeof(${schema.workspaces.settings}->${key}::text) = 'object' then ${schema.workspaces.settings}->${key}::text else '{}'::jsonb end) || ${JSON.stringify(values)}::jsonb))`; const settingsPatch = ( base: typeof schema.workspaces.settings | ReturnType, values: Record, ) => mergeByModel( mergeByModel( sql`${base} || ${JSON.stringify(values)}::jsonb`, "modelCompactionThresholds", thresholds, ), "realtimeVoice", voiceByModel, ); if (Object.prototype.hasOwnProperty.call(patch, "maxNestedAgentDepth")) { const requested = patch.maxNestedAgentDepth; if ( requested !== null && !( typeof requested === "number" && Number.isSafeInteger(requested) && requested >= 0 && requested <= 2_147_483_647 ) ) { throw new Error("maxNestedAgentDepth must be null or a non-negative 32-bit integer"); } const nextPatch = { ...ordinaryPatch }; if (requested === null) delete nextPatch.maxNestedAgentDepth; return await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { // Keep settings writers in the same control-row -> workspace-row order // as session admission. This makes a narrowing atomic with respect to // every create that could otherwise observe a mixed policy snapshot. await lockWorkspaceInferenceControl(tx as unknown as Database, workspaceId, "update", { ...(options.controlLockTimeoutMs !== undefined ? { lockTimeoutMs: options.controlLockTimeoutMs } : {}), }); const [row] = await tx .update(schema.workspaces) .set({ settings: requested === null ? settingsPatch( sql`(${schema.workspaces.settings} - 'maxNestedAgentDepth')`, nextPatch, ) : settingsPatch(schema.workspaces.settings, nextPatch), updatedAt: new Date(), }) .where(eq(schema.workspaces.id, workspaceId)) .returning(); if (!row) throw new Error(`Workspace not found: ${workspaceId}`); return mapWorkspace( row, await workspaceControlProjection(tx as unknown as Database, workspaceId), await workspaceKindProjection(tx as unknown as Database, row), ); }), ); } // A null default model removes the workspace's own choice, so it follows // its organization's default (or the automatic default) again. const clearSessionDefaults = ordinaryPatch.sessionDefaults === null; const plainPatch = { ...ordinaryPatch }; if (clearSessionDefaults) delete plainPatch.sessionDefaults; const [row] = await db .update(schema.workspaces) .set({ settings: settingsPatch( clearSessionDefaults ? sql`(${schema.workspaces.settings} - 'sessionDefaults')` : schema.workspaces.settings, plainPatch, ), updatedAt: new Date(), }) .where(eq(schema.workspaces.id, workspaceId)) .returning(); if (!row) { throw new Error(`Workspace not found: ${workspaceId}`); } return mapWorkspace( row, await workspaceControlProjection(db, workspaceId), await workspaceKindProjection(db, row), ); } export async function setWorkspaceDefaultRig( db: Database, workspaceId: string, rigId: string | null, ): Promise { const [row] = await db .update(schema.workspaces) .set({ defaultRigId: rigId, updatedAt: new Date(), }) .where(eq(schema.workspaces.id, workspaceId)) .returning(); if (!row) { throw new Error(`Workspace not found: ${workspaceId}`); } return mapWorkspace( row, await workspaceControlProjection(db, workspaceId), await workspaceKindProjection(db, row), ); } export async function getWorkspaceGrant( db: Database, subjectId: string, workspaceId: string, provenance?: { principalKind?: AccessPrincipalKind }, ): Promise { // A bare membership grant, never a Personal workspace's own row: whoever // names the owner's subject would otherwise reach it. See // membershipOutsidePersonalWorkspace. const [row] = await db .select({ membership: schema.workspaceMemberships, workspace: schema.workspaces, }) .from(schema.workspaceMemberships) .innerJoin(schema.workspaces, eq(schema.workspaceMemberships.workspaceId, schema.workspaces.id)) .where( and( eq(schema.workspaceMemberships.subjectId, subjectId), eq(schema.workspaceMemberships.workspaceId, workspaceId), joinedWorkspaceIsNotPersonal(), ), ) .limit(1); return row ? { workspaceId: row.workspace.id, accountId: row.workspace.accountId, subjectId: row.membership.subjectId, ...(row.membership.subjectLabel ? { subjectLabel: row.membership.subjectLabel } : {}), permissions: normalizeWorkspaceMembershipPermissions(row.membership.permissions), ...(provenance?.principalKind ? { principalKind: provenance.principalKind } : {}), } : null; } // removeWorkspaceMember moved to ./organization-membership-lifecycle: removal is // now the fenced SECURITY DEFINER teardown from migration 0278. /** * Resolve a managed user email to its user id. * * STANDALONE (default, unchanged): the `auth_users` table is owned by Better * Auth and is NOT in the Drizzle schema, so this runs the raw parameterized * select below — matching emails case-insensitively, returning the id or null. * * EMBEDDED (Step I `userLookup` port): when the handle was built via * `createDb({ userLookup })` (or registered with `registerDbBinding`), this * delegates to the host's resolver instead — so a host whose identity lives in * a different IdP/table/driver never forces Opengeni to touch `auth_users`. The * raw query also assumes the postgres-js array-shaped `db.execute` result; the * port is the cross-driver escape hatch for that too. * * Used to add an already-registered user to a workspace; email invites for * unknown users are deferred. */ export async function getManagedUserByEmail(db: Database, email: string): Promise { const binding = dbBindingFor(db); if (binding?.userLookup) { return await binding.userLookup(db, email); } const rows = await db.execute(sql<{ id: string }>` select id from auth_users where lower(email) = lower(${email}) limit 1 `); return (rows as unknown as Array<{ id?: string }>)[0]?.id ?? null; } /** * Resolve the safe profile fields organization administrators need to manage * their own roster. Embedded deployments can provide the same projection * through `userProfileLookup` without exposing their identity store schema. */ export async function getManagedUserProfilesByIds( db: Database, userIds: readonly string[], ): Promise> { const uniqueUserIds = [...new Set(userIds.filter(Boolean))]; if (uniqueUserIds.length === 0) return []; const binding = dbBindingFor(db); if (binding?.userProfileLookup) { return await binding.userProfileLookup(db, uniqueUserIds); } return await rawRows<{ id: string; name: string | null; email: string }>( db, sql`select id, name, email from auth_users where id in (${sql.join( uniqueUserIds.map((userId) => sql`${userId}`), sql`, `, )})`, ); } /** * A person's verified email address in lowercase, or null when the subject is * not a managed user (`user:`), has no email, or has not verified it. * Embedded hosts answer through their `userProfileLookup`; their address * counts only when the profile says `emailVerified: true`. */ export async function getVerifiedSubjectEmail( db: Database, subjectId: string, ): Promise { if (!subjectId.startsWith("user:")) return null; const userId = subjectId.slice("user:".length); if (!userId) return null; const binding = dbBindingFor(db); if (binding?.userProfileLookup) { const [profile] = await binding.userProfileLookup(db, [userId]); if (profile?.emailVerified !== true) return null; return profile.email?.trim().toLowerCase() || null; } const [row] = await rawRows<{ email: string | null }>( db, sql`select email from auth_users where id = ${userId} and email_verified is true limit 1`, ); return row?.email?.trim().toLowerCase() || null; } /** * A workspace member's name as the workspace's people list shows it: their * profile name, else the label their membership was given, else their email. * Null when none is known. */ export async function workspaceMemberDisplayName( db: Database, input: { workspaceId: string; subjectId: string }, ): Promise { // A deployment without managed profiles still has membership labels. const [profile] = input.subjectId.startsWith("user:") ? await getManagedUserProfilesByIds(db, [input.subjectId.slice("user:".length)]).catch(() => []) : []; const name = profile?.name?.trim(); if (name) return name; const [membership] = await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => scopedDb .select({ subjectLabel: schema.workspaceMemberships.subjectLabel }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, input.workspaceId), eq(schema.workspaceMemberships.subjectId, input.subjectId), ), ) .limit(1), ); return membership?.subjectLabel?.trim() || profile?.email?.trim() || null; } export async function deleteWorkspace(db: Database, workspaceId: string): Promise { await db.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await tx.execute( sql`select pg_advisory_xact_lock_shared(hashtextextended(${`session-tenancy:${workspaceId}`}, 0))`, ); await tx.execute(sql`select opengeni_private.defer_workspace_cascade_foreign_keys()`); await tx.delete(schema.workspaces).where(eq(schema.workspaces.id, workspaceId)); }); } export type TemporalScheduleCleanupClaim = { id: string; accountId: string; workspaceId: string; temporalScheduleId: string; scheduledTaskId: string | null; connectorCleanupSubjectId: string | null; connectorCleanupSnapshot: unknown | null; connectorCleanupCompletedAt: Date | null; claimId: string; attemptCount: number; }; export type DeleteWorkspaceIfQuiescentResult = | { status: "deleted"; temporalScheduleCleanups: TemporalScheduleCleanupClaim[]; } | { status: | "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes"; }; export type WorkspaceDeletePhase = | "transaction" | "lifecycle_lock" | "account_workspace_lock" | "session_fence" | "runtime_ownership" | "external_cleanup" | "variable_set_detach" | "cascade"; export type WorkspaceDeleteOutcome = DeleteWorkspaceIfQuiescentResult["status"] | "ok" | "error"; export type WorkspaceDeleteInventoryKind = | "workspaces" | "sessions" | "live_attempts" | "active_video_generations" | "active_background_commands" | "sandbox_leases" | "sandbox_holders" | "unsettled_sandbox_admissions" | "active_retained_processes" | "open_ptys" | "temporal_schedules"; export type WorkspaceDeleteObservation = { phase: WorkspaceDeletePhase; outcome: WorkspaceDeleteOutcome; durationSeconds: number; inventory?: Partial>; }; export type WorkspaceDeleteObserver = { onPhase?: (observation: WorkspaceDeleteObservation) => void; }; function observeWorkspaceDeletePhase( observer: WorkspaceDeleteObserver | undefined, observation: WorkspaceDeleteObservation, ): void { try { observer?.onPhase?.(observation); } catch { // Telemetry must never alter deletion authority or transaction outcome. } } function workspaceDeletePhaseDuration(startedAt: number): number { return Math.max(0, (performance.now() - startedAt) / 1_000); } async function lockBackgroundCommandWorkspaceLifecycle( tx: Database, workspaceIds: string[], mode: "share" | "update", ): Promise { for (const workspaceId of [...new Set(workspaceIds)].sort()) { if (mode === "share") { await tx.execute( sql`select pg_advisory_xact_lock_shared(hashtextextended(${`background-command-workspace:${workspaceId}`}, 0))`, ); } else { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`background-command-workspace:${workspaceId}`}, 0))`, ); } } } async function authorizeOrganizationWorkspaceDeletion( tx: Database, input: { accountId: string; workspaceId: string; subjectId: string; }, ): Promise { await setSubjectRlsContext(tx, input.subjectId); await tx.execute(sql` select authorize_organization_shared_workspace_administration( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId} ) `); } /** * Atomically prove a workspace has no live runtime ownership and delete it. * * The target takes the canonical writer prefix exclusively (workspace-control * advisory key and inference-control row, then the workspace row), which blocks * concurrent child inserts into that workspace through their foreign-key * key-share locks without inverting the order ordinary writers use. The account * row and sibling workspace rows take only the strength needed to serialize * deletions and the only-workspace check, so ordinary writers in other * workspaces of the same account cannot deadlock with a deletion. Existing * session and lease rows are then locked before their state is inspected, so a * cold lease cannot become live between a preflight count and the cascade. * Schedule ids are copied under the same fence and returned for post-commit * Temporal cleanup. */ export async function deleteWorkspaceIfQuiescent( db: Database, input: { accountId: string; workspaceId: string; observer?: WorkspaceDeleteObserver; organizationAdministratorSubjectId?: string; }, ): Promise { const transactionStartedAt = performance.now(); try { if (input.organizationAdministratorSubjectId) { // Reject a clearly unauthorized caller before it can acquire or wait on // the exclusive workspace lifecycle lock. This preflight is deliberately // not the mutation authority: the deletion transaction repeats the same // check after taking the lifecycle lock so a concurrent demotion still // fails closed without reintroducing the account/lifecycle lock cycle. await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await authorizeOrganizationWorkspaceDeletion(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.organizationAdministratorSubjectId!, }), ); } const result = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Adoption takes the matching shared prefix before its canonical // session/attempt or retained-process locks. Taking the exclusive // prefix first prevents parent-FK deletion from deadlocking with an // already-started cross-workspace adoption. It must also precede the // organization-administration seam: that seam takes the account row // FOR KEY SHARE, while ordinary deletion takes this lifecycle lock // before upgrading the account row to FOR NO KEY UPDATE. const lifecycleLockStartedAt = performance.now(); await lockBackgroundCommandWorkspaceLifecycle(tx, [input.workspaceId], "update"); observeWorkspaceDeletePhase(input.observer, { phase: "lifecycle_lock", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(lifecycleLockStartedAt), }); if (input.organizationAdministratorSubjectId) { await authorizeOrganizationWorkspaceDeletion(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.organizationAdministratorSubjectId, }); } const accountWorkspaceLockStartedAt = performance.now(); // NO KEY UPDATE serializes concurrent deletions in one account (the // only-workspace check below) without blocking ordinary writers. // Every account-scoped insert takes this row FOR KEY SHARE through // its account FK, often while already holding its own workspace row // the same way; FOR UPDATE here deadlocked those writers against the // workspace locks below. const [account] = await tx .select({ id: schema.managedAccounts.id }) .from(schema.managedAccounts) .where(eq(schema.managedAccounts.id, input.accountId)) .for("no key update") .limit(1); if (!account) { observeWorkspaceDeletePhase(input.observer, { phase: "account_workspace_lock", outcome: "not_found", durationSeconds: workspaceDeletePhaseDuration(accountWorkspaceLockStartedAt), }); return { status: "not_found" as const }; } // The target takes the canonical writer prefix exclusively: the // workspace-control advisory key and inference-control row before // the workspace row. Writers in this workspace (and the membership // lifecycle) hold the control row before reaching the workspace row, // and the cascade below deletes the control row, so locking the // workspace row first would deadlock them. // A missing control row (an unknown workspace, or one created // without it) leaves only the exclusive advisory key held. No writer // can hold a row that does not exist, so the deletion continues and // the workspace lookup below decides whether it is not_found. try { await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); } catch (error) { if (!(error instanceof SessionControlInvariantError)) throw error; } // The target row FOR UPDATE then blocks concurrent child inserts // into this workspace through their workspace FK key-share locks. // Sibling rows only have to stay present for the only-workspace // check, so they take KEY SHARE, which blocks their deletion but not // ordinary writes in those workspaces. const [target] = await tx .select({ id: schema.workspaces.id }) .from(schema.workspaces) .where( and( eq(schema.workspaces.id, input.workspaceId), eq(schema.workspaces.accountId, input.accountId), ), ) .for("update"); const accountWorkspaces = target ? await tx .select({ id: schema.workspaces.id }) .from(schema.workspaces) .where(eq(schema.workspaces.accountId, input.accountId)) .for("key share") : []; if ( !target || !accountWorkspaces.some((workspace) => workspace.id === input.workspaceId) ) { observeWorkspaceDeletePhase(input.observer, { phase: "account_workspace_lock", outcome: "not_found", durationSeconds: workspaceDeletePhaseDuration(accountWorkspaceLockStartedAt), inventory: { workspaces: accountWorkspaces.length }, }); return { status: "not_found" as const }; } if (accountWorkspaces.length <= 1) { observeWorkspaceDeletePhase(input.observer, { phase: "account_workspace_lock", outcome: "only_workspace", durationSeconds: workspaceDeletePhaseDuration(accountWorkspaceLockStartedAt), inventory: { workspaces: accountWorkspaces.length }, }); return { status: "only_workspace" as const }; } observeWorkspaceDeletePhase(input.observer, { phase: "account_workspace_lock", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(accountWorkspaceLockStartedAt), inventory: { workspaces: accountWorkspaces.length }, }); const sessionFenceStartedAt = performance.now(); const sessions = await tx .select({ id: schema.sessions.id, status: schema.sessions.status }) .from(schema.sessions) .where(eq(schema.sessions.workspaceId, input.workspaceId)) .for("update", { noWait: true }); if ( sessions.some( (session) => session.status === "queued" || session.status === "running" || session.status === "requires_action" || session.status === "recovering" || session.status === "waiting_capacity", ) ) { observeWorkspaceDeletePhase(input.observer, { phase: "session_fence", outcome: "active_sessions", durationSeconds: workspaceDeletePhaseDuration(sessionFenceStartedAt), inventory: { sessions: sessions.length }, }); return { status: "active_sessions" as const }; } // Session status is a projection, not execution ownership. Refuse an // inconsistent/stale projection while an exact attempt still owns work. const liveAttempts = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .for("update", { noWait: true }); if (liveAttempts.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "session_fence", outcome: "active_sessions", durationSeconds: workspaceDeletePhaseDuration(sessionFenceStartedAt), inventory: { sessions: sessions.length, live_attempts: liveAttempts.length }, }); return { status: "active_sessions" as const }; } observeWorkspaceDeletePhase(input.observer, { phase: "session_fence", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(sessionFenceStartedAt), inventory: { sessions: sessions.length, live_attempts: liveAttempts.length }, }); const runtimeOwnershipStartedAt = performance.now(); // A paid asynchronous video operation owns provider recovery outside // the originating turn. Cascading its row would lose the only stable // job/idempotency identity and could strand an already-paid result. const activeVideoGenerations = await tx .select({ id: schema.videoGenerationOperations.id }) .from(schema.videoGenerationOperations) .where( and( eq(schema.videoGenerationOperations.workspaceId, input.workspaceId), inArray(schema.videoGenerationOperations.status, [ "preparing", "prepared", "accepted", "submission_uncertain", "provider_started", "retaining", ]), ), ) .for("update", { noWait: true }); if (activeVideoGenerations.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "active_video_generations", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { active_video_generations: activeVideoGenerations.length }, }); return { status: "active_video_generations" as const }; } const [backgroundCommands] = await tx.execute<{ activeCount: number | string; }>(sql` select opengeni_private.prepare_workspace_background_command_deletion( ${input.accountId}::uuid, ${input.workspaceId}::uuid ) as "activeCount" `); if (Number(backgroundCommands?.activeCount ?? 0) > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "active_background_commands", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { active_video_generations: activeVideoGenerations.length, active_background_commands: Number(backgroundCommands?.activeCount ?? 0), }, }); return { status: "active_background_commands" as const }; } const leases = await tx .select({ liveness: schema.sandboxLeases.liveness, refcount: schema.sandboxLeases.refcount, turnHolders: schema.sandboxLeases.turnHolders, viewerHolders: schema.sandboxLeases.viewerHolders, instanceId: schema.sandboxLeases.instanceId, archiveCaptureId: schema.sandboxLeases.archiveCaptureId, reaperHoldId: schema.sandboxLeases.reaperHoldId, rotationRequestedAt: schema.sandboxLeases.rotationRequestedAt, providerDeadlineAt: schema.sandboxLeases.providerDeadlineAt, }) .from(schema.sandboxLeases) .where(eq(schema.sandboxLeases.workspaceId, input.workspaceId)) .for("update", { noWait: true }); // The workspace's compute sandboxes stay warm while idle; deleting it // ends their groups, so ask the reaper to tear them down now. await requestComputeGroupEndTx(tx, { workspaceId: input.workspaceId }); if ( leases.some( (lease) => lease.liveness !== "cold" || lease.refcount !== 0 || lease.turnHolders !== 0 || lease.viewerHolders !== 0 || lease.instanceId !== null || lease.archiveCaptureId !== null || lease.reaperHoldId !== null || lease.rotationRequestedAt !== null || lease.providerDeadlineAt !== null, ) ) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "live_sandboxes", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { sandbox_leases: leases.length }, }); return { status: "live_sandboxes" as const }; } // Counters are a fast projection. The underlying ownership ledgers are // authoritative and must independently be empty/settled before cascade // deletion can erase their provider address or mutation evidence. const holders = await tx .select({ id: schema.sandboxLeaseHolders.id }) .from(schema.sandboxLeaseHolders) .where(eq(schema.sandboxLeaseHolders.workspaceId, input.workspaceId)) .for("update", { noWait: true }); if (holders.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "live_sandboxes", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { sandbox_leases: leases.length, sandbox_holders: holders.length }, }); return { status: "live_sandboxes" as const }; } const unsettledAdmissions = await tx .select({ id: schema.sandboxWorkspaceMutationAdmissions.id }) .from(schema.sandboxWorkspaceMutationAdmissions) .where( and( eq(schema.sandboxWorkspaceMutationAdmissions.workspaceId, input.workspaceId), isNull(schema.sandboxWorkspaceMutationAdmissions.settledAt), ), ) .for("update", { noWait: true }); if (unsettledAdmissions.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "live_sandboxes", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { sandbox_leases: leases.length, sandbox_holders: holders.length, unsettled_sandbox_admissions: unsettledAdmissions.length, }, }); return { status: "live_sandboxes" as const }; } const activeProcesses = await tx .select({ id: schema.sandboxRetainedProcesses.id }) .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.state, "active"), ), ) .for("update", { noWait: true }); if (activeProcesses.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "live_sandboxes", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { active_retained_processes: activeProcesses.length }, }); return { status: "live_sandboxes" as const }; } const openPtys = await tx .select({ id: schema.sandboxPtySessions.id }) .from(schema.sandboxPtySessions) .where( and( eq(schema.sandboxPtySessions.workspaceId, input.workspaceId), eq(schema.sandboxPtySessions.status, "open"), ), ) .for("update", { noWait: true }); if (openPtys.length > 0) { observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "live_sandboxes", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { open_ptys: openPtys.length }, }); return { status: "live_sandboxes" as const }; } observeWorkspaceDeletePhase(input.observer, { phase: "runtime_ownership", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(runtimeOwnershipStartedAt), inventory: { active_video_generations: activeVideoGenerations.length, active_background_commands: Number(backgroundCommands?.activeCount ?? 0), sandbox_leases: leases.length, sandbox_holders: holders.length, unsettled_sandbox_admissions: unsettledAdmissions.length, active_retained_processes: activeProcesses.length, open_ptys: openPtys.length, }, }); const externalCleanupStartedAt = performance.now(); const schedules = await tx .select({ temporalScheduleId: schema.scheduledTasks.temporalScheduleId, }) .from(schema.scheduledTasks) .where(eq(schema.scheduledTasks.workspaceId, input.workspaceId)) .for("update", { noWait: true }); // The workspace cascade itself removes every connector/source row. // Adopt any earlier task-level receipt by completing its DB-only // connector stage before the parent disappears; the surviving row // then owns only the external Temporal deletion. await tx.execute(sql` select opengeni_private.complete_workspace_temporal_connector_cleanups( ${input.accountId}::uuid, ${input.workspaceId}::uuid ) `); const cleanupClaimId = randomUUID(); const temporalScheduleCleanups = schedules.length === 0 ? [] : await tx .insert(schema.temporalScheduleCleanupOutbox) .values( schedules.map((schedule) => ({ accountId: input.accountId, workspaceId: input.workspaceId, temporalScheduleId: schedule.temporalScheduleId, claimId: cleanupClaimId, claimUntil: sql`now() + interval '15 seconds'`, attemptCount: 1, })), ) .onConflictDoNothing({ target: schema.temporalScheduleCleanupOutbox.temporalScheduleId, }) .returning({ id: schema.temporalScheduleCleanupOutbox.id, accountId: schema.temporalScheduleCleanupOutbox.accountId, workspaceId: schema.temporalScheduleCleanupOutbox.workspaceId, temporalScheduleId: schema.temporalScheduleCleanupOutbox.temporalScheduleId, scheduledTaskId: schema.temporalScheduleCleanupOutbox.scheduledTaskId, connectorCleanupSubjectId: schema.temporalScheduleCleanupOutbox.connectorCleanupSubjectId, connectorCleanupSnapshot: schema.temporalScheduleCleanupOutbox.connectorCleanupSnapshot, connectorCleanupCompletedAt: schema.temporalScheduleCleanupOutbox.connectorCleanupCompletedAt, attemptCount: schema.temporalScheduleCleanupOutbox.attemptCount, }); await tx.execute(sql` select opengeni_private.prune_settled_cross_workspace_background_commands( ${input.accountId}::uuid, ${input.workspaceId}::uuid ) `); observeWorkspaceDeletePhase(input.observer, { phase: "external_cleanup", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(externalCleanupStartedAt), inventory: { temporal_schedules: schedules.length }, }); // Variable-set attachment guards intentionally prevent deleting a set // while any session still selects it. A workspace cascade owns both // sides, so detach those selections through the activity gate before // deleting the parent. Finalize the gate inside this transaction: the // workspace activity counter disappears with the parent cascade. const variableSetDetachStartedAt = performance.now(); // Release-N compatibility only: ordinary ORM reads no longer name // retired columns. The contract release removes this table and its // attachment guards atomically, after which detachment is unnecessary. const [retiredVariableSetSchema] = await rawRows<{ present: boolean }>( tx, sql`select pg_catalog.to_regclass('workspace_variable_sets') is not null as present`, ); if (retiredVariableSetSchema?.present) { await withRestoredSessionActivityRlsContext( tx, { accountId: input.accountId, workspaceId: input.workspaceId }, async (activityDb) => { await activityDb.execute(sql` update sessions set variable_set_ids = '[]'::jsonb, variable_set_id = null, updated_at = ${new Date().toISOString()}::timestamptz where workspace_id = ${input.workspaceId}::uuid and account_id = ${input.accountId}::uuid and variable_set_id is not null `); }, ); } observeWorkspaceDeletePhase(input.observer, { phase: "variable_set_detach", outcome: "ok", durationSeconds: workspaceDeletePhaseDuration(variableSetDetachStartedAt), }); const cascadeStartedAt = performance.now(); // The activity gate flushes deferred checks with ALL IMMEDIATE. // The cascade removes both ends of every reference between the // workspace's own tables; check those at commit, after the complete // cascade, not between rows. Activity and retention constraint // triggers stay immediate. await tx.execute(sql`select opengeni_private.defer_workspace_cascade_foreign_keys()`); const deleted = await tx .delete(schema.workspaces) .where( and( eq(schema.workspaces.id, input.workspaceId), eq(schema.workspaces.accountId, input.accountId), ), ) .returning({ id: schema.workspaces.id }); if (deleted.length !== 1) { observeWorkspaceDeletePhase(input.observer, { phase: "cascade", outcome: "not_found", durationSeconds: workspaceDeletePhaseDuration(cascadeStartedAt), }); return { status: "not_found" as const }; } observeWorkspaceDeletePhase(input.observer, { phase: "cascade", outcome: "deleted", durationSeconds: workspaceDeletePhaseDuration(cascadeStartedAt), }); return { status: "deleted" as const, temporalScheduleCleanups: temporalScheduleCleanups.map((cleanup) => ({ ...cleanup, claimId: cleanupClaimId, })), }; }), ); observeWorkspaceDeletePhase(input.observer, { phase: "transaction", outcome: result.status, durationSeconds: workspaceDeletePhaseDuration(transactionStartedAt), }); return result; } catch (error) { // The parent workspace lock deliberately blocks new FK children. Never wait // on a child row owned by a transaction that may itself be waiting for that // parent lock: fail closed and let the caller retry after live work settles. let current: unknown = error; const visited = new Set(); for (let depth = 0; depth < 8 && current && !visited.has(current); depth += 1) { visited.add(current); if ( typeof current === "object" && "code" in current && (current as { code?: unknown }).code === "55P03" ) { const result = { status: "live_sandboxes" as const }; observeWorkspaceDeletePhase(input.observer, { phase: "transaction", outcome: result.status, durationSeconds: workspaceDeletePhaseDuration(transactionStartedAt), }); return result; } current = typeof current === "object" && "cause" in current ? (current as { cause?: unknown }).cause : undefined; } observeWorkspaceDeletePhase(input.observer, { phase: "transaction", outcome: "error", durationSeconds: workspaceDeletePhaseDuration(transactionStartedAt), }); throw error; } } /** Claim a bounded cross-workspace batch after abandoned claims expire. */ export async function claimTemporalScheduleCleanups( db: Database, input: { claimId: string; limit?: number; claimSeconds?: number }, ): Promise { const rows = await rawRows<{ id: string; account_id: string; workspace_id: string; temporal_schedule_id: string; scheduled_task_id: string | null; connector_cleanup_subject_id: string | null; connector_cleanup_snapshot: unknown | null; connector_cleanup_completed_at: Date | null; attempt_count: number; }>( db, sql` select * from opengeni_private.claim_temporal_schedule_cleanups( ${input.claimId}, ${input.limit ?? 32}, ${input.claimSeconds ?? 15} ) `, ); return rows.map((row) => ({ id: row.id, accountId: row.account_id, workspaceId: row.workspace_id, temporalScheduleId: row.temporal_schedule_id, scheduledTaskId: row.scheduled_task_id, connectorCleanupSubjectId: row.connector_cleanup_subject_id, connectorCleanupSnapshot: row.connector_cleanup_snapshot, connectorCleanupCompletedAt: row.connector_cleanup_completed_at, claimId: input.claimId, attemptCount: row.attempt_count, })); } /** * Settle only the exact claimed cleanup. A null error acknowledges the * idempotent external deletion and removes the durable receipt; an error * releases it with bounded exponential backoff. */ export async function settleTemporalScheduleCleanup( db: Database, input: { id: string; claimId: string; error?: string | null }, ): Promise { const [row] = await rawRows<{ settled: boolean }>( db, sql` select opengeni_private.settle_temporal_schedule_cleanup( ${input.id}, ${input.claimId}, ${input.error ?? null} ) as settled `, ); return row?.settled === true; } export async function createApiKey( db: Database, input: { accountId: string; workspaceId?: string | null; name: string; description?: string | null; prefix: string; keyHash: string; permissions: Permission[]; expiresAt?: Date | null; credentialKind?: schema.ApiKeyCredentialKind; }, ): Promise { const workspaceId = input.workspaceId ?? null; const credentialKind = input.credentialKind ?? (workspaceId ? "workspace" : "legacy_account"); return await withRlsContext(db, { accountId: input.accountId, workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.apiKeys) .values({ accountId: input.accountId, workspaceId, name: input.name, description: input.description ?? null, credentialKind, prefix: input.prefix, keyHash: input.keyHash, permissions: input.permissions, expiresAt: input.expiresAt ?? null, }) .returning(); if (!row) { throw new Error("Failed to create API key"); } return mapApiKey(row); }); } export class OrganizationApiKeyLimitExceededError extends Error { constructor(readonly limit: number) { super(`API key limit reached (${limit})`); this.name = "OrganizationApiKeyLimitExceededError"; } } /** * Create an explicitly proven organization key under one account-scoped lock. * An authenticating organization key may open exactly one temporary overlap * slot at the configured cap so it can create a replacement before revocation. */ export async function createOrganizationApiKey( db: Database, input: { accountId: string; name: string; description?: string | null; prefix: string; keyHash: string; permissions: Permission[]; expiresAt?: Date | null; maxActiveKeys?: number | null; rotationSourceApiKeyId?: string | null; policy?: OrganizationAccessPolicy; /** The holder; omitted creates a service account named after the key. */ serviceAccountId?: string | null; createdBySubjectId?: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: null }, async (scopedDb) => { const policy = input.policy ? normalizeOrganizationAccessPolicy(input.policy) : undefined; const storedPermissions = policy?.permissions ?? input.permissions; const effective = effectiveKeyPermissions({ permissions: storedPermissions, permissionMode: policy ? "explicit" : "legacy", }); // A key creating a key (rotation) keeps it with the same service account. const [rotationHolder] = !input.serviceAccountId && input.rotationSourceApiKeyId ? await scopedDb .select({ serviceAccountId: schema.apiKeys.serviceAccountId }) .from(schema.apiKeys) .where( and( eq(schema.apiKeys.accountId, input.accountId), eq(schema.apiKeys.id, input.rotationSourceApiKeyId), ), ) : []; const holderId = input.serviceAccountId ?? rotationHolder?.serviceAccountId ?? null; const serviceAccount = holderId ? await lockOrganizationServiceAccount(scopedDb, input.accountId, holderId) : await insertOrganizationServiceAccount(scopedDb, { accountId: input.accountId, name: input.name, description: input.description ?? null, // Least privilege: admin only when the key needs it. role: permissionsBeyondServiceAccountRole("member", effective).length > 0 ? "admin" : "member", createdBySubjectId: input.createdBySubjectId ?? null, }); const beyond = permissionsBeyondServiceAccountRole(serviceAccount.role, effective); if (beyond.length > 0) throw new OrganizationServiceAccountRoleError(beyond); if (policy) await validateOrganizationApiKeyWorkspaceScope( scopedDb, input.accountId, policy.workspaceScope, ); if (input.maxActiveKeys !== null && input.maxActiveKeys !== undefined) { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-api-key:${input.accountId}`}, 0))`, ); const activePredicate = and( eq(schema.apiKeys.accountId, input.accountId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), isNull(schema.apiKeys.revokedAt), or(isNull(schema.apiKeys.expiresAt), gt(schema.apiKeys.expiresAt, new Date())), ); const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int` }) .from(schema.apiKeys) .where(activePredicate); const activeCount = Number(count); let rotationOverlapAllowed = false; if (activeCount === input.maxActiveKeys && input.rotationSourceApiKeyId) { const [rotationSource] = await scopedDb .select({ id: schema.apiKeys.id }) .from(schema.apiKeys) .where(and(activePredicate, eq(schema.apiKeys.id, input.rotationSourceApiKeyId))) .limit(1); rotationOverlapAllowed = Boolean(rotationSource); } if (activeCount >= input.maxActiveKeys && !rotationOverlapAllowed) { throw new OrganizationApiKeyLimitExceededError(input.maxActiveKeys); } } const [row] = await scopedDb .insert(schema.apiKeys) .values({ accountId: input.accountId, workspaceId: null, credentialKind: "organization", name: input.name, description: input.description ?? null, prefix: input.prefix, keyHash: input.keyHash, permissions: storedPermissions, permissionMode: policy ? "explicit" : "legacy", workspaceScope: policy?.workspaceScope.kind ?? "all", serviceAccountId: serviceAccount.id, expiresAt: input.expiresAt ?? null, }) .returning(); if (!row) throw new Error("Failed to create organization API key"); if (policy) await replaceOrganizationApiKeyWorkspaceScope( scopedDb, input.accountId, row.id, policy.workspaceScope, ); return { ...mapApiKey( row, policy?.workspaceScope.kind === "selected" ? policy.workspaceScope.workspaceIds : [], ), serviceAccount: { id: serviceAccount.id, name: serviceAccount.name, role: serviceAccount.role, }, }; }, ); } export async function listApiKeys(db: Database, workspaceId: string): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.apiKeys) .where(eq(schema.apiKeys.workspaceId, workspaceId)) .orderBy(desc(schema.apiKeys.createdAt)); return rows.map((row) => mapApiKey(row)); }); } export async function listOrganizationApiKeys(db: Database, accountId: string): Promise { return await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.apiKeys) .where( and( eq(schema.apiKeys.accountId, accountId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), ), ) .orderBy(desc(schema.apiKeys.createdAt)) .for("share"); const scopes = await readOrganizationApiKeyWorkspaceScopes(scopedDb, rows); const holders = await serviceAccountsForKeys(scopedDb, rows); return rows.map((row) => withHolder(mapApiKey(row, scopes.get(row.id)), row, holders)); }); } export async function getOrganizationApiKey( db: Database, accountId: string, keyId: string, ): Promise { return withRlsContext(db, { accountId, workspaceId: null }, async (tx) => { const [row] = await tx .select() .from(schema.apiKeys) .where( and( eq(schema.apiKeys.accountId, accountId), eq(schema.apiKeys.id, keyId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), ), ) .for("share"); if (!row) return null; const scopes = await readOrganizationApiKeyWorkspaceScopes(tx, [row]); return withHolder( mapApiKey(row, scopes.get(row.id)), row, await serviceAccountsForKeys(tx, [row]), ); }); } export async function updateOrganizationApiKey( db: Database, accountId: string, keyId: string, input: UpdateOrganizationApiKeyRequest, ): Promise { return withRlsContext(db, { accountId, workspaceId: null }, async (tx) => { const [prior] = await tx .select() .from(schema.apiKeys) .where( and( eq(schema.apiKeys.accountId, accountId), eq(schema.apiKeys.id, keyId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), ), ) .for("update"); if (!prior) return null; const policy = input.policy ? normalizeOrganizationAccessPolicy(input.policy) : undefined; if (policy) await validateOrganizationApiKeyWorkspaceScope(tx, accountId, policy.workspaceScope); if (policy && prior.serviceAccountId) { const holder = await lockOrganizationServiceAccount(tx, accountId, prior.serviceAccountId); const beyond = permissionsBeyondServiceAccountRole(holder.role, policy.permissions); if (beyond.length > 0) throw new OrganizationServiceAccountRoleError(beyond); } const [row] = await tx .update(schema.apiKeys) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.description !== undefined ? { description: input.description } : {}), ...(policy ? { permissions: policy.permissions, permissionMode: "explicit" as const, workspaceScope: policy.workspaceScope.kind, } : {}), updatedAt: new Date(), }) .where(and(eq(schema.apiKeys.accountId, accountId), eq(schema.apiKeys.id, keyId))) .returning(); if (!row) return null; if (policy) await replaceOrganizationApiKeyWorkspaceScope(tx, accountId, keyId, policy.workspaceScope); const scopes = await readOrganizationApiKeyWorkspaceScopes(tx, [row]); return withHolder( mapApiKey(row, scopes.get(row.id)), row, await serviceAccountsForKeys(tx, [row]), ); }); } export async function countActiveApiKeysForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int`, }) .from(schema.apiKeys) .where( and( eq(schema.apiKeys.workspaceId, workspaceId), sql`${schema.apiKeys.revokedAt} is null`, sql`(${schema.apiKeys.expiresAt} is null or ${schema.apiKeys.expiresAt} > now())`, ), ); return Number(count); }); } export async function countActiveOrganizationApiKeysForAccount( db: Database, accountId: string, ): Promise { return await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int`, }) .from(schema.apiKeys) .where( and( eq(schema.apiKeys.accountId, accountId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), sql`${schema.apiKeys.revokedAt} is null`, sql`(${schema.apiKeys.expiresAt} is null or ${schema.apiKeys.expiresAt} > now())`, ), ); return Number(count); }); } export async function revokeApiKey( db: Database, workspaceId: string, apiKeyId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .update(schema.apiKeys) .set({ revokedAt: new Date(), updatedAt: new Date(), }) .where(and(eq(schema.apiKeys.workspaceId, workspaceId), eq(schema.apiKeys.id, apiKeyId))) .returning(); if (!row) { throw new Error(`API key not found: ${apiKeyId}`); } return mapApiKey(row); }); } export async function revokeOrganizationApiKey( db: Database, accountId: string, apiKeyId: string, ): Promise { return await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => { const [row] = await scopedDb .update(schema.apiKeys) .set({ revokedAt: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.apiKeys.accountId, accountId), isNull(schema.apiKeys.workspaceId), eq(schema.apiKeys.credentialKind, "organization"), eq(schema.apiKeys.id, apiKeyId), ), ) .returning(); if (!row) return null; const scopes = await readOrganizationApiKeyWorkspaceScopes(scopedDb, [row]); return withHolder( mapApiKey(row, scopes.get(row.id)), row, await serviceAccountsForKeys(scopedDb, [row]), ); }); } export async function findActiveApiKeyByHash( db: Database, keyHash: string, ): Promise< | (ApiKey & { credentialKind: schema.ApiKeyCredentialKind; /** Personal keys: the person the key acts as and the most it may do. */ ownerSubjectId: string | null; ownerPermissions: string[] | null; }) | null > { const authenticated = await db.transaction( async (tx) => { await tx.execute(sql`select set_config('opengeni.api_key_hash', ${keyHash}, true)`); const [row] = await tx .select() .from(schema.apiKeys) .where( and( eq(schema.apiKeys.keyHash, keyHash), sql`${schema.apiKeys.revokedAt} is null`, sql`(${schema.apiKeys.expiresAt} is null or ${schema.apiKeys.expiresAt} > now())`, ), ) .limit(1); if (!row) { return null; } // Hash visibility proves this account. The join-table hash lane requires // both settings and remains bounded to this key, not sibling key scopes. if ( (row.credentialKind === "organization" || row.credentialKind === "personal") && row.workspaceScope === "selected" ) { await tx.execute(sql`select set_config('opengeni.account_id', ${row.accountId}, true)`); } const scopes = await readOrganizationApiKeyWorkspaceScopes(tx, [row]); return { ...mapApiKey(row, scopes.get(row.id)), ...(row.credentialKind === "personal" ? { workspaceScope: personalApiKeyAccess(row, scopes.get(row.id)).workspaceScope } : {}), credentialKind: row.credentialKind, ownerSubjectId: row.ownerSubjectId, ownerPermissions: row.ownerPermissions, }; }, { isolationLevel: "repeatable read", accessMode: "read only" }, ); if (!authenticated) return null; // Read the key and its scope rows from one snapshot without locking or // dirtying the key. Revocation/expiry is checked on every authentication; // no authorization result is cached between requests. // Last-use telemetry is not an authorization fence. Coalesce it across // replicas to one update per key per minute, outside the read-only snapshot. const now = new Date(); const lastUseBefore = new Date(now.getTime() - 60_000); if (!authenticated.lastUsedAt || Date.parse(authenticated.lastUsedAt) < lastUseBefore.getTime()) { try { await db.transaction(async (tx) => { await tx.execute(sql`select set_config('opengeni.api_key_hash', ${keyHash}, true), set_config('opengeni.account_id', ${authenticated.accountId}, true)`); const [touched] = await tx .update(schema.apiKeys) .set({ lastUsedAt: now }) .where( and( sql`${schema.apiKeys.id} = (select id from ${schema.apiKeys} where id = ${authenticated.id}::uuid and revoked_at is null and (expires_at is null or expires_at > now()) and (last_used_at is null or last_used_at < ${lastUseBefore.toISOString()}::timestamptz) for update skip locked)`, ), ) .returning({ lastUsedAt: schema.apiKeys.lastUsedAt }); if (touched?.lastUsedAt) authenticated.lastUsedAt = touched.lastUsedAt.toISOString(); }); } catch (error) { // Never expose hashes, SQL parameters or credentials in diagnostics. console.warn("API key last-use telemetry update failed", { keyId: authenticated.id, code: nestedPostgresSqlState(error), }); } } return authenticated; } export async function findActiveWorkspaceApiKeyById( db: Database, input: { accountId: string; workspaceId: string; apiKeyId: string }, ): Promise<(ApiKey & { credentialKind: schema.ApiKeyCredentialKind }) | null> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.apiKeys) .where( and( eq(schema.apiKeys.id, input.apiKeyId), eq(schema.apiKeys.accountId, input.accountId), sql`${schema.apiKeys.revokedAt} is null`, sql`(${schema.apiKeys.expiresAt} is null or ${schema.apiKeys.expiresAt} > now())`, or( eq(schema.apiKeys.workspaceId, input.workspaceId), isNull(schema.apiKeys.workspaceId), ), ), ) .limit(1) .for("share"); if (!row) { return null; } if (row.workspaceId !== null && row.workspaceId !== input.workspaceId) { return null; } if ( row.workspaceId === null && (row.credentialKind !== "organization" || !(await organizationApiKeyAllowsWorkspace(scopedDb, row, input.workspaceId))) ) return null; const scopes = await readOrganizationApiKeyWorkspaceScopes(scopedDb, [row]); return { ...mapApiKey(row, scopes.get(row.id)), credentialKind: row.credentialKind, }; }, ); } export type GitHubInstallation = { id: string; accountId: string; workspaceId: string; installationId: number; githubAccountId: number | null; accountLogin: string | null; accountType: string | null; repositoryScope: GitHubRepositoryScope; linkedBySubjectId: string | null; githubActorId: number | null; githubActorLogin: string | null; authorityKind: GitHubInstallationAuthorityKind | null; authorityCheckedAt: string | null; authorityExpiresAt: string | null; authorityNonce: string | null; createdAt: string; updatedAt: string; }; export type GitHubInstallationAccess = GitHubInstallation & { repositoryIds: number[]; }; export class GitHubInstallationAuthorityCommitError extends Error { constructor() { super("GitHub installation authority expired before the binding transaction completed"); } } const githubInstallationAuthorityMaxAgeMs = 10 * 60_000; /** * True only for a binding created by the owner-authority transaction. Legacy * installation rows remain visible for audit/unlink, but can never make a * workspace healthy, enumerate repositories, or authorize a token mint. * * `authorityExpiresAt` is the expiry of the consumed proof, not of the durable * delegation. A binding remains delegated after that instant; GitHub's live * installation/repository checks govern its ongoing usability. */ export function hasAuditableGitHubInstallationAuthority( installation: GitHubInstallationAccess, ): boolean { return ( installation.repositoryIds.length > 0 && installation.repositoryIds.every((id) => Number.isSafeInteger(id) && id > 0) && hasGitHubInstallationOwnerAuthority(installation) ); } /** * The owner-authority proof of a binding, whatever its repository allowlist * currently holds. A binding with this proof follows GitHub's repository * selection for the installation (applyGitHubInstallationRepositoryObservation); * one that GitHub has left with no repositories is unusable until GitHub * shares some again, without needing a new proof. */ export function hasGitHubInstallationOwnerAuthority(installation: GitHubInstallation): boolean { const checkedAt = installation.authorityCheckedAt ? Date.parse(installation.authorityCheckedAt) : Number.NaN; const expiresAt = installation.authorityExpiresAt ? Date.parse(installation.authorityExpiresAt) : Number.NaN; const common = installation.repositoryScope === "selected" && installation.githubAccountId !== null && Number.isSafeInteger(installation.githubAccountId) && installation.githubAccountId > 0 && Boolean(installation.accountLogin) && installation.githubActorId !== null && Number.isSafeInteger(installation.githubActorId) && installation.githubActorId > 0 && Boolean(installation.githubActorLogin) && Boolean(installation.linkedBySubjectId) && Boolean(installation.authorityNonce) && Number.isFinite(checkedAt) && Number.isFinite(expiresAt) && checkedAt < expiresAt; if (!common) { return false; } return installation.authorityKind === "personal_owner" ? installation.accountType === "User" && installation.githubActorId === installation.githubAccountId : installation.authorityKind === "organization_owner" && installation.accountType === "Organization"; } export async function upsertGitHubInstallation( db: Database, input: { accountId: string; workspaceId: string; installationId: number; accountLogin?: string | null; accountType?: string | null; linkedBySubjectId?: string | null; /** The deployment's event route secret: GitHub event routes are recomputed with it. */ eventRouteSecret: Uint8Array | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.githubInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, installationId: input.installationId, accountLogin: input.accountLogin ?? null, accountType: input.accountType ?? null, linkedBySubjectId: input.linkedBySubjectId ?? null, }) .onConflictDoUpdate({ target: [ schema.githubInstallations.workspaceId, schema.githubInstallations.installationId, ], set: { accountId: input.accountId, accountLogin: input.accountLogin ?? null, accountType: input.accountType ?? null, ...(input.linkedBySubjectId !== undefined ? { linkedBySubjectId: input.linkedBySubjectId } : {}), updatedAt: new Date(), }, // This legacy metadata helper cannot mutate an owner-authorized row. // New bindings use bindAuthorizedGitHubInstallationRepositories. setWhere: isNull(schema.githubInstallations.authorityNonce), }) .returning(); if (!row) { throw new Error("Failed to upsert GitHub installation"); } await syncGitHubEventRoutes(scopedDb, input.workspaceId, input.eventRouteSecret); return mapGitHubInstallation(row); }, ); } export async function bindGitHubInstallationRepositories( db: Database, input: { accountId: string; workspaceId: string; installationId: number; accountLogin?: string | null; accountType?: string | null; linkedBySubjectId: string; repositoryIds: number[]; /** The deployment's event route secret: GitHub event routes are recomputed with it. */ eventRouteSecret: Uint8Array | null; }, ): Promise { if (!Number.isSafeInteger(input.installationId) || input.installationId <= 0) { throw new Error("GitHub installation id must be a positive safe integer"); } const repositoryIds = [...new Set(input.repositoryIds)]; if ( repositoryIds.length === 0 || repositoryIds.some((id) => !Number.isSafeInteger(id) || id <= 0) ) { throw new Error("GitHub repository ids must contain at least one positive safe integer"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [row] = await tx .insert(schema.githubInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, installationId: input.installationId, accountLogin: input.accountLogin ?? null, accountType: input.accountType ?? null, repositoryScope: "selected", linkedBySubjectId: input.linkedBySubjectId, }) .onConflictDoUpdate({ target: [ schema.githubInstallations.workspaceId, schema.githubInstallations.installationId, ], set: { accountId: input.accountId, accountLogin: input.accountLogin ?? null, accountType: input.accountType ?? null, repositoryScope: "selected", linkedBySubjectId: input.linkedBySubjectId, updatedAt: new Date(), }, // Preserve the immutable authority + allowlist audit boundary. setWhere: isNull(schema.githubInstallations.authorityNonce), }) .returning(); if (!row) { throw new Error("Failed to bind GitHub installation"); } await tx .delete(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, input.workspaceId), eq(schema.githubInstallationRepositories.installationId, input.installationId), ), ); for (let offset = 0; offset < repositoryIds.length; offset += 1_000) { await tx.insert(schema.githubInstallationRepositories).values( repositoryIds.slice(offset, offset + 1_000).map((repositoryId) => ({ accountId: input.accountId, workspaceId: input.workspaceId, installationId: input.installationId, repositoryId, })), ); } await syncGitHubEventRoutes(tx, input.workspaceId, input.eventRouteSecret); return { ...mapGitHubInstallation(row), repositoryIds }; }), ); } export async function bindAuthorizedGitHubInstallationRepositories( db: Database, input: { accountId: string; workspaceId: string; installationId: number; githubAccountId: number; accountLogin: string | null; accountType: string | null; linkedBySubjectId: string; githubActorId: number; githubActorLogin: string; authorityKind: GitHubInstallationAuthorityKind; authorityCheckedAt: Date; authorityExpiresAt: Date; authorityNonce: string; repositoryIds: number[]; /** The deployment's event route secret: GitHub event routes are recomputed with it. */ eventRouteSecret: Uint8Array | null; }, ): Promise { if (!Number.isSafeInteger(input.installationId) || input.installationId <= 0) { throw new Error("GitHub installation id must be a positive safe integer"); } if (!Number.isSafeInteger(input.githubAccountId) || input.githubAccountId <= 0) { throw new Error("GitHub account id must be a positive safe integer"); } if (!Number.isSafeInteger(input.githubActorId) || input.githubActorId <= 0) { throw new Error("GitHub actor id must be a positive safe integer"); } const authorityCheckedAtMs = input.authorityCheckedAt.getTime(); const authorityExpiresAtMs = input.authorityExpiresAt.getTime(); if ( !Number.isFinite(authorityCheckedAtMs) || !Number.isFinite(authorityExpiresAtMs) || authorityCheckedAtMs >= authorityExpiresAtMs || authorityExpiresAtMs - authorityCheckedAtMs > githubInstallationAuthorityMaxAgeMs || !input.authorityNonce || !input.githubActorLogin.trim() || !input.accountLogin?.trim() || !input.linkedBySubjectId.trim() || (input.authorityKind !== "personal_owner" && input.authorityKind !== "organization_owner") || (input.authorityKind === "personal_owner" && (input.accountType !== "User" || input.githubActorId !== input.githubAccountId)) || (input.authorityKind === "organization_owner" && input.accountType !== "Organization") ) { throw new Error("GitHub installation authority proof is invalid or expired"); } const repositoryIds = [...new Set(input.repositoryIds)]; if ( repositoryIds.length === 0 || repositoryIds.length !== input.repositoryIds.length || repositoryIds.some((id) => !Number.isSafeInteger(id) || id <= 0) ) { throw new Error( "GitHub repository ids must be a nonempty, unique list of positive safe integers", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await assertGitHubAuthorityWindowOpen( tx, input.authorityCheckedAt, input.authorityExpiresAt, ); await tx .delete(schema.integrationOauthStateNonces) .where( and( eq(schema.integrationOauthStateNonces.workspaceId, input.workspaceId), lt(schema.integrationOauthStateNonces.expiresAt, input.authorityCheckedAt), ), ); const consumed = await tx .insert(schema.integrationOauthStateNonces) .values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.linkedBySubjectId, nonce: input.authorityNonce, expiresAt: input.authorityExpiresAt, usedAt: input.authorityCheckedAt, }) .onConflictDoNothing({ target: schema.integrationOauthStateNonces.nonce, }) .returning({ nonce: schema.integrationOauthStateNonces.nonce }); if (consumed.length === 0) { return null; } // The proof's repository list was read before `authorityCheckedAt`. If // GitHub changed the binding's repositories since (a removal or a // newer list moved the fence past the proof), keep only proof // repositories the binding still has; the sync that follows the bind // adds any GitHub shares now. A repository GitHub removed within the // hold window stays out either way. const [existing] = await tx .select({ updatedAt: schema.githubInstallations.updatedAt }) .from(schema.githubInstallations) .where( and( eq(schema.githubInstallations.workspaceId, input.workspaceId), eq(schema.githubInstallations.installationId, input.installationId), ), ) .limit(1) .for("update"); let boundRepositoryIds = repositoryIds; if (existing) { const held = await recentGitHubRepositoryRemovals( tx, input.workspaceId, input.installationId, input.authorityCheckedAt, ); let current: Set | null = null; if (existing.updatedAt.getTime() > authorityCheckedAtMs) { current = new Set( ( await tx .select({ repositoryId: schema.githubInstallationRepositories.repositoryId }) .from(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, input.workspaceId), eq( schema.githubInstallationRepositories.installationId, input.installationId, ), ), ) ).map((repository) => repository.repositoryId), ); } boundRepositoryIds = repositoryIds.filter( (id) => !held.has(id) && (current === null || current.has(id)), ); } const [row] = await tx .insert(schema.githubInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, installationId: input.installationId, githubAccountId: input.githubAccountId, accountLogin: input.accountLogin, accountType: input.accountType, repositoryScope: "selected", linkedBySubjectId: input.linkedBySubjectId, githubActorId: input.githubActorId, githubActorLogin: input.githubActorLogin, authorityKind: input.authorityKind, authorityCheckedAt: input.authorityCheckedAt, authorityExpiresAt: input.authorityExpiresAt, authorityNonce: input.authorityNonce, }) .onConflictDoUpdate({ target: [ schema.githubInstallations.workspaceId, schema.githubInstallations.installationId, ], set: { accountId: input.accountId, githubAccountId: input.githubAccountId, accountLogin: input.accountLogin, accountType: input.accountType, repositoryScope: "selected", linkedBySubjectId: input.linkedBySubjectId, githubActorId: input.githubActorId, githubActorLogin: input.githubActorLogin, authorityKind: input.authorityKind, authorityCheckedAt: input.authorityCheckedAt, authorityExpiresAt: input.authorityExpiresAt, authorityNonce: input.authorityNonce, // `updated_at` is the binding's ordering fence for GitHub's // repository lists: a re-bind never moves it back. updatedAt: sql`greatest(${schema.githubInstallations.updatedAt}, ${input.authorityCheckedAt.toISOString()}::timestamptz)`, }, }) .returning(); if (!row) { throw new Error("Failed to bind GitHub installation"); } await tx .delete(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, input.workspaceId), eq(schema.githubInstallationRepositories.installationId, input.installationId), ), ); for (let offset = 0; offset < boundRepositoryIds.length; offset += 1_000) { await tx.insert(schema.githubInstallationRepositories).values( boundRepositoryIds.slice(offset, offset + 1_000).map((repositoryId) => ({ accountId: input.accountId, workspaceId: input.workspaceId, installationId: input.installationId, repositoryId, })), ); } // Recheck against the database clock after all writes. Throwing here // rolls the transaction back if the proof expired while it was being // committed, so no partial nonce or binding can survive. await assertGitHubAuthorityWindowOpen( tx, input.authorityCheckedAt, input.authorityExpiresAt, ); await syncGitHubEventRoutes(tx, input.workspaceId, input.eventRouteSecret); return { ...mapGitHubInstallation(row), repositoryIds: boundRepositoryIds }; }), ); } async function assertGitHubAuthorityWindowOpen( tx: Database, checkedAt: Date, expiresAt: Date, ): Promise { // postgres.js does not serialize JavaScript Date instances passed through // raw Drizzle SQL. Bind the already-validated ISO timestamp representation // and retain PostgreSQL's timestamptz/database-clock authority checks. const checkedAtIso = checkedAt.toISOString(); const expiresAtIso = expiresAt.toISOString(); const result = await tx.execute<{ valid: boolean }>(sql` select ( ${checkedAtIso}::timestamptz <= clock_timestamp() and clock_timestamp() < ${expiresAtIso}::timestamptz and ${expiresAtIso}::timestamptz <= ${checkedAtIso}::timestamptz + interval '10 minutes' ) as valid `); if (result[0]?.valid !== true) { throw new GitHubInstallationAuthorityCommitError(); } } export async function listGitHubInstallationsForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.githubInstallations) .where(eq(schema.githubInstallations.workspaceId, workspaceId)) .orderBy(desc(schema.githubInstallations.updatedAt)); return rows.map(mapGitHubInstallation); }); } export async function listGitHubInstallationIdsForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ installationId: schema.githubInstallations.installationId }) .from(schema.githubInstallations) .where(eq(schema.githubInstallations.workspaceId, workspaceId)) .orderBy(desc(schema.githubInstallations.updatedAt)); return rows.map((row) => row.installationId); }); } export async function listGitHubInstallationAccessForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [installations, repositories] = await Promise.all([ scopedDb .select() .from(schema.githubInstallations) .where(eq(schema.githubInstallations.workspaceId, workspaceId)) .orderBy(desc(schema.githubInstallations.updatedAt)), scopedDb .select({ installationId: schema.githubInstallationRepositories.installationId, repositoryId: schema.githubInstallationRepositories.repositoryId, }) .from(schema.githubInstallationRepositories) .where(eq(schema.githubInstallationRepositories.workspaceId, workspaceId)), ]); const repositoriesByInstallation = new Map(); for (const repository of repositories) { const ids = repositoriesByInstallation.get(repository.installationId) ?? []; ids.push(repository.repositoryId); repositoriesByInstallation.set(repository.installationId, ids); } return installations.map((installation) => ({ ...mapGitHubInstallation(installation), repositoryIds: repositoriesByInstallation.get(installation.installationId) ?? [], })); }); } export async function areGitHubRepositoriesAllowedForWorkspace( db: Database, workspaceId: string, installationId: number, repositoryIds: number[], ): Promise { const requestedIds = [...new Set(repositoryIds)]; if (requestedIds.length === 0) { return false; } const allowed = await listAllowedGitHubRepositoryIdsForWorkspace( db, workspaceId, installationId, requestedIds, ); return allowed.length === requestedIds.length; } /** Per-repository decisions under the same workspace and audited installation * authority as the all-or-nothing allowlist check. Never grants installation * authority merely because a repository row exists. */ export async function listAllowedGitHubRepositoryIdsForWorkspace( db: Database, workspaceId: string, installationId: number, repositoryIds: number[], ): Promise { const requestedIds = [...new Set(repositoryIds)]; if (requestedIds.length === 0) return []; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [installation] = await scopedDb .select() .from(schema.githubInstallations) .where( and( eq(schema.githubInstallations.workspaceId, workspaceId), eq(schema.githubInstallations.installationId, installationId), ), ) .limit(1); if (!installation) { return []; } const allowed = await scopedDb .select({ repositoryId: schema.githubInstallationRepositories.repositoryId, }) .from(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, workspaceId), eq(schema.githubInstallationRepositories.installationId, installationId), inArray(schema.githubInstallationRepositories.repositoryId, requestedIds), ), ); if ( !hasAuditableGitHubInstallationAuthority({ ...mapGitHubInstallation(installation), repositoryIds: allowed.map((row) => row.repositoryId), }) ) return []; const allowedIds = new Set(allowed.map((row) => row.repositoryId)); return requestedIds.filter((id) => allowedIds.has(id)); }); } export async function deleteGitHubInstallationBinding( db: Database, input: { accountId: string; workspaceId: string; installationId: number; /** The deployment's event route secret: GitHub event routes are recomputed with it. */ eventRouteSecret: Uint8Array | null; /** Who removed the installation from the workspace: audited in the same transaction. */ audit?: DisconnectAuditActor | null; /** * The installation that replaces this one (a reinstall on the same GitHub * account). Its approval choices move to the replacement in the same * transaction; a choice already made there wins. */ replacedByInstallationId?: number | undefined; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .delete(schema.githubInstallations) .where( and( eq(schema.githubInstallations.workspaceId, input.workspaceId), eq(schema.githubInstallations.installationId, input.installationId), ), ) .returning({ id: schema.githubInstallations.id }); await syncGitHubEventRoutes(scopedDb, input.workspaceId, input.eventRouteSecret); const replacedBy = input.replacedByInstallationId; const moved = rows.length > 0 && replacedBy !== undefined && replacedBy !== input.installationId ? await moveConnectorActionPoliciesInScope(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, fromConnectionId: `github-app:${input.installationId}`, toConnectionId: `github-app:${replacedBy}`, auditSubjectId: input.audit?.subjectId ?? null, }) : null; if (input.audit && rows.length > 0) { await insertDisconnectAuditEventInScope(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, action: CONNECTION_DISCONNECTED_AUDIT_ACTION, actor: input.audit, target: { type: "github_installation", id: String(input.installationId), provider: "github", providerDomain: "github.com", }, ...(moved ? { details: { replacedByInstallationId: String(replacedBy), approvalPoliciesMoved: moved.movedPolicyIds.length, approvalPoliciesRemoved: moved.removedPolicyIds, }, } : {}), }); } return rows.length > 0; }, ); } /** * Moves one connection's approval choices to the connection that replaced it, * in the caller's scoped transaction, and removes them from the old one. A * choice already made on the new connection wins. Moved rows keep who created * and last changed them, and when; the actor doing the move is audited. */ async function moveConnectorActionPoliciesInScope( scopedDb: Database, input: { accountId: string; workspaceId: string; fromConnectionId: string; toConnectionId: string; auditSubjectId: string | null; }, ): Promise<{ movedPolicyIds: string[]; removedPolicyIds: string[] }> { const fromConnection = and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.fromConnectionId), ); const previous = await scopedDb .select() .from(schema.connectorActionPolicies) .where(fromConnection) .orderBy(asc(schema.connectorActionPolicies.id)) .for("update"); if (previous.length === 0) return { movedPolicyIds: [], removedPolicyIds: [] }; const moved: Array = []; for (let offset = 0; offset < previous.length; offset += 128) { const batch = previous.slice(offset, offset + 128); const inserted = await scopedDb .insert(schema.connectorActionPolicies) .values( batch.map((policy) => ({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.toConnectionId, serverId: policy.serverId, toolName: policy.toolName, actionName: policy.actionName, policy: policy.policy, createdBySubjectId: policy.createdBySubjectId, updatedBySubjectId: policy.updatedBySubjectId, createdAt: policy.createdAt, updatedAt: policy.updatedAt, })), ) .onConflictDoNothing({ target: [ schema.connectorActionPolicies.workspaceId, schema.connectorActionPolicies.connectionId, schema.connectorActionPolicies.serverId, schema.connectorActionPolicies.toolName, schema.connectorActionPolicies.actionName, ], }) .returning(); const scope = (policy: { serverId: string; toolName: string; actionName: string }) => JSON.stringify([policy.serverId, policy.toolName, policy.actionName]); const sources = new Map(batch.map((policy) => [scope(policy), policy.id])); for (const row of inserted) moved.push({ ...row, from: sources.get(scope(row))! }); } const removed = await scopedDb .delete(schema.connectorActionPolicies) .where(fromConnection) .returning({ id: schema.connectorActionPolicies.id }); if (input.auditSubjectId && moved.length > 0) { for (let offset = 0; offset < moved.length; offset += 128) await scopedDb.insert(schema.auditEvents).values( moved.slice(offset, offset + 128).map((row) => withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.auditSubjectId!, action: "connector.action.policy_changed", targetType: "connector_action_policy", targetId: row.id, metadata: { connectionId: row.connectionId, serverId: row.serverId, toolName: row.toolName, actionName: row.actionName, policy: row.policy, version: row.version, previousPolicy: null, previousVersion: null, movedFromConnectionId: input.fromConnectionId, movedFromPolicyId: row.from, }, }, "metadata", "metadataCodecVersion", ), ), ); } return { movedPolicyIds: moved.map((row) => row.id), removedPolicyIds: removed.map((row) => row.id), }; } /** * Every workspace bound to one GitHub App installation, across accounts (the * installation lane of migration 1293: only that installation's binding rows * are visible). Used to apply a verified GitHub webhook to each workspace; * the writes then run in each workspace's own RLS scope. */ export async function listGitHubInstallationBindingWorkspaces( db: Database, installationId: number, ): Promise> { if (!Number.isSafeInteger(installationId) || installationId <= 0) return []; return await db.transaction(async (raw) => { const tx = raw as unknown as Database; await tx.execute( sql`select set_config('opengeni.github_installation_id', ${String(installationId)}, true)`, ); const rows = await tx .select({ accountId: schema.githubInstallations.accountId, workspaceId: schema.githubInstallations.workspaceId, }) .from(schema.githubInstallations) .where(eq(schema.githubInstallations.installationId, installationId)) .orderBy(schema.githubInstallations.workspaceId); // A caller's outer transaction must not keep the installation lane open. await tx.execute(sql`select set_config('opengeni.github_installation_id', '', true)`); return rows; }); } /** * How long a repository GitHub reported removed from an installation stays * out of the lists read after the removal (GitHub's list can lag its webhook). */ export const GITHUB_REMOVED_REPOSITORY_HOLD_MS = 5 * 60_000; /** * Repositories GitHub reported removed from this binding too recently for a * list read at `observedAt` to add back, with their removal times. Markers * past the window are dropped. */ async function recentGitHubRepositoryRemovals( scopedDb: Database, workspaceId: string, installationId: number, observedAt: Date, ): Promise> { const binding = and( eq(schema.githubInstallationRepositoryRemovals.workspaceId, workspaceId), eq(schema.githubInstallationRepositoryRemovals.installationId, installationId), ); const holdStart = new Date(observedAt.getTime() - GITHUB_REMOVED_REPOSITORY_HOLD_MS); await scopedDb .delete(schema.githubInstallationRepositoryRemovals) .where(and(binding, lte(schema.githubInstallationRepositoryRemovals.removedAt, holdStart))); const rows = await scopedDb .select({ repositoryId: schema.githubInstallationRepositoryRemovals.repositoryId, removedAt: schema.githubInstallationRepositoryRemovals.removedAt, }) .from(schema.githubInstallationRepositoryRemovals) .where(binding); return new Map(rows.map((row) => [row.repositoryId, row.removedAt])); } /** * What Opengeni learned from GitHub about one installation's repositories. * * - `mirror`: the complete list GitHub returned for the installation, read at * `observedAt` (taken before the request was sent). It replaces the * workspace's allowlist, adding repositories GitHub now shares (for an * "All repositories" installation, every new repository) and dropping the * rest. A list read before the binding last changed is ignored, so a slow * or cached read never undoes a newer bind, removal or list. * - `remove`: repositories GitHub reported as no longer shared (or "all", for * a deleted installation). Removals apply at once, whatever their order, * fence out any list read before them, and keep the repositories out of * lists read within `GITHUB_REMOVED_REPOSITORY_HOLD_MS` after them. */ export type GitHubInstallationRepositoryObservation = | { kind: "mirror"; repositoryIds: readonly number[]; observedAt: Date } | { kind: "remove"; repositoryIds: readonly number[] | "all"; observedAt: Date }; export type GitHubInstallationRepositoryObservationResult = { /** False when a mirror was older than the binding and left it unchanged. */ applied: boolean; /** * Set when a list named repositories a recent removal still holds out: * when the first of those holds ends, a list read again can add it. */ heldUntil?: Date; changed: boolean; added: number[]; removed: number[]; repositoryIds: number[]; }; /** * Bring one workspace's allowlist for an installation in line with GitHub. * * Only a binding made with an owner-authority proof follows GitHub's list: * the owner who bound the installation delegated "the repositories this * installation shares", and GitHub's later selection is that delegation. * GitHub's removals narrow every binding, including legacy rows without a * proof. The proof, its audit fields and the binding's lifecycle checks are * untouched. A workspace never gains a repository GitHub does not list for the * installation. Returns null when the workspace has no such binding (or, for * a list, no owner proof). */ export async function applyGitHubInstallationRepositoryObservation( db: Database, input: { accountId: string; workspaceId: string; installationId: number; observation: GitHubInstallationRepositoryObservation; }, ): Promise { const { observation } = input; const observedAtMs = observation.observedAt.getTime(); if (!Number.isFinite(observedAtMs)) { throw new Error("GitHub repository observation time is invalid"); } const validId = (id: number) => Number.isSafeInteger(id) && id > 0; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.githubInstallations) .where( and( eq(schema.githubInstallations.workspaceId, input.workspaceId), eq(schema.githubInstallations.installationId, input.installationId), ), ) .limit(1) .for("update"); // Only an owner-proved binding follows GitHub's list; GitHub's // removals narrow every binding. if ( !row || (observation.kind === "mirror" && !hasGitHubInstallationOwnerAuthority(mapGitHubInstallation(row))) ) { return null; } const current = ( await scopedDb .select({ repositoryId: schema.githubInstallationRepositories.repositoryId }) .from(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, input.workspaceId), eq(schema.githubInstallationRepositories.installationId, input.installationId), ), ) ).map((repository) => repository.repositoryId); const currentSet = new Set(current); // GitHub sends a webhook after its change, and a bind's proof read its list // before the bind: a list read at or after the fence is at least as new. if (observation.kind === "mirror" && observedAtMs < row.updatedAt.getTime()) { return { applied: false, changed: false, added: [], removed: [], repositoryIds: [...current].sort((left, right) => left - right), }; } let target: Set; let heldUntilMs: number | null = null; if (observation.kind === "mirror") { // GitHub's list can lag its own webhook: a repository it reported // removed is not added back by a list read within the hold window. const held = await recentGitHubRepositoryRemovals( scopedDb, input.workspaceId, input.installationId, observation.observedAt, ); target = new Set(observation.repositoryIds.filter((id) => validId(id) && !held.has(id))); for (const id of observation.repositoryIds) { const removedAt = held.get(id); if (!removedAt) continue; const until = removedAt.getTime() + GITHUB_REMOVED_REPOSITORY_HOLD_MS; if (heldUntilMs === null || until < heldUntilMs) heldUntilMs = until; } } else if (observation.repositoryIds === "all") { target = new Set(); } else { const removed = new Set(observation.repositoryIds); target = new Set(current.filter((id) => !removed.has(id))); } const removed = current.filter((id) => !target.has(id)); const added = [...target].filter((id) => !currentSet.has(id)); for (let offset = 0; offset < removed.length; offset += 1_000) { await scopedDb .delete(schema.githubInstallationRepositories) .where( and( eq(schema.githubInstallationRepositories.workspaceId, input.workspaceId), eq(schema.githubInstallationRepositories.installationId, input.installationId), inArray( schema.githubInstallationRepositories.repositoryId, removed.slice(offset, offset + 1_000), ), ), ); } for (let offset = 0; offset < added.length; offset += 1_000) { await scopedDb .insert(schema.githubInstallationRepositories) .values( added.slice(offset, offset + 1_000).map((repositoryId) => ({ accountId: row.accountId, workspaceId: input.workspaceId, installationId: input.installationId, repositoryId, })), ) .onConflictDoNothing(); } if (observation.kind === "remove" && observation.repositoryIds !== "all") { const removedIds = [...new Set(observation.repositoryIds.filter(validId))]; for (let offset = 0; offset < removedIds.length; offset += 1_000) { await scopedDb .insert(schema.githubInstallationRepositoryRemovals) .values( removedIds.slice(offset, offset + 1_000).map((repositoryId) => ({ accountId: row.accountId, workspaceId: input.workspaceId, installationId: input.installationId, repositoryId, removedAt: observation.observedAt, })), ) .onConflictDoUpdate({ target: [ schema.githubInstallationRepositoryRemovals.workspaceId, schema.githubInstallationRepositoryRemovals.installationId, schema.githubInstallationRepositoryRemovals.repositoryId, ], set: { removedAt: sql`greatest(${schema.githubInstallationRepositoryRemovals.removedAt}, excluded.removed_at)`, }, }); } } const changed = removed.length > 0 || added.length > 0; // `updated_at` is the binding's ordering fence: a mirror read before it // is ignored, and repository lists cached before it are re-read from // GitHub on every API replica. A removal always advances it, so a list // read before the removal can never restore the repository. The fence // moves just past the removal: a list read in the same millisecond may // predate it, so the removal wins the tie. const fenceAtMs = observation.kind === "remove" ? observedAtMs + 1 : observedAtMs; if ((changed || observation.kind === "remove") && fenceAtMs > row.updatedAt.getTime()) { await scopedDb .update(schema.githubInstallations) .set({ updatedAt: new Date(fenceAtMs) }) .where(eq(schema.githubInstallations.id, row.id)); } return { applied: true, changed, added: added.sort((left, right) => left - right), removed: removed.sort((left, right) => left - right), repositoryIds: [...target].sort((left, right) => left - right), ...(heldUntilMs === null ? {} : { heldUntil: new Date(heldUntilMs) }), }; }, ); } /** The residency claim a side-feature usage event records (never evidence). */ export type UsageEventProcessingResidency = { geography: string; deploymentType: string; regions: readonly string[]; }; export async function recordUsageEvent( db: Database, input: { accountId: string; workspaceId: string; subjectId?: string | null; eventType: string; quantity: number; unit: string; sourceResourceType?: string | null; sourceResourceId?: string | null; sessionId?: string | null; turnId?: string | null; turnAttemptId?: string | null; initiator?: TurnInitiator | null; initiatorContext?: TurnInitiatorContext; origin?: SessionTurnSource | null; idempotencyKey: string; occurredAt?: Date; /** * Where a model-backed side feature processed the call: its route's * residency claim (never evidence). See docs/eu-only-inference.md. */ processingResidency?: UsageEventProcessingResidency | null; }, ): Promise { if (input.turnId && !input.sessionId) { throw new Error("recordUsageEvent: turnId requires sessionId"); } if (input.turnAttemptId && !input.turnId) { throw new Error("recordUsageEvent: turnAttemptId requires turnId"); } if (input.initiatorContext && !input.initiator) { throw new Error("recordUsageEvent: initiatorContext requires initiator"); } const attribution = input.initiator ? initiatorColumns({ initiator: input.initiator, context: input.initiatorContext ?? {}, }) : { initiatorKind: null, initiatorSubjectId: null, initiatorContext: {}, }; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.usageEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, eventType: input.eventType, quantity: input.quantity, unit: input.unit, sourceResourceType: input.sourceResourceType ?? null, sourceResourceId: input.sourceResourceId ?? null, sessionId: input.sessionId ?? null, turnId: input.turnId ?? null, turnAttemptId: input.turnAttemptId ?? null, ...attribution, origin: input.origin ?? null, idempotencyKey: input.idempotencyKey, occurredAt: input.occurredAt ?? new Date(), ...(input.processingResidency ? { processingResidency: { geography: input.processingResidency.geography, deploymentType: input.processingResidency.deploymentType, regions: [...input.processingResidency.regions], }, } : {}), }) .onConflictDoUpdate({ target: schema.usageEvents.idempotencyKey, set: { sessionId: sql`coalesce(${schema.usageEvents.sessionId}, excluded.session_id)`, turnId: sql`coalesce(${schema.usageEvents.turnId}, excluded.turn_id)`, turnAttemptId: sql`coalesce(${schema.usageEvents.turnAttemptId}, excluded.turn_attempt_id)`, initiatorKind: sql`coalesce(${schema.usageEvents.initiatorKind}, excluded.initiator_kind)`, initiatorSubjectId: sql`coalesce(${schema.usageEvents.initiatorSubjectId}, excluded.initiator_subject_id)`, initiatorContext: sql`case when ${schema.usageEvents.initiatorKind} is null then excluded.initiator_context else ${schema.usageEvents.initiatorContext} end`, origin: sql`coalesce(${schema.usageEvents.origin}, excluded.origin)`, }, }) .returning(); if (row) { const expectedContext = [ ["sessionId", input.sessionId, row.sessionId], ["turnId", input.turnId, row.turnId], ["turnAttemptId", input.turnAttemptId, row.turnAttemptId], ] as const; for (const [field, expected, actual] of expectedContext) { if (expected && actual !== expected) { throw new Error(`recordUsageEvent: idempotency key resolved to a different ${field}`); } } if ( input.initiator && (row.initiatorKind !== input.initiator.kind || row.initiatorSubjectId !== input.initiator.subjectId) ) { throw new Error("recordUsageEvent: idempotency key resolved to a different initiator"); } if (input.origin && row.origin !== input.origin) { throw new Error("recordUsageEvent: idempotency key resolved to a different origin"); } return mapUsageEvent(row); } throw new Error("Failed to record usage event"); }, ); } export type ModelCallBillingPath = "opengeni_credits" | "external"; export type ModelCallFact = { id: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; turnAttemptId: string | null; sourceKey: string; provider: string; providerApi: string; model: string; billingPath: ModelCallBillingPath; turnSource: string | null; initiatorKind: string | null; initiatorSubjectId: string | null; scheduledTaskId: string | null; inputTokens: number | null; outputTokens: number | null; cachedTokens: number | null; cacheWriteTokens: number | null; reasoningTokens: number | null; totalTokens: number | null; pricedCostMicros: number; estimatedProviderCostMicros: number | null; equivalentCreditCostMicros: number | null; pricingSource: "configured_list_price" | "gateway_reported" | null; contextContributions: readonly ModelContextContributionSummary[] | null; /** Prompt-cache observation and warm-miss classification, when recorded. */ promptCacheDiagnostics: PromptCacheDiagnostics | null; /** * Where the route that served the call processed it (no evidence). Null * only for calls recorded before calls carried a processing residency. */ processingResidency: ModelCallProcessingResidencyV1 | null; occurredAt: Date; recordedAt: Date; }; function mapModelCallFact(row: typeof schema.modelCallFacts.$inferSelect): ModelCallFact { const billingPath = row.billingPath; if (billingPath !== "opengeni_credits" && billingPath !== "external") { throw new Error(`model_call_facts: invalid billing_path ${billingPath}`); } return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, turnId: row.turnId, turnAttemptId: row.turnAttemptId, sourceKey: row.sourceKey, provider: row.provider, providerApi: row.providerApi, model: row.model, billingPath, turnSource: row.turnSource, initiatorKind: row.initiatorKind, initiatorSubjectId: row.initiatorSubjectId, scheduledTaskId: row.scheduledTaskId, inputTokens: row.inputTokens, outputTokens: row.outputTokens, cachedTokens: row.cachedTokens, cacheWriteTokens: row.cacheWriteTokens, reasoningTokens: row.reasoningTokens, totalTokens: row.totalTokens, pricedCostMicros: row.pricedCostMicros, estimatedProviderCostMicros: row.estimatedProviderCostMicros, equivalentCreditCostMicros: row.equivalentCreditCostMicros, pricingSource: row.pricingSource === "configured_list_price" || row.pricingSource === "gateway_reported" ? row.pricingSource : null, contextContributions: row.contextContributions, promptCacheDiagnostics: row.promptCacheDiagnostics ?? null, processingResidency: parseModelCallProcessingResidency(row.processingResidency), occurredAt: row.occurredAt, recordedAt: row.recordedAt, }; } function scheduledRunIdsFromContext(context: unknown): string[] { if (!context || typeof context !== "object" || Array.isArray(context)) return []; const raw = (context as Record).scheduledRunIds; if (!Array.isArray(raw)) return []; return raw.filter((value): value is string => typeof value === "string" && value.length > 0); } async function resolveScheduledTaskIdForTurn( scopedDb: Database, input: { workspaceId: string; initiatorSubjectId: string | null; initiatorContext: unknown; }, ): Promise { // initiatorSubjectId is intentionally unused: any turn that carries // scheduledRunIds is eligible for schedule attribution (scheduler wakes and // inherited contexts alike). Mis-bucketing by turn.source remains forbidden. void input.initiatorSubjectId; const runIds = scheduledRunIdsFromContext(input.initiatorContext); if (runIds.length === 0) return null; // Prefer the earliest run when a batch somehow carries multiple ids so // attribution is deterministic across retries. const [run] = await scopedDb .select({ taskId: schema.scheduledTaskRuns.taskId }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), inArray(schema.scheduledTaskRuns.id, runIds), ), ) .orderBy(schema.scheduledTaskRuns.createdAt) .limit(1); return run?.taskId ?? null; } /** * Idempotent Insights fact for one authoritative model call. Soft-callers must * never let failures affect billing; this writer itself is safe to retry. */ export async function recordModelCallFact( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; turnAttemptId?: string | null; sourceKey: string; provider: string; providerApi: string; model: string; billingPath: ModelCallBillingPath; pricedCostMicros: number; estimatedProviderCostMicros?: number | null; equivalentCreditCostMicros?: number | null; /** Captured classes must conserve the already-recorded provider total. */ listByClassMicros?: { uncachedInput: number; cacheRead: number; cacheWrite: number; output: number; } | null; listByClassApprox?: boolean; pricingSource?: "configured_list_price" | "gateway_reported" | null; contextContributions?: readonly ModelContextContributionSummary[] | null; inputTokens?: number | null; outputTokens?: number | null; cachedTokens?: number | null; cacheWriteTokens?: number | null; reasoningTokens?: number | null; totalTokens?: number | null; /** Worker-measured timing of the call; absent for calls it did not stream. */ timing?: ModelCallTiming | null; /** * What the worker observed about the call's prompt cache. When present * (even null), the write classifies a warm-cache miss against the previous * call of the same model in the session. Omitted by repair paths. */ promptCache?: PromptCacheObservation | null; /** * Processing residency claim of the route that served the call. Only the * claim is stored, never evidence; a call whose route is not known is * recorded as unknown, never null. */ processingResidency?: ModelCallProcessingResidencyV1 | null; occurredAt?: Date; /** * The shared-core subscription connection that served the call (core * Codex turns). Legacy and non-subscription calls leave it NULL. */ connectionId?: string | null; }, ): Promise { if (input.pricedCostMicros < 0 || !Number.isSafeInteger(input.pricedCostMicros)) { throw new Error("recordModelCallFact: pricedCostMicros must be a non-negative safe integer"); } if ( input.estimatedProviderCostMicros != null && (input.estimatedProviderCostMicros < 0 || !Number.isSafeInteger(input.estimatedProviderCostMicros)) ) { throw new Error( "recordModelCallFact: estimatedProviderCostMicros must be null or a non-negative safe integer", ); } if ( input.equivalentCreditCostMicros != null && (input.equivalentCreditCostMicros < 0 || !Number.isSafeInteger(input.equivalentCreditCostMicros)) ) { throw new Error( "recordModelCallFact: equivalentCreditCostMicros must be null or a non-negative safe integer", ); } if (input.equivalentCreditCostMicros != null && input.estimatedProviderCostMicros == null) { throw new Error( "recordModelCallFact: equivalentCreditCostMicros requires estimatedProviderCostMicros", ); } if ((input.estimatedProviderCostMicros == null) !== (input.pricingSource == null)) { throw new Error( "recordModelCallFact: estimatedProviderCostMicros and pricingSource must be present together", ); } const contextContributions = input.contextContributions == null ? null : ModelContextContributionSummaries.parse(input.contextContributions); const timing = modelCallTimingOrNull(input.timing); const classes = input.listByClassMicros; if ( classes != null && (Object.values(classes).some((value) => !Number.isSafeInteger(value) || value < 0) || input.estimatedProviderCostMicros == null || Object.values(classes).reduce((total, value) => total + BigInt(value), 0n) !== BigInt(input.estimatedProviderCostMicros)) ) { throw new Error( "recordModelCallFact: list classes must be non-negative safe integers conserving the recorded total", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [turn] = await scopedDb .select({ source: schema.sessionTurns.source, initiatorKind: schema.sessionTurns.initiatorKind, initiatorSubjectId: schema.sessionTurns.initiatorSubjectId, initiatorContext: schema.sessionTurns.initiatorContext, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), ), ) .limit(1); const scheduledTaskId = turn ? await resolveScheduledTaskIdForTurn(scopedDb, { workspaceId: input.workspaceId, initiatorSubjectId: turn.initiatorSubjectId, initiatorContext: turn.initiatorContext, }) : null; const occurredAt = input.occurredAt ?? new Date(); const promptCacheDiagnostics = input.promptCache === undefined ? null : await promptCacheDiagnosticsForCall(scopedDb, { workspaceId: input.workspaceId, sessionId: input.sessionId, model: input.model, current: { sourceKey: input.sourceKey, inputTokens: input.inputTokens ?? null, cachedTokens: input.cachedTokens ?? null, connectionId: input.connectionId ?? null, occurredAt, observation: parsePromptCacheObservation(input.promptCache), }, }); const [row] = await scopedDb .insert(schema.modelCallFacts) .values({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnAttemptId: input.turnAttemptId ?? null, sourceKey: input.sourceKey, provider: input.provider, providerApi: input.providerApi, model: input.model, billingPath: input.billingPath, turnSource: turn?.source ?? null, initiatorKind: turn?.initiatorKind ?? null, initiatorSubjectId: turn?.initiatorSubjectId ?? null, scheduledTaskId, inputTokens: input.inputTokens ?? null, outputTokens: input.outputTokens ?? null, cachedTokens: input.cachedTokens ?? null, cacheWriteTokens: input.cacheWriteTokens ?? null, reasoningTokens: input.reasoningTokens ?? null, totalTokens: input.totalTokens ?? null, pricedCostMicros: input.pricedCostMicros, estimatedProviderCostMicros: input.estimatedProviderCostMicros ?? null, equivalentCreditCostMicros: input.equivalentCreditCostMicros ?? null, pricingSource: input.pricingSource ?? null, listUncachedInputCostMicros: classes?.uncachedInput ?? null, listCacheReadCostMicros: classes?.cacheRead ?? null, listCacheWriteCostMicros: classes?.cacheWrite ?? null, listOutputCostMicros: classes?.output ?? null, listCostIsApprox: classes == null ? null : (input.listByClassApprox ?? false), contextContributions, connectionId: input.connectionId ?? null, ...modelCallTimingColumns(timing), promptCacheDiagnostics, processingResidency: parseModelCallProcessingResidency(input.processingResidency) ?? modelCallProcessingResidency(null), occurredAt, }) .onConflictDoUpdate({ target: [ schema.modelCallFacts.workspaceId, schema.modelCallFacts.turnId, schema.modelCallFacts.sourceKey, ], set: { turnAttemptId: sql`coalesce(${schema.modelCallFacts.turnAttemptId}, excluded.turn_attempt_id)`, scheduledTaskId: sql`coalesce(${schema.modelCallFacts.scheduledTaskId}, excluded.scheduled_task_id)`, initiatorKind: sql`coalesce(${schema.modelCallFacts.initiatorKind}, excluded.initiator_kind)`, initiatorSubjectId: sql`coalesce(${schema.modelCallFacts.initiatorSubjectId}, excluded.initiator_subject_id)`, turnSource: sql`coalesce(${schema.modelCallFacts.turnSource}, excluded.turn_source)`, estimatedProviderCostMicros: sql`coalesce(${schema.modelCallFacts.estimatedProviderCostMicros}, excluded.estimated_provider_cost_micros)`, equivalentCreditCostMicros: sql`coalesce(${schema.modelCallFacts.equivalentCreditCostMicros}, excluded.equivalent_credit_cost_micros)`, pricingSource: sql`coalesce(${schema.modelCallFacts.pricingSource}, excluded.pricing_source)`, listUncachedInputCostMicros: sql`coalesce(${schema.modelCallFacts.listUncachedInputCostMicros}, excluded.list_uncached_input_cost_micros)`, listCacheReadCostMicros: sql`coalesce(${schema.modelCallFacts.listCacheReadCostMicros}, excluded.list_cache_read_cost_micros)`, listCacheWriteCostMicros: sql`coalesce(${schema.modelCallFacts.listCacheWriteCostMicros}, excluded.list_cache_write_cost_micros)`, listOutputCostMicros: sql`coalesce(${schema.modelCallFacts.listOutputCostMicros}, excluded.list_output_cost_micros)`, listCostIsApprox: sql`coalesce(${schema.modelCallFacts.listCostIsApprox}, excluded.list_cost_is_approx)`, contextContributions: sql`coalesce(${schema.modelCallFacts.contextContributions}, excluded.context_contributions)`, connectionId: sql`coalesce(${schema.modelCallFacts.connectionId}, excluded.connection_id)`, preDispatchMs: sql`coalesce(${schema.modelCallFacts.preDispatchMs}, excluded.pre_dispatch_ms)`, timeToFirstTokenMs: sql`coalesce(${schema.modelCallFacts.timeToFirstTokenMs}, excluded.time_to_first_token_ms)`, timeToFirstTextMs: sql`coalesce(${schema.modelCallFacts.timeToFirstTextMs}, excluded.time_to_first_text_ms)`, durationMs: sql`coalesce(${schema.modelCallFacts.durationMs}, excluded.duration_ms)`, promptCacheDiagnostics: sql`coalesce(${schema.modelCallFacts.promptCacheDiagnostics}, excluded.prompt_cache_diagnostics)`, processingResidency: sql`coalesce(${schema.modelCallFacts.processingResidency}, excluded.processing_residency)`, }, }) .returning(); if (!row) { throw new Error("Failed to record model call fact"); } return mapModelCallFact(row); }, ); } /** * The call's prompt-cache observation plus its warm-miss classification * against the previous call of the same model in the same session. */ async function promptCacheDiagnosticsForCall( scopedDb: Database, input: { workspaceId: string; sessionId: string; model: string; current: PromptCacheCallSample; }, ): Promise { const [previous] = await scopedDb .select({ sourceKey: schema.modelCallFacts.sourceKey, inputTokens: schema.modelCallFacts.inputTokens, cachedTokens: schema.modelCallFacts.cachedTokens, connectionId: schema.modelCallFacts.connectionId, occurredAt: schema.modelCallFacts.occurredAt, promptCacheDiagnostics: schema.modelCallFacts.promptCacheDiagnostics, }) .from(schema.modelCallFacts) .where( and( eq(schema.modelCallFacts.workspaceId, input.workspaceId), eq(schema.modelCallFacts.sessionId, input.sessionId), eq(schema.modelCallFacts.model, input.model), lt(schema.modelCallFacts.occurredAt, input.current.occurredAt), ne(schema.modelCallFacts.sourceKey, input.current.sourceKey), ), ) .orderBy(desc(schema.modelCallFacts.occurredAt)) .limit(1); const warmMiss = classifyPromptCacheWarmMiss( previous ? { sourceKey: previous.sourceKey, inputTokens: previous.inputTokens, cachedTokens: previous.cachedTokens, connectionId: previous.connectionId, occurredAt: previous.occurredAt, observation: parsePromptCacheObservation(previous.promptCacheDiagnostics), } : null, input.current, ); const observation = input.current.observation; if (!observation && !warmMiss) return null; return { ...observation, ...(warmMiss ? { warmMiss } : {}) }; } export { getOrganizationModelUsage, getOrganizationUsageSummary, getOrganizationUsageWorkspacePage, organizationUsageWindow, } from "./organization-usage"; export async function listUsageEvents( db: Database, input: { accountId: string; workspaceId?: string; limit?: number; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId ?? null }, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.usageEvents) .where( input.workspaceId ? and( eq(schema.usageEvents.accountId, input.accountId), eq(schema.usageEvents.workspaceId, input.workspaceId), ) : eq(schema.usageEvents.accountId, input.accountId), ) .orderBy(desc(schema.usageEvents.occurredAt), desc(schema.usageEvents.recordedAt)) .limit(input.limit ?? 100); return rows.map(mapUsageEvent); }, ); } export async function sumUsageQuantity( db: Database, input: { accountId?: string; workspaceId?: string; eventType: string; since?: Date; }, ): Promise { const context = input.workspaceId ? await rlsContextForWorkspace(db, input.workspaceId) : input.accountId ? { accountId: input.accountId, workspaceId: null } : null; if (!context) { throw new Error("Usage quantity queries require accountId or workspaceId"); } return await withRlsContext(db, context, async (scopedDb) => { const clauses = [ eq(schema.usageEvents.eventType, input.eventType), ...(input.accountId ? [eq(schema.usageEvents.accountId, input.accountId)] : []), ...(input.workspaceId ? [eq(schema.usageEvents.workspaceId, input.workspaceId)] : []), ...(input.since ? [gt(schema.usageEvents.occurredAt, input.since)] : []), ]; const [{ total } = { total: 0 }] = await scopedDb .select({ total: sql`coalesce(sum(${schema.usageEvents.quantity}), 0)`, }) .from(schema.usageEvents) .where(and(...clauses)); return Number(total); }); } const USAGE_ORIGIN_TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * The funding origin a usage debit is charged under, frozen on its ledger row * (`usage_origin`): the caller's explicit origin; else the origin carried in * its attribution metadata; else the turn it names; else the origin a * trusted outer scope fixed; else app (today's behaviour, and legacy null). * API debits never count against the monthly plan allowance. */ /** * The origin a frozen billing record is charged under, resolved like the * debit itself (see resolveUsageOrigin), so admission and charge agree. */ async function attributionBillingOrigin( scopedDb: Database, input: { accountId: string; workspaceId: string; attribution?: CreditDebitAttribution | null | undefined; }, ): Promise { const attribution = input.attribution; if (!attribution || attribution.kind === "unknown") return ambientBillingOrigin() ?? "app"; return await resolveUsageOrigin(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, metadata: creditDebitAttributionMetadata(attribution), }); } /** {@link attributionBillingOrigin} for a caller outside an account scope. */ export async function billingOriginForAttribution( db: Database, input: { accountId: string; workspaceId: string; attribution?: CreditDebitAttribution | null | undefined; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await attributionBillingOrigin(scopedDb, input), ); } async function resolveUsageOrigin( scopedDb: Database, input: { accountId: string; workspaceId?: string | null; usageOrigin?: BillingOrigin | undefined; metadata?: Record | undefined; }, ): Promise { if (input.usageOrigin) return input.usageOrigin; const metadataOrigin = input.metadata?.billingOrigin; if (metadataOrigin === "app" || metadataOrigin === "api") return metadataOrigin; const attribution = currentCreditDebitAttribution(); const turnId = typeof input.metadata?.turnId === "string" ? input.metadata.turnId : attribution.kind === "turn" && !attribution.billingOrigin ? attribution.turnId : null; if (turnId && input.workspaceId && USAGE_ORIGIN_TURN_ID.test(turnId)) { const [turn] = await rawRows<{ billingOrigin: string | null }>( scopedDb, sql`SELECT billing_origin AS "billingOrigin" FROM session_turns WHERE account_id=${input.accountId}::uuid AND workspace_id=${input.workspaceId}::uuid AND id=${turnId}::uuid`, ); if (turn) return storedBillingOrigin(turn.billingOrigin); } return ambientBillingOrigin() ?? "app"; } /** * Settle an already-consumed, Opengeni-funded resource for its full cost. * Admission happens before use; an in-flight operation can take the account * below zero. Future grants and purchased top-ups net against that balance. * Model responses settle here too: parallel or long calls are charged their * full price even when it exceeds what was left when they were admitted. * Never use this helper to admit a new operation or for externally paid use. */ export async function applyCreditDebitAfterUse( db: Database, input: { accountId: string; workspaceId?: string | null; type: string; amountMicros: number; sourceType: string; sourceId: string; idempotencyKey: string; metadata?: Record; occurredAt?: Date; /** * What the charge paid for. Monthly plan credit pays first, then grants * covering the excess (oldest first), then other general credit. * Omitted: general credit only. */ usage?: CreditUsage; /** * The promotion policy revision the operation was admitted under, so its * grants are allocated with the model coverage it was admitted with. * Omitted: the current policy. */ creditPolicyRevision?: number | undefined; /** Funding origin; omitted resolves from the attribution (see resolveUsageOrigin). */ usageOrigin?: BillingOrigin; }, ): Promise<{ balance: BillingBalance; debitedMicros: number; /** * The part of `debitedMicros` paid by promotional or plan credit grants; * the rest came from general credit. Zero on an idempotent replay. */ grantDebitedMicros: number; }> { if (!Number.isSafeInteger(input.amountMicros) || input.amountMicros <= 0) { throw new Error("post-use credit debit requires a positive, safe integer micro amount"); } if (input.type === BYOK_PLATFORM_FEE_TYPE) { throw new Error("a bring-your-own-key fee settles with applyByokPlatformFeeDebit"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId ?? null }, async (scopedDb) => { // Serialize ALL post-use charges with plan expiry, including resources // that cannot allocate promotional grants. await scopedDb.execute(sql`select pg_advisory_xact_lock(hashtext(${input.accountId}))`); const settledAt = await beginPlanCreditSettlement(scopedDb, input.accountId); const usageOrigin = await resolveUsageOrigin(scopedDb, input); let allocations: { grantEntryId: string; amountMicros: number }[] = []; // App use: plan credit (the Free plan's scoped credit too) pays for // tools as well as models. if (usageOrigin === "app") { allocations = planPostUseCreditAllocations( await getBillingBalance( scopedDb, input.accountId, input.creditPolicyRevision, settledAt, true, ), input.amountMicros, input.usage, ); } const insertedId = await insertPostUseDebit(scopedDb, input, usageOrigin, settledAt); if (insertedId && allocations.length) { await scopedDb.insert(schema.creditDebitAllocations).values( allocations.map((allocation) => ({ ...allocation, accountId: input.accountId, debitEntryId: insertedId, })), ); } return { balance: await getBillingBalance(scopedDb, input.accountId), debitedMicros: insertedId ? input.amountMicros : 0, grantDebitedMicros: insertedId ? allocations.reduce((sum, allocation) => sum + allocation.amountMicros, 0) : 0, }; }, ); } /** * Insert an already-consumed charge once. A replay of the same idempotency * key must be the same charge. Returns the new row's id, or null on replay. * A model response settled by an earlier release, which capped the debit at * the eligible balance (possibly a zero-cost receipt), recorded its full price * as `requestedAmountMicros`; replaying that same price is the same charge and * is never charged again. */ async function insertPostUseDebit( scopedDb: Database, input: { accountId: string; workspaceId?: string | null; type: string; amountMicros: number; sourceType: string; sourceId: string; idempotencyKey: string; metadata?: Record; occurredAt?: Date; }, usageOrigin: BillingOrigin, settledAt: string, createdAt: SQL = sql`${settledAt}::timestamptz`, ): Promise { const inserted = await scopedDb .insert(schema.creditLedgerEntries) .values({ accountId: input.accountId, workspaceId: input.workspaceId ?? null, type: input.type, amountMicros: -input.amountMicros, sourceType: input.sourceType, sourceId: input.sourceId, usageOrigin, idempotencyKey: input.idempotencyKey, metadata: input.metadata ?? {}, occurredAt: input.occurredAt ?? new Date(), createdAt, }) .onConflictDoNothing({ target: schema.creditLedgerEntries.idempotencyKey }) .returning({ id: schema.creditLedgerEntries.id }); if (inserted.length) return inserted[0]!.id; const [prior] = await scopedDb .select({ accountId: schema.creditLedgerEntries.accountId, workspaceId: schema.creditLedgerEntries.workspaceId, type: schema.creditLedgerEntries.type, amountMicros: schema.creditLedgerEntries.amountMicros, sourceType: schema.creditLedgerEntries.sourceType, sourceId: schema.creditLedgerEntries.sourceId, requestedAmountMicros: sql< string | null >`${schema.creditLedgerEntries.metadata}->>'requestedAmountMicros'`, }) .from(schema.creditLedgerEntries) .where(eq(schema.creditLedgerEntries.idempotencyKey, input.idempotencyKey)); if ( !prior || prior.accountId !== input.accountId || prior.workspaceId !== (input.workspaceId ?? null) || prior.type !== input.type || (prior.amountMicros !== -input.amountMicros && prior.requestedAmountMicros !== String(input.amountMicros)) || prior.sourceType !== input.sourceType || prior.sourceId !== input.sourceId ) { throw new Error("post-use credit debit idempotency key conflicts with a different charge"); } return null; } /** * Settle one bring-your-own-key platform fee (`byok_platform_fee`), payable * only from paid credit: an active paid plan's credit first (app use), then * paid credits; the rest is fee debt the next top-up repays. Its row records * the split (`planPaidMicros`, `creditPaidMicros`, `unfundedMicros`) and a * paid-credit mark (paid-credit.ts). One balance read under the account lock. */ export async function applyByokPlatformFeeDebit( db: Database, input: { accountId: string; workspaceId?: string | null; amountMicros: number; sourceType: string; sourceId: string; idempotencyKey: string; metadata?: Record; occurredAt?: Date; /** Funding origin; omitted resolves from the attribution (see resolveUsageOrigin). */ usageOrigin?: BillingOrigin; }, ): Promise<{ debitedMicros: number; planPaidMicros: number; creditPaidMicros: number; unfundedMicros: number; }> { if (!Number.isSafeInteger(input.amountMicros) || input.amountMicros <= 0) { throw new Error("post-use credit debit requires a positive, safe integer micro amount"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId ?? null }, async (scopedDb) => { await scopedDb.execute(sql`select pg_advisory_xact_lock(hashtext(${input.accountId}))`); const settledAt = await beginPlanCreditSettlement(scopedDb, input.accountId); const usageOrigin = await resolveUsageOrigin(scopedDb, input); const { balance, paid } = await readBillingBalance( scopedDb, input.accountId, undefined, settledAt, true, ); const funding = byokFeeFunding(balance, paid, input.amountMicros, usageOrigin); const insertedId = await insertPostUseDebit( scopedDb, { ...input, type: BYOK_PLATFORM_FEE_TYPE, metadata: { ...input.metadata, ...chainedReceipt( paid, { type: BYOK_PLATFORM_FEE_TYPE, amountMicros: input.amountMicros }, { ...funding, ...paidCreditMark(paid), ...feeDebtRepaid(paid) }, ), }, }, usageOrigin, settledAt, receiptCreatedAt(settledAt, paid), ); return insertedId ? { debitedMicros: input.amountMicros, ...funding } : { debitedMicros: 0, planPaidMicros: 0, creditPaidMicros: 0, unfundedMicros: 0 }; }, ); } export async function hasCreditLedgerEntry( db: Database, accountId: string, idempotencyKey: string, ): Promise { return await withAccountRls(db, accountId, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.creditLedgerEntries.id }) .from(schema.creditLedgerEntries) .where( and( eq(schema.creditLedgerEntries.accountId, accountId), eq(schema.creditLedgerEntries.idempotencyKey, idempotencyKey), ), ) .limit(1); return Boolean(row); }); } export async function getCreditLedgerEntry( db: Database, accountId: string, idempotencyKey: string, ): Promise<{ amountMicros: number; sourceType: string | null; metadata: Record; } | null> { return await withAccountRls(db, accountId, async (scopedDb) => { const [row] = await scopedDb .select({ amountMicros: schema.creditLedgerEntries.amountMicros, sourceType: schema.creditLedgerEntries.sourceType, metadata: schema.creditLedgerEntries.metadata, }) .from(schema.creditLedgerEntries) .where( and( eq(schema.creditLedgerEntries.accountId, accountId), eq(schema.creditLedgerEntries.idempotencyKey, idempotencyKey), ), ) .limit(1); return row ?? null; }); } export async function upsertBillingCustomer( db: Database, input: { accountId: string; provider?: string; providerCustomerId: string; email?: string | null; }, ): Promise { await withAccountRls(db, input.accountId, async (scopedDb) => { await scopedDb .insert(schema.billingCustomers) .values({ accountId: input.accountId, provider: input.provider ?? "stripe", providerCustomerId: input.providerCustomerId, email: input.email ?? null, }) .onConflictDoUpdate({ target: [schema.billingCustomers.accountId, schema.billingCustomers.provider], set: { providerCustomerId: input.providerCustomerId, email: input.email ?? null, updatedAt: new Date(), }, }); }); } export async function recordStripeWebhookEvent( db: Database, input: { id: string; type: string; livemode: boolean; payload: unknown; }, ): Promise { const [row] = await db .insert(schema.stripeWebhookEvents) .values({ id: input.id, type: input.type, livemode: String(input.livemode), payload: input.payload, }) .onConflictDoNothing({ target: schema.stripeWebhookEvents.id }) .returning({ id: schema.stripeWebhookEvents.id }); return Boolean(row); } export async function isStripeWebhookProcessed(db: Database, id: string): Promise { const [row] = await db .select({ processedAt: schema.stripeWebhookEvents.processedAt }) .from(schema.stripeWebhookEvents) .where(eq(schema.stripeWebhookEvents.id, id)) .limit(1); return Boolean(row?.processedAt); } export async function markStripeWebhookProcessed(db: Database, id: string): Promise { await db .update(schema.stripeWebhookEvents) .set({ processedAt: new Date() }) .where(eq(schema.stripeWebhookEvents.id, id)); } /** * Whether the organization holds a positive Opengeni credit balance, whatever * its source: a purchase, an operator grant, a test credit, or the one-time * verified-signup trial grant. It turns false again once usage brings the * balance to zero or below. Read-only; it never gates credit admission. */ export async function organizationHoldsCredits(db: Database, accountId: string): Promise { return (await getBillingBalance(db, accountId)).balanceMicros > 0; } export async function countScheduledTasksForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int`, }) .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), isNull(schema.scheduledTasks.deletedAt), ), ); return Number(count); }); } export type AppendEventInput = { type: SessionEventType; payload?: unknown; /** * Server-created retained-output evidence for canonical audit truncation. * Producer payload fields are never trusted as evidence. */ retainedOutputEvidence?: unknown; clientEventId?: string; turnId?: string | null; turnGeneration?: number | null; turnAttemptId?: string | null; turnAssociation?: "current" | "late_rejected" | "duplicate" | null; duplicateOfEventId?: string | null; duplicateReason?: string | null; producerId?: string; producerSeq?: number; occurredAt?: Date; }; /** * The creating session's access policy frozen onto an agent-created scheduled * task. Each key is null when the creating session projection did not expose * that fact at create time; a generated session then keeps its own default. */ export type ScheduledTaskCreatorSessionPolicy = { agentAccess: string | null; scopeSubjectId: string | null; memoryScope: string | null; }; /** * Frozen creator boundary of a scheduled task (migration 0428). Every field is * null for an ordinary human/API-created task, which keeps the deployment default for * its generated sessions. An agent-created task stores its creating session's * explicit first-party selection (null follows defaults) and permission set * so a narrowed session cannot widen its permissions through a schedule. * A human/API creator may instead name the tools and permissions at create * (`agentConfig.firstPartyMcpTools` / `firstPartyMcpPermissions`), stored * here with a null session policy. * Its owner's explicit access refresh re-freezes tools and permissions within their grants; * the session policy and optional credential restriction never change after * create. A restriction alone does not select tools or permissions. */ export type ScheduledTaskCreatorPolicy = { firstPartyMcpTools: FirstPartyMcpToolName[] | null; firstPartyMcpPermissions: Permission[] | null; sessionPolicy: ScheduledTaskCreatorSessionPolicy | null; credentialRestriction?: "developer_setup"; }; export type CreateScheduledTaskInput = { id?: string; accountId: string; /** Funding origin of whoever set the task up, inherited by every run. */ billingOrigin?: BillingOrigin | null; /** Vault narrowing for every run (0739); omission is `{ mode: "all" }`. */ vaultPolicy?: import("@opengeni/contracts").VaultPolicy | undefined; workspaceId: string; name: string; status: ScheduledTaskStatus; schedule: ScheduledTaskScheduleSpec; temporalScheduleId: string; runMode: ScheduledTaskRunMode; overlapPolicy: ScheduledTaskOverlapPolicy; action?: ScheduledTaskAction; agentConfig: ScheduledTaskAgentConfig; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; xaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1; claudeProviderAccountAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1; /** Trusted frozen creator boundary, never copied from task metadata. */ creatorPolicy?: ScheduledTaskCreatorPolicy | null; targetSessionId?: string | null; // The rig each run binds to (M3); active version resolved per fire at dispatch. rigId?: string | null; metadata: Record; /** Who can see it; `user_private` requires a human owner. Default shared. */ visibility?: "user_private" | "workspace_shared"; /** Only the frozen creator principal may change, run or delete it; never an agent attempt. */ creatorLocked?: boolean; /** Trusted database-only admission seam. Throwing rolls the task creation back. */ beforeCreateCommit?: (tx: Database) => Promise; captureLinkAuthority?: (tx: Database, task: ScheduledTask) => Promise; }; export type UpdateScheduledTaskInput = Partial<{ name: string; vaultPolicy: import("@opengeni/contracts").VaultPolicy; status: ScheduledTaskStatus; visibility: "user_private" | "workspace_shared"; schedule: ScheduledTaskScheduleSpec; runMode: ScheduledTaskRunMode; overlapPolicy: ScheduledTaskOverlapPolicy; action: ScheduledTaskAction; agentConfig: ScheduledTaskAgentConfig; reusableSessionId: string | null; targetSessionId: string | null; rigId: string | null; metadata: Record; refreshPersonalResourceAuthority: boolean; clonePersonalResourceAuthorityFromRevision: number; authorityUpdatedBy: TurnInitiator; authorityUpdatedByContext: TurnInitiatorContext; authorityUpdatedByActor: AgentSessionCreationActor | null; /** Trusted database-only admission seam. Throwing rolls the task update back. */ beforeUpdateCommit: (tx: Database) => Promise; captureLinkAuthority: (tx: Database, task: ScheduledTask) => Promise; /** * Refuse the update unless the locked row still has this execution digest: * the head a person reviewed before an explicit access refresh. */ expectedExecutionDigest: string; /** * Re-freeze an agent-created task's Opengeni tools and permissions (the * owner's explicit access refresh). Applies only to a row whose creator * tools are already frozen; the creator session policy is never rewritten. */ creatorFirstPartyPolicy: { firstPartyMcpTools: FirstPartyMcpToolName[]; firstPartyMcpPermissions: Permission[]; }; }>; /** The task changed after the caller read it; nothing was written. */ export class ScheduledTaskHeadChangedError extends Error { constructor() { super("scheduled task changed after it was read"); this.name = "ScheduledTaskHeadChangedError"; } } export type CreateKnowledgeMemoryInput = { accountId: string; workspaceId: string; status?: KnowledgeMemoryStatus | undefined; kind?: KnowledgeMemoryKind | undefined; scope?: string | undefined; text: string; sourceRefs?: KnowledgeSourceRef[] | undefined; confidence?: number | undefined; metadata?: Record | undefined; createdBySessionId?: string | null | undefined; }; export type UpdateKnowledgeMemoryInput = { status?: KnowledgeMemoryStatus | undefined; kind?: KnowledgeMemoryKind | undefined; scope?: string | undefined; text?: string | undefined; sourceRefs?: KnowledgeSourceRef[] | undefined; confidence?: number | undefined; metadata?: Record | undefined; reviewedBy?: string | null | undefined; pinned?: boolean | undefined; }; export type ListKnowledgeMemoryOptions = { query?: string | undefined; status?: KnowledgeMemoryStatus | KnowledgeMemoryStatus[] | undefined; kind?: KnowledgeMemoryKind | undefined; scope?: string | undefined; limit?: number | undefined; /** Agent-only typed read layers; see WorkspaceMemorySearchInput.agentScope. */ agentScope?: MemoryAgentScope | undefined; }; export type CreateSocialConnectionInput = { accountId: string; workspaceId: string; subjectId?: string | null; provider: SocialProvider; accountHandle: string; accountName?: string | null; externalAccountId?: string | null; status: SocialConnectionStatus; scopes?: string[]; credentialRef?: string | null; credentialEncrypted?: string | null; tokenMetadata?: Record; metadata?: Record; }; export type UpsertSocialOAuthConnectionInput = { expectedConnection?: { id: string; version: number }; accountId: string; workspaceId: string; subjectId?: string | null; provider: SocialProvider; accountHandle: string; accountName?: string | null; externalAccountId?: string | null; scopes: string[]; credentialEncrypted: string; tokenMetadata?: Record; }; export type UpdateSocialConnectionCredentialInput = { workspaceId: string; connectionId: string; subjectId?: string | null; credentialEncrypted?: string | null; status?: SocialConnectionStatus; tokenMetadata?: Record; /** * A disconnect (status `disabled`) by this actor: audited in the same * transaction when the connection was not already disabled. */ audit?: DisconnectAuditActor | null; }; export type CreateSocialPostInput = { accountId: string; workspaceId: string; subjectId?: string | null; connectionId: string; externalPostId?: string | null; url?: string | null; authorHandle?: string | null; text: string; publishedAt: Date; metrics?: Record; raw?: Record; }; export type CreateConnectionInput = { accountId: string; workspaceId: string; subjectId?: string | null; providerDomain: string; kind: ConnectionKind; status?: ConnectionStatus; credentialEncrypted: string; grantedScopes?: string[]; expiresAt?: Date | null; verifiedInstallAt?: Date | null; verifiedInstallVersion?: number | null; metadata?: Record; /** See connectionAccountIdentityKey; omit when the account is unverified. */ accountIdentityKey?: string | null; /** The person's own name for the connection (already normalized). */ label?: string | null; createdBySubjectId?: string | null; updatedBySubjectId?: string | null; }; type UpsertWorkspaceProviderApiKeyConnectionInput = { accountId: string; workspaceId: string; operationId: string; requestDigest: string; credentialEncrypted: string; grantedScopes?: string[]; expiresAt?: Date | null; metadata?: Record; updatedBySubjectId: string; }; type RotateWorkspaceProviderApiKeyConnectionInput = { accountId: string; workspaceId: string; connectionId: string; expectedVersion: number; operationId: string; requestDigest: string; credentialEncrypted: string; grantedScopes?: string[]; expiresAt?: Date | null; metadata?: Record; updatedBySubjectId: string; }; type RevokeWorkspaceProviderApiKeyConnectionsInput = { accountId: string; workspaceId: string; connectionId: string; expectedVersion: number; updatedBySubjectId: string; /** Audit the disconnect, in its transaction, as this actor. */ audit?: DisconnectAuditActor | null; }; export type UpsertWorkspaceVercelAiGatewayConnectionInput = UpsertWorkspaceProviderApiKeyConnectionInput; export type RotateWorkspaceVercelAiGatewayConnectionInput = RotateWorkspaceProviderApiKeyConnectionInput; export type RevokeWorkspaceVercelAiGatewayConnectionsInput = RevokeWorkspaceProviderApiKeyConnectionsInput; export type UpsertWorkspaceOpenRouterConnectionInput = UpsertWorkspaceProviderApiKeyConnectionInput; export type RotateWorkspaceOpenRouterConnectionInput = RotateWorkspaceProviderApiKeyConnectionInput; export type RevokeWorkspaceOpenRouterConnectionsInput = RevokeWorkspaceProviderApiKeyConnectionsInput; export type UpdateConnectionInput = { workspaceId: string; connectionId: string; visibleToSubjectId?: string | null; expectedVersion?: number | undefined; subjectId?: string | null; providerDomain?: string; kind?: ConnectionKind; status?: ConnectionStatus; credentialEncrypted?: string; grantedScopes?: string[]; expiresAt?: Date | null; verifiedInstallAt?: Date | null; verifiedInstallVersion?: number | null; metadata?: Record; /** * See connectionAccountIdentityKey. Undefined keeps the stored key, unless * the update replaces the credential: then the key is cleared. */ accountIdentityKey?: string | null; /** * The key the writer derives from the stored row's own verified account, * for a row saved before keys existed. With `accountIdentityKey` equal to * it (and no scope lost) the reconnect keeps `authorityGeneration`. */ previousAccountIdentityKey?: string | null; /** * The new credential's verified account key, when the writer cannot store * it on this row (another live row of the same owner already holds it, as * for a legacy duplicate). It counts like `accountIdentityKey` for keeping * `authorityGeneration`, but the row stays without a key. Pass it only * after verifying the new credential is that account; it is ignored when * `accountIdentityKey` is given (including null, an unverified account). */ vouchedAccountIdentityKey?: string | null; /** Rename: display only, so it changes neither `version` nor authority. */ label?: string | null; updatedBySubjectId?: string | null; }; export type PersistProviderOAuthConnectionInput = CreateConnectionInput & { /** Server continuation reauthorization; runs inside the credential transaction. */ authorize?: (tx: Database) => Promise; visibleToSubjectId: string; credentialRole: string; providerFamily: string; providerPrincipalId: string; requestedConnectionId?: string; requestedConnectionVersion?: number; /** * Require this exact subject to retain live workspace authority in the same * transaction that persists the credential. This is only a consistency * fence: the caller must separately prove that the subject is the * authenticated managed human before opting in. */ requireLiveUserAuthority?: boolean; /** Permission that must remain present while the owner row is locked. */ requiredLiveUserPermission?: "connections:write"; /** * Permit the canonical managed-human personal-workspace exception when no * ordinary membership row exists. The caller must have authenticated that * exact human before opting in. */ allowCanonicalPersonalWorkspaceOwner?: boolean; /** Keep at most one non-revoked provider principal for this owner/family. */ exclusiveProviderPrincipalPerOwner?: boolean; /** Existing values for these metadata keys survive exact-principal convergence. */ preserveExistingMetadataKeys?: readonly string[]; }; export type UpdateSlackBotDocumentDestinationInput = { accountId: string; workspaceId: string; connectionId: string; visibleToSubjectId: string; expectedVersion: number; metadata: Record; updatedBySubjectId: string; }; export type TransitionConnectionStateInput = { workspaceId: string; connectionId: string; visibleToSubjectId?: string | null; expectedVersion: number; status?: ConnectionStatus; metadata: Record; lastError?: string | null; updatedBySubjectId?: string | null; }; export type DisconnectConnectionIdempotentlyInput = { accountId: string; workspaceId: string; subjectId: string; connectionId: string; expectedVersion: number; idempotencyKey: string; metadata: Record; lastError?: string | null; updatedBySubjectId?: string | null; /** Audit the disconnect, in its transaction, as this actor (never on a replay). */ audit?: DisconnectAuditActor | null; }; export class ConnectionDisconnectIdempotencyError extends Error { readonly code = "IDEMPOTENCY_KEY_REUSED"; constructor() { super("The disconnect idempotency key was already used with different input"); this.name = "ConnectionDisconnectIdempotencyError"; } } export class ConnectionDisconnectGenerationError extends Error { readonly code = "CONNECTION_GENERATION_CHANGED"; constructor() { super("The disconnect operation belongs to an older connection generation"); this.name = "ConnectionDisconnectGenerationError"; } } export type PersonalGitHubRepositoryPermissions = { pull: boolean; push: boolean; admin: boolean; maintain: boolean; triage: boolean; }; export type PersonalGitHubSelectedRepositoryRecord = { repositoryId: string; fullName: string; canonicalUrl: string; defaultBranch: string; visibility: "public" | "private" | "internal"; private: boolean; archived: boolean; disabled: boolean; permissions: PersonalGitHubRepositoryPermissions; selectedAccess: "read" | "write"; selectionGeneration: number; selectedAt: string; lastVerifiedAt: string; }; export type PersonalGitHubRepositorySelectionState = { connectionAuthorityGeneration: number; credentialBindingId: string; providerPrincipalId: string; selectionGeneration: number; /** "All my repositories": null keeps only `repositories`. */ allRepositoriesAccess: "read" | "write" | null; /** * The selection generation at which All my repositories was last turned * on, off or changed. Work accepted under the mode before it stays stopped. */ allRepositoriesGeneration?: number | null | undefined; repositories: PersonalGitHubSelectedRepositoryRecord[]; }; export type PersonalGitHubVerifiedRepositoryInput = Omit< PersonalGitHubSelectedRepositoryRecord, "selectionGeneration" | "selectedAt" >; export type PersonalGitHubRepositorySelectionMutationInput = { accountId: string; originWorkspaceId: string; subjectId: string; connectionId: string; expectedConnectionAuthorityGeneration: number; expectedSelectionGeneration: number; idempotencyKey: string; repositories: PersonalGitHubVerifiedRepositoryInput[]; /** Set "All my repositories" with the list (null turns it off); omitted keeps the mode. */ allRepositoriesAccess?: "read" | "write" | null; }; export class PersonalGitHubRepositorySelectionChangedError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_CHANGED"; constructor() { super("The personal GitHub repository selection changed"); this.name = "PersonalGitHubRepositorySelectionChangedError"; } } export class PersonalGitHubRepositorySelectionIdempotencyError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_IDEMPOTENCY_KEY_REUSED"; constructor() { super("The personal GitHub repository idempotency key was reused"); this.name = "PersonalGitHubRepositorySelectionIdempotencyError"; } } export class PersonalGitHubRepositorySelectionUnavailableError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_UNAVAILABLE"; constructor() { super("The personal GitHub repository selection is unavailable"); this.name = "PersonalGitHubRepositorySelectionUnavailableError"; } } export type SlackBotPostOperation = { id: string; accountId: string; workspaceId: string; connectionId: string; operationId: string; clientMessageId: string; targetKind: "channel" | "user"; targetId: string; requestDigest: string; status: "pending" | "provider_started" | "outcome_unknown" | "completed"; claimHolderId: string | null; claimExpiresAt: Date | null; claimMode: "send" | "reconcile" | null; attemptCount: number; lastFailureCode: string | null; slackChannelId: string | null; slackMessageTimestamp: string | null; completedAt: Date | null; createdAt: Date; updatedAt: Date; }; export type SlackBotUpdateOperation = { id: string; accountId: string; workspaceId: string; connectionId: string; operationId: string; slackChannelId: string; slackMessageTimestamp: string; requestDigest: string; status: "provider_started" | "completed"; claimHolderId: string | null; claimExpiresAt: Date | null; attemptCount: number; lastFailureCode: string | null; completedAt: Date | null; createdAt: Date; updatedAt: Date; }; export type SlackBotDeleteOperation = { id: string; accountId: string; workspaceId: string; connectionId: string; operationId: string; principalType: "subject" | "service"; principalId: string; toolName: "slack_bot_delete_message"; channelId: string; messageTimestamp: string; requestDigest: string; status: "pending" | "provider_started" | "outcome_unknown" | "completed"; claimHolderId: string | null; claimExpiresAt: Date | null; attemptCount: number; lastFailureCode: string | null; slackChannelId: string | null; slackMessageTimestamp: string | null; completedAt: Date | null; createdAt: Date; updatedAt: Date; }; export type IntegrationOAuthClientForUse = { id: string; issuer: string; authorizationServer: string; clientId: string; clientSecret: string | null; tokenEndpointAuthMethod: string; metadata: Record; createdAt: Date; updatedAt: Date; }; export type StoredIntegrationOAuthClient = { id: string; issuer: string; authorizationServer: string; clientId: string; clientSecretEncrypted: string | null; tokenEndpointAuthMethod: string; metadata: Record; createdAt: Date; updatedAt: Date; }; export type StoreIntegrationOAuthClientInput = { issuer: string; authorizationServer: string; clientId: string; clientSecretEncrypted?: string | null; tokenEndpointAuthMethod?: string; metadata?: Record; }; export type ReplaceIntegrationOAuthClientInput = StoreIntegrationOAuthClientInput; export type ReplaceIntegrationOAuthClientIfCurrentInput = ReplaceIntegrationOAuthClientInput & { expectedClientId: string; }; export type ConsumeOAuthStateNonceInput = { accountId: string; workspaceId: string; subjectId: string; nonce: string; expiresAt: Date; now: Date; }; export type CreateCapabilityCatalogItemInput = { accountId: string; workspaceId: string; id: string; kind: "mcp"; source: CapabilitySource; name: string; description?: string | null; category?: string; tags?: string[]; homepageUrl?: string | null; endpointUrl?: string | null; installUrl?: string | null; authModel?: string | null; /** A known service's sign-in, when the address identifies it (e.g. Microsoft Dynamics). */ authKind?: "oauth2" | null; mcpUrl?: string | null; providerDomain?: string | null; metadata?: Record; /** * Insert only: an existing workspace row with this id is returned unchanged * instead of being rewritten (a member adding a server never edits one). */ createOnly?: boolean; }; export type ImportBatch = { id: string; source: string; snapshotDate: string; snapshotRef: string | null; attributionNote: string; importedCount: number; skippedCount: number; quarantinedCount: number; logoFailureCount: number; staleCount: number; details: Record; createdAt: string; updatedAt: string; }; export type CreateImportBatchInput = { source: string; snapshotDate: Date; snapshotRef?: string | null; attributionNote: string; importedCount?: number; skippedCount?: number; quarantinedCount?: number; logoFailureCount?: number; staleCount?: number; details?: Record; }; export type UpdateImportBatchCountsInput = { importedCount: number; skippedCount: number; quarantinedCount: number; logoFailureCount: number; staleCount: number; details?: Record; }; export type RegistryCapabilityCatalogItemInput = { id: string; providerDomain: string; name: string; description?: string | null; mcpUrl: string; transport: string; authKind: "oauth2" | "api_key" | "none" | "unknown"; credentialFacts: Array>; tier: "verified" | "community"; provenance: string; logoAssetPath?: string | null; /** * The row has no logo by policy (an overlay `logoSourceUrl: null`, or a * screened letter placeholder): clear any asset an earlier import stored. * Without it a null `logoAssetPath` keeps the existing asset, because a * skipped or failed fetch must not erase a good logo. */ clearLogoAsset?: boolean; importBatchId: string; scopesHint?: string[]; homepageUrl?: string | null; installUrl?: string | null; /** Curated catalog grouping. Defaults to the registry-wide "integrations". */ category?: string | null; tags?: string[]; metadata?: Record; }; export type RegistryCatalogSurfaceKey = { id: string; providerDomain: string; mcpUrl: string; }; export type EnableCapabilityInstallationInput = { accountId: string; workspaceId: string; capabilityId: string; kind: "mcp"; /** Automatic setup must preserve every existing installation, including disabled ones. */ onlyIfUninstalled?: boolean; config?: Record; metadata?: Record; /** The person turning it on or changing it; recorded as its installer. */ installedBySubjectId?: string | null; }; export type InstallPortableSkillInput = { accountId: string; workspaceId: string; subjectId: string; /** Required at runtime after 0426; omission fails before distribution writes. */ skillActor?: SkillActor; skillOperationId?: string; /** Host-canonical original request, including source/options/owner/explicit CAS, before resolution. */ skillRequestIdentity?: Record; capabilityId: string; pluginKey: string; source: "library" | "github" | "skills_sh"; sourceUrl: string; repositoryUrl: string; version?: string; sourceCommit: string; sourcePath: string; name: string; description: string; activationMode?: "workspace_managed" | "session_selected"; category?: string; tags?: string[]; provenance?: "platform" | "deployment" | "registry" | "workspace"; sourceProvenance?: string; contentSha256: string; totalBytes: number; license?: string | null; files: Array<{ path: string; content: string; byteSize: number; contentSha256: string; }>; owner?: PortableSkillOwner; expectedInstallationVersion?: number; }; export type InstalledPortableSkill = { skillReceipt: SkillWriteReceipt; created: boolean; capabilityId: string; pluginId: string; pluginVersionId: string; facetId: string; pluginInstallationId: string; facetInstallationId: string; installationVersion: number; source: "library" | "github" | "skills_sh"; version: string; sourceUrl: string; sourceCommit: string; contentSha256: string; name: string; }; export type PortableSkillRuntime = { capabilityId: string; source: "library" | "github" | "skills_sh"; version: string; name: string; description: string; activationMode: "workspace_managed" | "session_selected"; sourceUrl: string; sourceCommit: string; sourcePath: string; contentSha256: string; files: Array<{ path: string; content: string }>; }; export type InstalledSkillSummary = { capabilityId: string; pluginKey: string; installationVersion: number; name: string; description: string; category: string; tags: string[]; provenance: string; source: "library" | "github" | "skills_sh"; version: string; sourceUrl: string; repositoryUrl: string; sourceCommit: string; sourcePath: string; contentSha256: string; fileCount: number; totalBytes: number; license: string | null; installedAt: string; updatedAt: string; owners: PortableSkillOwner[]; }; export type PortableSkillOwner = { kind: "direct" | "plugin" | "migration"; id: string; removable: boolean; }; export type PortableSkillUninstallPreview = { capabilityId: string; installed: boolean; installationVersion: number | null; directOwner: PortableSkillOwner | null; remainingOwners: PortableSkillOwner[]; removesRuntimeSkill: boolean; }; export type UninstallPortableSkillResult = { capabilityId: string; status: "not_installed" | "uninstalled" | "retained_by_other_owners"; remainingOwners: PortableSkillOwner[]; skillReleases?: SkillSourceReleaseReceipt[]; }; export class PortableSkillInstallationVersionConflictError extends Error { readonly name = "PortableSkillInstallationVersionConflictError"; constructor( readonly capabilityId: string, readonly expectedVersion: number, readonly actualVersion: number, ) { super( `Portable Skill installation ${capabilityId} changed: expected version ${expectedVersion}, current version ${actualVersion}`, ); } } export class PortableSkillInstallationVersionRequiredError extends Error { readonly name = "PortableSkillInstallationVersionRequiredError"; } export class PortableSkillSourcePathConflictError extends Error { readonly name = "PortableSkillSourcePathConflictError"; } /** The Skill's metadata (for example its description) cannot be stored. */ export class PortableSkillMetadataError extends Error { readonly name = "PortableSkillMetadataError"; } /** Row checks on a Skill's own metadata and files: rejected input, not a fault. */ const PORTABLE_SKILL_METADATA_CONSTRAINT = /^(?:capability_skill_facets_[a-z_]+_chk|capability_skill_files_[a-z_]+_chk|capability_plugins_text_chk)$/u; function isPortableSkillMetadataViolation(error: unknown): boolean { for (const record of nestedErrorRecords(error)) { const constraint = record.constraint_name ?? record.constraint; if (typeof constraint === "string" && PORTABLE_SKILL_METADATA_CONSTRAINT.test(constraint)) return true; } return false; } const SKILL_FACET_DESCRIPTION_MAX_CHARS = 2048; /** * The Skill facet stores a one-line summary. SKILL.md descriptions may be YAML * block scalars (`description: |` or `>`) that keep line breaks; fold every * whitespace run to one space. The plugin row and the SKILL.md content keep the * original text, and nothing compares the facet summary back to SKILL.md. */ export function portableSkillFacetDescription(description: string): string { const line = description.replace(/\s+/gu, " ").trim(); if (line.length === 0 || line.length > SKILL_FACET_DESCRIPTION_MAX_CHARS) { throw new PortableSkillMetadataError( `A Skill description must be 1 to ${SKILL_FACET_DESCRIPTION_MAX_CHARS} characters`, ); } return line; } export type EnabledMcpCapabilityServer = { capabilityId: string; id: string; name: string; /** The catalog item's category ("communication", "files"), naming the need it serves. */ category?: string; url: string; allowedTools?: string[]; timeoutMs?: number; cacheToolsList?: boolean; requireApproval?: SessionMcpApprovalPolicy; approvalFloor?: SessionMcpApprovalPolicy; /** * Credential request headers stored encrypted at enable time * (AES-256-GCM under the workspace encryption key). Decrypted only at * the runtime boundary that builds the MCP client; never exposed by the * capability API surface. */ headersEncrypted?: Record; connectionRef?: McpServerConnectionRef; }; export type CreateSessionMcpServerInput = { id: string; name?: string | null; url: string; allowedTools?: string[] | null; timeoutMs?: number | null; cacheToolsList?: boolean | null; requireApproval?: SessionMcpApprovalPolicy | null; connectionRef?: McpServerConnectionRef | null; headersEncrypted?: Record; }; export type UpdateSessionMcpServerCredentialsInput = { id: string; headersEncrypted: Record; }; export type UpdateSessionMcpServerCredentialsResult = { servers: SessionMcpServerMetadata[]; missingIds: string[]; }; export type UpdateSessionMcpApprovalPolicyResult = { server: SessionMcpApprovalPolicyTarget | null; changed: boolean; }; export type SessionMcpServerForRun = SessionMcpServerMetadata & { allowedTools?: string[]; timeoutMs?: number; cacheToolsList?: boolean; requireApproval: SessionMcpApprovalPolicy; headers: Record; }; export type EnqueueSessionTurnInput = { accountId: string; workspaceId: string; sessionId: string; triggerEventId: string; temporalWorkflowId: string; source: SessionTurnSource; /** Content-free product surface the request entered through. */ surface?: SessionTurnSurface | null; /** Funding origin frozen on the turn; null inherits the session's latest. */ billingOrigin?: BillingOrigin | null; prompt: string; modelContext?: string | null; resources: ResourceRef[]; tools: ToolRef[]; toolsProvided?: boolean; model: string; reasoningEffort: ReasoningEffort; latencyMode?: LatencyMode; sandboxBackend: SandboxBackend; sandboxOs?: SandboxOs | null; metadata: Record; lineage?: Record; initiator: TurnInitiator; initiatorContext?: TurnInitiatorContext; personalConnectionDelegations?: McpPersonalConnectionDelegation[]; mcpAccountBindings?: McpConnectionAccountBinding[] | null; xaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1; claudeProviderAccountAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1; /** Steer inserts before all waiting prompts; Send appends after them. */ placement?: "head" | "tail"; }; /** Worker-only turn projection with causal authority omitted from public APIs. */ export type SessionTurnForExecution = SessionTurn & { personalConnectionDelegations: McpPersonalConnectionDelegation[]; mcpAccountBindings: McpConnectionAccountBinding[] | null; /** Worker-only causal authority; never inferred from the current worker. */ initiatingHumanSubjectId: string | null; scheduledTaskRunId: string | null; /** Funding origin frozen at acceptance; legacy null is app. */ billingOrigin: BillingOrigin; xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1; claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1; goalSnapshot: SessionGoalSnapshot; }; export async function createFileUpload( db: Database, input: { accountId: string; workspaceId: string; fileId: string; privateOwnerSubjectId?: string | null; filename: string; safeFilename: string; contentType: string; sizeBytes: number; sha256?: string | null; bucket: string; objectKey: string; expiresAt: Date; /** An app-shot's capture, stored with the file once. */ appShot?: AppShotCapture | null; }, ): Promise<{ file: FileAsset; uploadId: string; expiresAt: string }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [fileRow] = await tx .insert(schema.files) .values({ id: input.fileId, privateOwnerSubjectIds: input.privateOwnerSubjectId ? [input.privateOwnerSubjectId] : null, accountId: input.accountId, workspaceId: input.workspaceId, filename: input.filename, safeFilename: input.safeFilename, contentType: input.contentType, sizeBytes: input.sizeBytes, sha256: input.sha256 ?? null, bucket: input.bucket, objectKey: input.objectKey, appShot: input.appShot ?? null, status: "pending_upload", }) .returning(); if (!fileRow) { throw new Error("Failed to create file"); } const [uploadRow] = await tx .insert(schema.fileUploads) .values({ accountId: input.accountId, workspaceId: input.workspaceId, fileId: fileRow.id, privateFileOwnerSubjectId: input.privateOwnerSubjectId ?? null, status: "pending", expiresAt: input.expiresAt, }) .returning({ id: schema.fileUploads.id, expiresAt: schema.fileUploads.expiresAt, }); if (!uploadRow) { throw new Error("Failed to create file upload"); } return { file: mapFile(fileRow), uploadId: uploadRow.id, expiresAt: uploadRow.expiresAt.toISOString(), }; }), ); } export type PrepareGeneratedWorkspaceFileInput = { accountId: string; workspaceId: string; fileId: string; uploadId: string; filename: string; safeFilename: string; contentType: string; sizeBytes: number; sha256: string; bucket: string; objectKey: string; expiresAt: Date; /** * Who can open a newly prepared file: its private owner, or null for the * workspace. Omitted, the scope's private-file owner decides, as before. * An existing file keeps whatever audience its owner has since given it. */ privateOwnerSubjectId?: string | null; }; /** * Prepare one deterministic upload intent for a generated workspace file. * Retries return the same pending/ready file only when every immutable byte and * storage fact matches; identity reuse with different content fails closed. */ export async function prepareGeneratedWorkspaceFile( db: Database, input: PrepareGeneratedWorkspaceFileInput, ): Promise<{ file: FileAsset; uploadId: string; created: boolean }> { if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 1) { throw new TypeError("Editable artifact source size is invalid"); } if (!/^[0-9a-f]{64}$/u.test(input.sha256)) { throw new TypeError("Editable artifact source sha256 is invalid"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`generated-workspace-file:${input.workspaceId}:${input.fileId}`}, 0))`, ); // Callers scope this to the source session before retaining generated bytes. // This is a host-owned context value, never inferred from the file name. const [ownership] = await rawRows<{ owner: string | null }>( tx as unknown as Database, sql`SELECT nullif(current_setting('opengeni.private_file_owner',true),'') AS owner`, ); const privateOwner = input.privateOwnerSubjectId !== undefined ? input.privateOwnerSubjectId : (ownership?.owner ?? null); const [existing] = await tx .select({ file: schema.files, upload: schema.fileUploads }) .from(schema.files) .innerJoin( schema.fileUploads, and( eq(schema.fileUploads.workspaceId, schema.files.workspaceId), eq(schema.fileUploads.fileId, schema.files.id), eq(schema.fileUploads.id, input.uploadId), ), ) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ) .for("update") .limit(1); if (existing) { assertGeneratedWorkspaceFileMatches(existing.file, existing.upload, input); // Row-level security already hid it unless this scope may open it; // its owner may have shared or limited it since it was prepared. return { file: mapFile(existing.file), uploadId: existing.upload.id, created: false, }; } const [file] = await tx .insert(schema.files) .values({ id: input.fileId, privateOwnerSubjectIds: privateOwner ? [privateOwner] : null, accountId: input.accountId, workspaceId: input.workspaceId, status: "pending_upload", filename: input.filename, safeFilename: input.safeFilename, contentType: input.contentType, sizeBytes: input.sizeBytes, sha256: input.sha256, bucket: input.bucket, objectKey: input.objectKey, }) .returning(); if (!file) throw new Error("Failed to prepare generated workspace file"); const [upload] = await tx .insert(schema.fileUploads) .values({ id: input.uploadId, accountId: input.accountId, workspaceId: input.workspaceId, fileId: input.fileId, status: "pending", expiresAt: input.expiresAt, }) .returning(); if (!upload) throw new Error("Failed to prepare generated workspace file upload"); return { file: mapFile(file), uploadId: upload.id, created: true }; }), ); } function assertGeneratedWorkspaceFileMatches( file: typeof schema.files.$inferSelect, upload: typeof schema.fileUploads.$inferSelect, input: PrepareGeneratedWorkspaceFileInput, ): void { const statusMatches = (file.status === "pending_upload" && upload.status === "pending") || (file.status === "ready" && upload.status === "completed"); if ( !statusMatches || file.accountId !== input.accountId || file.workspaceId !== input.workspaceId || file.id !== input.fileId || upload.id !== input.uploadId || upload.accountId !== input.accountId || upload.workspaceId !== input.workspaceId || upload.fileId !== input.fileId || file.filename !== input.filename || file.safeFilename !== input.safeFilename || file.contentType !== input.contentType || file.sizeBytes !== input.sizeBytes || file.sha256 !== input.sha256 || file.bucket !== input.bucket || file.objectKey !== input.objectKey ) { throw new Error(`Generated workspace file identity conflict: ${input.fileId}`); } } export async function getFile( db: Database, workspaceId: string, fileId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.files) .where(and(eq(schema.files.workspaceId, workspaceId), eq(schema.files.id, fileId))) .limit(1); return row ? mapFile(row) : null; }); } export async function requireFile( db: Database, workspaceId: string, fileId: string, ): Promise { const file = await getFile(db, workspaceId, fileId); if (!file) { throw new Error(`File not found: ${fileId}`); } return file; } export type FileVisibilityChangeResult = | { kind: "changed" | "unchanged"; file: FileAsset } | { kind: "not_found" } | { kind: "not_owner" } | { kind: "not_changeable" }; /** Session screenshots and spilled tool results expire with their sessions. */ const UNSHAREABLE_FILE_OBJECT_KEY = /^workspaces\/[^/]+\/files\/[^/]+\/(retained|tool-results)\//u; /** * Share one finished file with the workspace, or limit a file back to its * owner. The file must already be visible to the caller's own scope. Only a * private owner shares it, only its owner limits it, and the database trigger * enforces the same two transitions. The change and its audit fact commit * together. Whether the owner may make anything Only me is decided first by * the caller. */ export async function updateFileVisibility( db: Database, input: { accountId: string; workspaceId: string; fileId: string; visibility: "private" | "workspace"; /** The person changing it: the human caller, or the human an agent acts for. */ actorSubjectId: string; /** Audit subject: the caller's own subject (an agent's technical subject). */ auditSubjectId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const [row] = await tx .select() .from(schema.files) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ) .for("update") .limit(1); if (!row) return { kind: "not_found" }; const current = row.privateOwnerSubjectIds ? "private" : "workspace"; if (current === input.visibility) return { kind: "unchanged", file: mapFile(row) }; if (row.status !== "ready" || UNSHAREABLE_FILE_OBJECT_KEY.test(row.objectKey)) return { kind: "not_changeable" }; const sharing = input.visibility === "workspace"; if ( sharing ? !row.privateOwnerSubjectIds?.includes(input.actorSubjectId) : row.ownerSubjectId !== input.actorSubjectId ) return { kind: "not_owner" }; // The change runs as its owner's private-file identity, the one the // row-level policies and the ownership trigger check, then restores the // caller's own identity for the rest of the transaction. const [previous] = await rawRows<{ owner: string | null }>( tx, sql`select current_setting('opengeni.private_file_owner', true) as owner`, ); await rawRows( tx, sql`select set_config('opengeni.private_file_owner', ${input.actorSubjectId}::text, true)`, ); const [updated] = await tx .update(schema.files) .set({ privateOwnerSubjectIds: sharing ? null : [input.actorSubjectId], ownerSubjectId: sharing ? (row.ownerSubjectId ?? input.actorSubjectId) : input.actorSubjectId, updatedAt: new Date(), }) .where(and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, row.id))) .returning(); await rawRows( tx, sql`select set_config('opengeni.private_file_owner', ${previous?.owner ?? ""}::text, true)`, ); if (!updated) return { kind: "not_found" }; await recordAuditEvent(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.auditSubjectId, action: "file.visibility.changed", targetType: "workspace_file", targetId: row.id, metadata: { fileId: row.id, from: current, to: input.visibility }, }); return { kind: "changed", file: mapFile(updated) }; }, ); } export type FileReachChangeResult = | { kind: "changed" | "unchanged"; file: FileAsset } | { kind: "not_found" } | { kind: "not_owner" } | { kind: "not_private" }; /** * Where the owner's Only me file works besides the workspace that stores it * and their Personal workspace: the other workspaces of the organization in * `reachWorkspaceIds`, or all of them (null). The caller resolves the list to * the owner's own workspaces of this organization first. Only the owner * changes it, from the workspace that stores the file, and the change and its * audit fact commit together. */ export async function updateFileReach( db: Database, input: { accountId: string; workspaceId: string; fileId: string; reachWorkspaceIds: readonly string[] | null; /** The owner: the human caller, or the human an agent acts for. */ actorSubjectId: string; /** Audit subject: the caller's own subject. */ auditSubjectId: string; }, ): Promise { const reach = input.reachWorkspaceIds === null ? null : [...new Set(input.reachWorkspaceIds)].filter((id) => id !== input.workspaceId).sort(); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { // Read and change it as its owner's private-file identity, the one the // row-level policies check, then restore the caller's own identity. const [previous] = await rawRows<{ owner: string | null }>( tx, sql`select current_setting('opengeni.private_file_owner', true) as owner`, ); await rawRows( tx, sql`select set_config('opengeni.private_file_owner', ${input.actorSubjectId}::text, true)`, ); const restore = async () => await rawRows( tx, sql`select set_config('opengeni.private_file_owner', ${previous?.owner ?? ""}::text, true)`, ); const [row] = await tx .select() .from(schema.files) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ) .for("update") .limit(1); if (!row) { await restore(); return { kind: "not_found" }; } if (!row.privateOwnerSubjectIds) { await restore(); return { kind: "not_private" }; } if (mapFile(row).ownerSubjectId !== input.actorSubjectId) { await restore(); return { kind: "not_owner" }; } const current = row.reachWorkspaceIds === null ? null : [...row.reachWorkspaceIds].sort(); if (JSON.stringify(current) === JSON.stringify(reach)) { await restore(); return { kind: "unchanged", file: mapFile(row) }; } const [updated] = await tx .update(schema.files) .set({ reachWorkspaceIds: reach, updatedAt: new Date() }) .where(and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, row.id))) .returning(); await restore(); if (!updated) return { kind: "not_found" }; await recordAuditEvent(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.auditSubjectId, action: "file.reach.changed", targetType: "workspace_file", targetId: row.id, metadata: { fileId: row.id, from: current, to: reach }, }); return { kind: "changed", file: mapFile(updated) }; }, ); } /** * Whether a finished file exists in this workspace but is Only me for someone * other than the caller. It reveals nothing else: no name, owner or content. */ export async function isFilePrivateToAnother( db: Database, input: { accountId: string; workspaceId: string; fileId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const [row] = await rawRows<{ private: boolean }>( tx, sql`select opengeni_private.file_private_to_another(${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.fileId}::uuid) as private`, ); return row?.private === true; }, ); } /** * Subject-bound file read for user-visible and model-injection surfaces. The * database predicate returns true for ordinary workspace files, but Drive- * derived bytes require current per-object ACL evidence for every protecting * mapping. Missing/stale/mixed denied mappings therefore look not found. */ export async function requireFileForSubject( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileId: string; }, ): Promise { if (currentSessionAttachmentReadAccess()) { const file = (await getFilesForSubject(db, { ...input, fileIds: [input.fileId] }))[0]; if (!file) throw new Error(`File not found: ${input.fileId}`); return file; } const reaching = filesReachingWorkspace(input); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); const subjectIdSql = input.subjectId === null ? sql`NULL::text` : sql`${input.subjectId}`; const [row] = await scopedDb .select() .from(schema.files) .where( and( eq(schema.files.accountId, input.accountId), reaching, eq(schema.files.id, input.fileId), sql`google_drive_file_authorized( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${subjectIdSql}, ${input.fileId}::uuid )`, ), ) .limit(1); if (!row) throw new Error(`File not found: ${input.fileId}`); return mapFile(row); }, ); } /** * The files a workspace may read for a person: its own, plus their Only me * files from the organization's other workspaces that work here, because the * file's reach list names this workspace or is null (every workspace, as all * files made before the list existed). In the person's own Personal * workspace all their Only me files work (docs/design/ownership-and-reach.md: * an Only me thing works where its owner turned it on, always in their * Personal workspace). Row-level security still decides whose Only me files * these are, and a Personal workspace has exactly one member, so a person * reading in one is its owner. The workspace kind is read once per statement * inside the caller's workspace context, never in a separate round trip. */ function filesReachingWorkspace(input: { accountId: string; workspaceId: string; subjectId: string | null; }): SQL { const reachesHere = or( isNull(schema.files.reachWorkspaceIds), sql`${input.workspaceId}::uuid = ANY(${schema.files.reachWorkspaceIds})`, ); return or( eq(schema.files.workspaceId, input.workspaceId), and( isNotNull(schema.files.privateOwnerSubjectIds), input.subjectId === null ? reachesHere : or( sql`(select get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid)) = 'personal'`, reachesHere, ), ), )!; } /** * Resolve a Document's immutable origin File through one database authority * statement. The resolver proves target-workspace Document visibility, live * portable-owner authority, and provider ACL before returning origin metadata; * it never grants generic visibility into the origin workspace's Files. */ export async function resolveDocumentOriginalFileForSubject( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; documentId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); const rows = await rawRows( scopedDb, sql`select original_file.id as "id", original_file.account_id as "accountId", original_file.workspace_id as "workspaceId", original_file.status as "status", original_file.filename as "filename", original_file.safe_filename as "safeFilename", original_file.content_type as "contentType", original_file.size_bytes::double precision as "sizeBytes", original_file.sha256 as "sha256", original_file.bucket as "bucket", original_file.object_key as "objectKey", original_file.created_at::text as "createdAt", original_file.updated_at::text as "updatedAt" from resolve_document_original_file( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}, ${input.documentId}::uuid ) original_file`, ); return rows[0] ?? null; }, ); } /** Batch form of requireFileForSubject; unauthorized or missing ids are omitted. */ /** * Ready originals the caller can see here, newest first, filtered by owner RLS * and provider ACL before pagination. * * A page costs about its size, not the organization's file count. The files * the caller can see are disjoint sets, and each is read newest first from its * own index, stopping after one page (`fileListCandidates`). Row-level * security still applies to every read. Another person's private file is * readable only through a capability that one function call holds for its * own duration, so no listing returns one. * * The provider ACL function writes a capability row per call, so it runs only * for the page's candidates after they are ordered and limited. A rejected * candidate is skipped and the walk continues after it. */ export async function listFilesForSubject( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; scope?: "all" | "workspace" | "personal"; limit?: number; cursor?: string | undefined; /** Cancels the running statement when the caller has gone away. */ signal?: AbortSignal | undefined; }, ): Promise<{ files: FileAsset[]; nextCursor: string | null }> { const limit = input.limit ?? 30; if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new RangeError("Invalid file page size"); let after: FileListPosition | null = null; if (input.cursor) { try { after = z .object({ id: z.uuid(), at: z.string().datetime({ offset: true }) }) .strict() .parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"))); } catch { throw new z.ZodError([{ code: "custom", path: ["cursor"], message: "Invalid file cursor" }]); } } return withDatabaseQueryCancellation(db, input.signal, () => withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { if (input.subjectId) await setSubjectRlsContext(tx, input.subjectId); // A person sees all their own files in their Personal workspace. A // read without a person keeps to what reaches this workspace. const personalWorkspace = input.subjectId !== null && input.scope !== "workspace" ? ( await rawRows<{ kind: string }>( tx, sql`select get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) as kind`, ) )[0]?.kind === "personal" : false; const rows: FileListCandidate[] = []; for (let from = after; ;) { const wanted = limit + 1 - rows.length; const candidates = await fileListCandidates( tx, { ...input, personalWorkspace }, from, wanted, ); const authorized = await providerAuthorizedFileIds( tx, input, candidates.map((row) => row.file.id), ); rows.push(...candidates.filter((row) => authorized.has(row.file.id))); const last = candidates.at(-1); if (!last || candidates.length < wanted || rows.length > limit) break; from = { id: last.file.id, at: last.position }; } const page = rows.slice(0, limit), last = page.at(-1); return { files: page.map((row) => mapFile(row.file)), nextCursor: rows.length > limit && last ? Buffer.from(JSON.stringify({ id: last.file.id, at: last.position })).toString( "base64url", ) : null, }; }, ), ); } type FileListPosition = { id: string; at: string }; type FileListCandidate = { file: typeof schema.files.$inferSelect; position: string }; /** * The next `limit` files the caller may see, newest first, before the provider * ACL. Each branch is an ordered walk of one index (migrations 1409-1412) that * stops after `limit` rows: * * - shared: this workspace's shared files; * - own files, keyed on their one owner (1431) and the owner the row-level * security policy reads; a read without an owner sees none. In a Personal * workspace that is every own file: those that may reach other workspaces * (reach null or listed) and those that stay where they were made. Elsewhere * it is the own files made here, plus own files made elsewhere whose reach * includes here. * * Owner and status are index conditions because subscripting and text * equality are leakproof, which row-level security requires; array operators * and `coalesce` are not. Reach is a partial-index predicate for the same * reason. A walk skips only rows whose explicit reach list leaves this * workspace out. */ async function fileListCandidates( tx: Database, input: { accountId: string; workspaceId: string; scope?: "all" | "workspace" | "personal"; personalWorkspace: boolean; }, after: FileListPosition | null, limit: number, ): Promise { const newestFirst = [desc(schema.files.createdAt), desc(schema.files.id)] as const; const walk = (where: SQL | undefined) => tx .select({ file: schema.files, position: sql`to_char(${schema.files.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, }) .from(schema.files) .where( and( eq(schema.files.accountId, input.accountId), eq(schema.files.status, "ready"), after ? sql`(${schema.files.createdAt}, ${schema.files.id}) < (${after.at}::text::timestamptz, ${after.id}::uuid)` : undefined, where, ), ) .orderBy(...newestFirst) .limit(limit); const own = sql`${schema.files.privateOwnerSubjectIds} IS NOT NULL AND ${schema.files.privateOwnerSubjectIds}[1] = nullif(current_setting('opengeni.private_file_owner', true), '')`; const roaming = sql`(${schema.files.reachWorkspaceIds} IS NULL OR cardinality(${schema.files.reachWorkspaceIds}) > 0)`; const branches = []; if (input.scope !== "personal") branches.push( walk( and( eq(schema.files.workspaceId, input.workspaceId), isNull(schema.files.privateOwnerSubjectIds), ), ), ); if (input.scope !== "workspace" && input.personalWorkspace) branches.push( walk(and(own, roaming)), walk( and( own, sql`${schema.files.reachWorkspaceIds} IS NOT NULL AND cardinality(${schema.files.reachWorkspaceIds}) = 0`, ), ), ); if (input.scope !== "workspace" && !input.personalWorkspace) branches.push( walk(and(own, eq(schema.files.workspaceId, input.workspaceId))), walk( and( own, roaming, ne(schema.files.workspaceId, input.workspaceId), or( isNull(schema.files.reachWorkspaceIds), sql`${input.workspaceId}::uuid = ANY(${schema.files.reachWorkspaceIds})`, ), ), ), ); const [first, second, ...rest] = branches; if (!second) return await first!; return await unionAll(first!, second, ...rest) .orderBy(...newestFirst) .limit(limit); } /** The candidates the Google Drive provider ACL allows, one function call each. */ async function providerAuthorizedFileIds( tx: Database, input: { accountId: string; workspaceId: string; subjectId: string | null }, fileIds: readonly string[], ): Promise> { if (fileIds.length === 0) return new Set(); const rows = await rawRows<{ id: string }>( tx, sql`select candidate.id from unnest(${new Param([...fileIds])}::uuid[]) as candidate(id) where google_drive_file_authorized(${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}::text, candidate.id)`, ); return new Set(rows.map((row) => row.id)); } export async function getFilesForSubject( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileIds: readonly string[]; }, ): Promise { const ids = [...new Set(input.fileIds)]; if (ids.length === 0) return []; const reaching = filesReachingWorkspace(input); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { // A service continuation has no human file authority. Its ambient actor // (for example service:agent-turn) must not disagree with the explicit null // passed to the file ACL function, or ordinary shared files disappear. const [previousScope] = input.subjectId === null ? await scopedDb.execute<{ subject: string | null; owner: string | null }>(sql` select current_setting('opengeni.subject_id', true) as subject, current_setting('opengeni.private_file_owner', true) as owner`) : []; if (input.subjectId === null) { await scopedDb.execute(sql`select set_config('opengeni.subject_id', '', true), set_config('opengeni.private_file_owner', '', true)`); } else { await setSubjectRlsContext(scopedDb, input.subjectId); } const subjectIdSql = input.subjectId === null ? sql`NULL::text` : sql`${input.subjectId}`; const rows = await scopedDb .select() .from(schema.files) .where( and( eq(schema.files.accountId, input.accountId), reaching, inArray(schema.files.id, ids), sql`google_drive_file_authorized( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${subjectIdSql}, ${schema.files.id} )`, ), ); // withRlsContext can be a savepoint on a caller's transaction. Restore // its actor scope so this read cannot change later authorization. // On query failure, savepoint rollback restores scope; do not mask the // original SQLSTATE by issuing SQL in an aborted transaction. if (input.subjectId === null) { await scopedDb.execute(sql`select set_config('opengeni.subject_id', ${previousScope?.subject ?? ""}, true), set_config('opengeni.private_file_owner', ${previousScope?.owner ?? ""}, true)`); } const ordinary = rows.map(mapFile); const access = currentSessionAttachmentReadAccess(); if (!access) return ordinary; const missing = ids.filter((id) => !ordinary.some((file) => file.id === id)); const shared = await readSessionFileAttachments(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, fileIds: missing, access, }); return [...ordinary, ...shared]; }, ); } /** One RLS-scoped query for all attachment metadata needed by a model turn. */ export async function getFiles( db: Database, workspaceId: string, fileIds: readonly string[], ): Promise { const ids = [...new Set(fileIds)]; if (ids.length === 0) return []; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.files) .where(and(eq(schema.files.workspaceId, workspaceId), inArray(schema.files.id, ids))); return rows.map(mapFile); }); } /** Build the canonical user row with stable attachment refs, never inline bytes. */ export function durableUserHistoryItem( prompt: string, resources: readonly ResourceRef[], annotations: readonly TimelineAnnotation[] = [], modelContext?: string | null, goalSnapshot?: SessionGoalSnapshot, sentAt?: Date | null, sender?: string | null, timeZone?: string | null, ): Record { const attachmentRefs = resources.filter( (resource): resource is Extract => resource.kind === "file", ); return { type: "message", role: "user", content: renderUserMessageContentForModel( prompt, annotations, modelContext, goalSnapshot, sentAt, sender, timeZone, ), ...(attachmentRefs.length > 0 ? { [MODEL_ATTACHMENT_REFS_FIELD]: attachmentRefs, [MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION_FIELD]: MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION, [MODEL_ATTACHMENT_CONVERTED_IMAGE_FORMATS_FIELD]: [ ...MODEL_ATTACHMENT_CONVERTED_IMAGE_FORMATS, ], } : {}), ...(annotations.length > 0 ? { [MODEL_TIMELINE_ANNOTATIONS_FIELD]: TimelineAnnotations.parse(annotations), } : {}), }; } export type RetainedFileArtifact = { file: FileAsset; uploadStatus: FileUploadStatus | null; uploadExpiresAt: Date | null; }; /** * RLS-scoped file lookup with just enough upload lifecycle truth to distinguish * pending, failed, and expired artifact references. The bytes and provider * location remain in the existing FileAsset/object-storage seam. */ export async function getRetainedFileArtifact( db: Database, workspaceId: string, fileId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ file: schema.files, uploadStatus: schema.fileUploads.status, uploadExpiresAt: schema.fileUploads.expiresAt, }) .from(schema.files) .leftJoin( schema.fileUploads, and( eq(schema.fileUploads.workspaceId, schema.files.workspaceId), eq(schema.fileUploads.fileId, schema.files.id), ), ) .where(and(eq(schema.files.workspaceId, workspaceId), eq(schema.files.id, fileId))) .orderBy(desc(schema.fileUploads.createdAt)) .limit(1); if (!row) return null; return { file: mapFile(row.file), uploadStatus: row.uploadStatus as FileUploadStatus | null, uploadExpiresAt: row.uploadExpiresAt, }; }); } export type RetainedScreenshotArtifactStatus = | "pending" | "reconciling" | "ready" | "cleanup_queued" | "cleanup_pending" | "failed" | "expired" | "deleted"; export type RetainedScreenshotQuotaState = "reserved" | "ready" | "released"; export type RetainedScreenshotArtifact = { artifactId: string; accountId: string; workspaceId: string; sessionId: string | null; turnId: string | null; attemptId: string | null; settlementKey: string; toolCallId: string; toolOutputId: string; status: RetainedScreenshotArtifactStatus; quotaState: RetainedScreenshotQuotaState; mediaType: string; sizeBytes: number; sha256: string; width: number; height: number; retentionExpiresAt: Date; readyAt: Date | null; cleanupReason: string | null; lastError: string | null; maintenanceClaimId: string | null; maintenanceClaimedAt: Date | null; createdAt: Date; updatedAt: Date; file: FileAsset; }; export class RetainedScreenshotQuotaExceededError extends Error { readonly code = "retained_screenshot_workspace_quota_exceeded"; constructor( readonly quotaBytes: number, readonly usedBytes: number, readonly requestedBytes: number, ) { super( `Retained screenshot workspace quota exceeded: ${usedBytes} + ${requestedBytes} > ${quotaBytes}`, ); this.name = "RetainedScreenshotQuotaExceededError"; } } export type PrepareRetainedScreenshotArtifactInput = { artifactId: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; settlementKey: string; toolCallId: string; toolOutputId: string; mediaType: "image/png" | "image/jpeg" | "image/webp"; sizeBytes: number; sha256: string; width: number; height: number; retentionExpiresAt: Date; bucket: string; objectKey: string; workspaceQuotaBytes: number; }; /** * Queue the workspace's oldest ready images for cleanup until at least * `neededBytes` are on their way out, counting images already queued. Runs * inside the caller's workspace-scoped transaction, which holds the quota row * lock, through the migration's workspace-checked SECURITY DEFINER seam: the * quota is workspace-wide, so eviction must see images in every session. * Returns the bytes leaving, which may be less than needed. */ async function makeRoomForRetainedScreenshot( tx: Database, input: { accountId: string; workspaceId: string; neededBytes: number }, ): Promise { const [row] = await rawRows<{ leaving: string | number }>( tx, sql`select opengeni_private.make_room_for_retained_screenshot( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.neededBytes}::bigint ) as leaving`, ); return Number(row?.leaving ?? 0); } /** * Reserve quota and create one deterministic pending file/artifact pair. * Replays return the original row only when every immutable identity and byte * fact matches; a UUID/settlement collision fails closed. */ export async function prepareRetainedScreenshotArtifact( db: Database, input: PrepareRetainedScreenshotArtifactInput, ): Promise<{ artifact: RetainedScreenshotArtifact; created: boolean }> { return await retryRlsPersistence( db, { accountId: input.accountId, workspaceId: input.workspaceId }, { stage: "retained_screenshot_prepare", correlationId: input.settlementKey, }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); if (!locks.sessions[0] || !locks.turns[0] || !locks.attempts[0]) { throw new Error( `Retained screenshot parent rows missing: ${input.sessionId}/${input.turnId}/${input.attemptId}`, ); } await tx .insert(schema.workspaceScreenshotQuotas) .values({ accountId: input.accountId, workspaceId: input.workspaceId, }) .onConflictDoNothing({ target: schema.workspaceScreenshotQuotas.workspaceId, }); const [existing] = await tx .select({ artifact: schema.retainedScreenshotArtifacts, file: schema.files, }) .from(schema.retainedScreenshotArtifacts) .innerJoin( schema.files, and( eq(schema.files.workspaceId, schema.retainedScreenshotArtifacts.workspaceId), eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId), ), ) .where(eq(schema.retainedScreenshotArtifacts.settlementKey, input.settlementKey)) .for("update") .limit(1); if (existing) { const artifact = mapRetainedScreenshotArtifact(existing.artifact, existing.file); assertRetainedScreenshotReplayMatches(artifact, input); return { artifact, created: false }; } const [quota] = await tx .select() .from(schema.workspaceScreenshotQuotas) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)) .for("update") .limit(1); if (!quota) { throw new Error(`Screenshot quota row not found: ${input.workspaceId}`); } const usedBytes = quota.reservedBytes + quota.readyBytes; const neededBytes = usedBytes + input.sizeBytes - input.workspaceQuotaBytes; if (neededBytes > 0) { // A full quota keeps the newest images: the workspace's oldest // images are queued for cleanup to make room. Only an image larger // than the whole quota is refused. const leavingBytes = input.sizeBytes > input.workspaceQuotaBytes ? 0 : await makeRoomForRetainedScreenshot(tx, { accountId: input.accountId, workspaceId: input.workspaceId, neededBytes, }); if (leavingBytes < neededBytes) { throw new RetainedScreenshotQuotaExceededError( input.workspaceQuotaBytes, usedBytes - leavingBytes, input.sizeBytes, ); } } const [file] = await tx .insert(schema.files) .values({ id: input.artifactId, privateOwnerSubjectIds: sql`CASE WHEN nullif(current_setting('opengeni.private_file_owner',true),'') IS NULL THEN NULL ELSE ARRAY[current_setting('opengeni.private_file_owner',true)] END`, accountId: input.accountId, workspaceId: input.workspaceId, status: "pending_upload", filename: `computer-screenshot-${input.artifactId}.png`, safeFilename: `computer-screenshot-${input.artifactId}.png`, contentType: input.mediaType, sizeBytes: input.sizeBytes, sha256: input.sha256, bucket: input.bucket, objectKey: input.objectKey, }) .returning(); if (!file) throw new Error("Failed to create retained screenshot file"); const [artifact] = await tx .insert(schema.retainedScreenshotArtifacts) .values({ artifactId: input.artifactId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, attemptId: input.attemptId, settlementKey: input.settlementKey, toolCallId: input.toolCallId, toolOutputId: input.toolOutputId, status: "pending", quotaState: "reserved", mediaType: input.mediaType, sizeBytes: input.sizeBytes, sha256: input.sha256, width: input.width, height: input.height, retentionExpiresAt: input.retentionExpiresAt, }) .returning(); if (!artifact) throw new Error("Failed to create retained screenshot artifact"); await tx .update(schema.workspaceScreenshotQuotas) .set({ reservedBytes: sql`${schema.workspaceScreenshotQuotas.reservedBytes} + ${input.sizeBytes}`, updatedAt: new Date(), }) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)); return { artifact: mapRetainedScreenshotArtifact(artifact, file), created: true, }; }), ); } /** Settle one exact pending/reconciling artifact ready and move its quota once. */ export async function settleRetainedScreenshotArtifactReady( db: Database, input: { accountId: string; workspaceId: string; artifactId: string; settlementKey: string; maintenanceClaimId?: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [artifact] = await tx .select() .from(schema.retainedScreenshotArtifacts) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ) .for("update") .limit(1); if (!artifact || artifact.settlementKey !== input.settlementKey) { throw new Error(`Retained screenshot settlement not found: ${input.artifactId}`); } const [quota] = await tx .select() .from(schema.workspaceScreenshotQuotas) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)) .for("update") .limit(1); const [file] = await tx .select() .from(schema.files) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ) .for("update") .limit(1); if (!quota || !file) throw new Error(`Retained screenshot backing rows missing: ${input.artifactId}`); if ( artifact.status === "ready" && artifact.quotaState === "ready" && file.status === "ready" ) { return mapRetainedScreenshotArtifact(artifact, file); } if (artifact.status !== "pending" && artifact.status !== "reconciling") { throw new Error(`Retained screenshot is ${artifact.status}: ${input.artifactId}`); } if (artifact.quotaState !== "reserved") { throw new Error( `Retained screenshot quota state is ${artifact.quotaState}: ${input.artifactId}`, ); } if ( input.maintenanceClaimId !== undefined && artifact.maintenanceClaimId !== input.maintenanceClaimId ) { throw new Error( `Retained screenshot maintenance claim was superseded: ${input.artifactId}`, ); } if (quota.reservedBytes < artifact.sizeBytes) { throw new Error( `Retained screenshot reserved-byte invariant failed: ${input.artifactId}`, ); } const now = new Date(); const [updatedArtifact] = await tx .update(schema.retainedScreenshotArtifacts) .set({ status: "ready", quotaState: "ready", readyAt: now, cleanupReason: null, lastError: null, maintenanceClaimId: null, maintenanceClaimedAt: null, updatedAt: now, }) .where(eq(schema.retainedScreenshotArtifacts.artifactId, artifact.artifactId)) .returning(); const [updatedFile] = await tx .update(schema.files) .set({ status: "ready", updatedAt: now }) .where(eq(schema.files.id, artifact.artifactId)) .returning(); await tx .update(schema.workspaceScreenshotQuotas) .set({ reservedBytes: sql`${schema.workspaceScreenshotQuotas.reservedBytes} - ${artifact.sizeBytes}`, readyBytes: sql`${schema.workspaceScreenshotQuotas.readyBytes} + ${artifact.sizeBytes}`, updatedAt: now, }) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)); if (!updatedArtifact || !updatedFile) { throw new Error(`Failed to settle retained screenshot: ${input.artifactId}`); } return mapRetainedScreenshotArtifact(updatedArtifact, updatedFile); }), ); } /** Record a bounded diagnostic while preserving retryable pending truth. */ export async function recordRetainedScreenshotArtifactError( db: Database, input: { accountId: string; workspaceId: string; artifactId: string; settlementKey: string; error: string; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .update(schema.retainedScreenshotArtifacts) .set({ lastError: input.error.slice(0, 512), updatedAt: new Date() }) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), eq(schema.retainedScreenshotArtifacts.settlementKey, input.settlementKey), sql`${schema.retainedScreenshotArtifacts.status} in ('pending', 'reconciling')`, ), ); }, ); } /** Session-qualified lookup: a screenshot from another session is indistinguishable from absent. */ export async function getRetainedScreenshotArtifact( db: Database, workspaceId: string, sessionId: string, artifactId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ artifact: schema.retainedScreenshotArtifacts, file: schema.files, }) .from(schema.retainedScreenshotArtifacts) .innerJoin( schema.files, and( eq(schema.files.workspaceId, schema.retainedScreenshotArtifacts.workspaceId), eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId), ), ) .where(retainedScreenshotSessionArtifactPredicate(workspaceId, sessionId, artifactId)) .limit(1); return row ? mapRetainedScreenshotArtifact(row.artifact, row.file) : null; }); } /** * This session's own retained screenshots among `artifactIds`, in one query. * Screenshots a fork reaches through its ancestry are left out; resolve each * of those with getRetainedScreenshotArtifact, which proves the copied receipt. */ export async function getSessionRetainedScreenshotArtifacts( db: Database, workspaceId: string, sessionId: string, artifactIds: readonly string[], ): Promise> { const found = new Map(); if (artifactIds.length === 0) return found; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ artifact: schema.retainedScreenshotArtifacts, file: schema.files, }) .from(schema.retainedScreenshotArtifacts) .innerJoin( schema.files, and( eq(schema.files.workspaceId, schema.retainedScreenshotArtifacts.workspaceId), eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId), ), ) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, workspaceId), eq(schema.retainedScreenshotArtifacts.sessionId, sessionId), inArray(schema.retainedScreenshotArtifacts.artifactId, [...new Set(artifactIds)]), ), ); for (const row of rows) { found.set(row.artifact.artifactId, mapRetainedScreenshotArtifact(row.artifact, row.file)); } return found; }); } function retainedScreenshotSessionArtifactPredicate( workspaceId: string, sessionId: string, artifactId: string, ) { return and( eq(schema.retainedScreenshotArtifacts.workspaceId, workspaceId), or( eq(schema.retainedScreenshotArtifacts.sessionId, sessionId), // A fork copies canonical receipts, not the original artifact row. // Require both recorded ancestry and an actually copied image receipt; // knowing an ancestor artifact UUID is not enough. All reads retain RLS. sql`exists ( with recursive lineage(id, parent_id) as ( select s.id, s.forked_from_session_id from sessions s where s.workspace_id = ${workspaceId} and s.id = ${sessionId} union select s.id, s.forked_from_session_id from sessions s join lineage l on s.id = l.parent_id where s.workspace_id = ${workspaceId} ) select 1 from lineage l where l.id = ${schema.retainedScreenshotArtifacts.sessionId} and exists ( select 1 from session_history_items h where h.workspace_id = ${workspaceId} and h.session_id = ${sessionId} and h.turn_id is null and ( h.item @> ${JSON.stringify({ output: { type: "retained_artifact", artifact: { artifactId } } })}::jsonb or h.item @> ${JSON.stringify({ output: [{ image: { type: "retained_artifact", artifact: { artifactId } } }] })}::jsonb or h.item @> ${JSON.stringify({ output: { content: [{ image: { type: "retained_artifact", artifact: { artifactId } } }] } })}::jsonb ) ) )`, ), eq(schema.retainedScreenshotArtifacts.artifactId, artifactId), ); } /** Recover a legacy damaged receipt only when its tool call has one exact * screenshot in this session. Never infer an artifact across fork ancestry. */ export async function getRetainedScreenshotArtifactForToolCall( db: Database, workspaceId: string, sessionId: string, toolCallId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ artifact: schema.retainedScreenshotArtifacts, file: schema.files }) .from(schema.retainedScreenshotArtifacts) .innerJoin( schema.files, and( eq(schema.files.workspaceId, schema.retainedScreenshotArtifacts.workspaceId), eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId), ), ) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, workspaceId), eq(schema.retainedScreenshotArtifacts.sessionId, sessionId), eq(schema.retainedScreenshotArtifacts.toolCallId, toolCallId), ), ) .limit(2); return rows.length === 1 ? mapRetainedScreenshotArtifact(rows[0]!.artifact, rows[0]!.file) : null; }); } /** Recover a legacy damaged receipt's artifact id when its tool call has one * exact screenshot in this session whose file the current file authority hides. * The file foreign key restricts deleting a file while its artifact row exists, * so such a row is an authority exclusion, never a deletion. Returns only the * id; the caller projects it as a neutral receipt without bytes. */ export async function getWithheldRetainedScreenshotArtifactIdForToolCall( db: Database, workspaceId: string, sessionId: string, toolCallId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ artifactId: schema.retainedScreenshotArtifacts.artifactId, fileId: schema.files.id, }) .from(schema.retainedScreenshotArtifacts) .leftJoin( schema.files, and( eq(schema.files.workspaceId, schema.retainedScreenshotArtifacts.workspaceId), eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId), ), ) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, workspaceId), eq(schema.retainedScreenshotArtifacts.sessionId, sessionId), eq(schema.retainedScreenshotArtifacts.toolCallId, toolCallId), ), ) .limit(2); return rows.length === 1 && rows[0]!.fileId === null ? rows[0]!.artifactId : null; }); } export type RetainedScreenshotMaintenanceClaim = { action: "reconcile" | "delete"; claimId: string; artifactId: string; accountId: string; workspaceId: string; sessionId: string | null; objectKey: string; mediaType: string; sizeBytes: number; sha256: string; width: number; height: number; retentionExpiresAt: Date; cleanupReason: string | null; }; /** Bounded global claim through the migration's sole FORCE-RLS bypass. */ export async function claimRetainedScreenshotMaintenance( db: Database, input: { pendingGraceMs: number; claimTimeoutMs: number; limit: number }, ): Promise { const rows = await rawRows<{ action: "reconcile" | "delete"; claim_id: string; artifact_id: string; account_id: string; workspace_id: string; session_id: string | null; object_key: string; media_type: string; size_bytes: string | number; sha256: string; width: number; height: number; retention_expires_at: Date; cleanup_reason: string | null; }>( db, sql` select * from opengeni_private.claim_retained_screenshot_maintenance( ${input.pendingGraceMs}, ${input.claimTimeoutMs}, ${input.limit} ) `, ); return rows.map((row) => ({ action: row.action, claimId: row.claim_id, artifactId: row.artifact_id, accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, objectKey: row.object_key, mediaType: row.media_type, sizeBytes: Number(row.size_bytes), sha256: row.sha256, width: row.width, height: row.height, retentionExpiresAt: new Date(row.retention_expires_at), cleanupReason: row.cleanup_reason, })); } /** * Atomically transfer one exact reconcile claim into cleanup ownership before * any provider delete. A concurrent ready settlement clears/replaces the claim * and makes this a stale no-op. */ export async function promoteRetainedScreenshotMaintenanceCleanup( db: Database, input: { accountId: string; workspaceId: string; artifactId: string; claimId: string; cleanupReason: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [updated] = await scopedDb .update(schema.retainedScreenshotArtifacts) .set({ status: "cleanup_pending", cleanupReason: input.cleanupReason.slice(0, 128), updatedAt: new Date(), }) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), eq(schema.retainedScreenshotArtifacts.status, "reconciling"), eq(schema.retainedScreenshotArtifacts.maintenanceClaimId, input.claimId), ), ) .returning({ artifactId: schema.retainedScreenshotArtifacts.artifactId, }); return updated !== undefined; }, ); } /** * Complete a claimed reconcile/delete operation and release exactly one quota * bucket. A lost response is idempotent on the requested terminal state. */ export async function completeRetainedScreenshotMaintenance( db: Database, input: Parameters[1], ): Promise { return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const [claim] = await tx .select({ owner: schema.retainedScreenshotArtifacts.privateFileOwnerSubjectId, claimId: schema.retainedScreenshotArtifacts.maintenanceClaimId, status: schema.retainedScreenshotArtifacts.status, }) .from(schema.retainedScreenshotArtifacts) .where( and( eq(schema.retainedScreenshotArtifacts.accountId, input.accountId), eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ) .limit(1); if ( claim && claim.claimId !== input.claimId && !(claim.claimId === null && claim.status === input.outcome) ) return false; // Maintenance runs without an acting subject, which keeps every session // in the workspace visible, including another member's private chat. A // service subject would hide user-private sessions, and with them their // screenshot rows, so expiry could never settle. Only an image held as // a private file needs an actor, and then it acts as that file's owner: // the owner's own private sessions stay visible to it. if (!claim?.owner) return completeRetainedScreenshotMaintenanceInOwnerScope(tx, input); return withSessionRlsActorContext( { subjectId: "service:retained-screenshot-maintenance", initiatingHumanSubjectId: claim.owner, privateFileOwnerSubjectId: claim.owner, }, () => completeRetainedScreenshotMaintenanceInOwnerScope(tx, input), ); }, ); } async function completeRetainedScreenshotMaintenanceInOwnerScope( db: Database, input: { accountId: string; workspaceId: string; artifactId: string; claimId: string; outcome: "ready" | "failed" | "expired" | "deleted"; }, ): Promise { if (input.outcome === "ready") { const current = await getRetainedScreenshotArtifactByWorkspace( db, input.accountId, input.workspaceId, input.artifactId, ); if (!current) return false; await settleRetainedScreenshotArtifactReady(db, { accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, settlementKey: current.settlementKey, maintenanceClaimId: input.claimId, }); return true; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [artifact] = await tx .select() .from(schema.retainedScreenshotArtifacts) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ) .for("update") .limit(1); if (!artifact) { if (input.outcome !== "deleted") return false; const [file] = await tx .select({ id: schema.files.id }) .from(schema.files) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ) .limit(1); return file === undefined; } if (artifact.status === input.outcome && artifact.quotaState === "released") { if (input.outcome !== "deleted") return true; await tx .delete(schema.retainedScreenshotArtifacts) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ); await tx .delete(schema.files) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ); return true; } if ( artifact.status !== "cleanup_pending" || artifact.maintenanceClaimId !== input.claimId ) { return false; } const [quota] = await tx .select() .from(schema.workspaceScreenshotQuotas) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)) .for("update") .limit(1); const [file] = await tx .select() .from(schema.files) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ) .for("update") .limit(1); if (!quota || !file) return false; if (artifact.quotaState === "released") { throw new Error( `Retained screenshot quota was already released before terminal settlement: ${input.artifactId}`, ); } if ( artifact.quotaState === "ready" ? quota.readyBytes < artifact.sizeBytes : quota.reservedBytes < artifact.sizeBytes ) { throw new Error(`Retained screenshot quota invariant failed: ${input.artifactId}`); } const now = new Date(); await tx .update(schema.retainedScreenshotArtifacts) .set({ status: input.outcome, quotaState: "released", cleanupReason: artifact.cleanupReason ?? input.outcome, maintenanceClaimId: null, maintenanceClaimedAt: null, updatedAt: now, }) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ); await tx .update(schema.workspaceScreenshotQuotas) .set({ ...(artifact.quotaState === "ready" ? { readyBytes: sql`${schema.workspaceScreenshotQuotas.readyBytes} - ${artifact.sizeBytes}`, } : { reservedBytes: sql`${schema.workspaceScreenshotQuotas.reservedBytes} - ${artifact.sizeBytes}`, }), updatedAt: now, }) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, input.workspaceId)); if (input.outcome === "deleted") { await tx .delete(schema.retainedScreenshotArtifacts) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, input.workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, input.artifactId), ), ); await tx .delete(schema.files) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ); } else { await tx .update(schema.files) .set({ status: input.outcome, updatedAt: now }) .where( and( eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.artifactId), ), ); } return true; }), ); } export async function getWorkspaceScreenshotQuota( db: Database, workspaceId: string, ): Promise<{ reservedBytes: number; readyBytes: number } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ reservedBytes: schema.workspaceScreenshotQuotas.reservedBytes, readyBytes: schema.workspaceScreenshotQuotas.readyBytes, }) .from(schema.workspaceScreenshotQuotas) .where(eq(schema.workspaceScreenshotQuotas.workspaceId, workspaceId)) .limit(1); return row ?? null; }); } async function getRetainedScreenshotArtifactByWorkspace( db: Database, accountId: string, workspaceId: string, artifactId: string, ): Promise { return await withRlsContext(db, { accountId, workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select({ artifact: schema.retainedScreenshotArtifacts, file: schema.files, }) .from(schema.retainedScreenshotArtifacts) .innerJoin(schema.files, eq(schema.files.id, schema.retainedScreenshotArtifacts.artifactId)) .where( and( eq(schema.retainedScreenshotArtifacts.workspaceId, workspaceId), eq(schema.retainedScreenshotArtifacts.artifactId, artifactId), ), ) .limit(1); return row ? mapRetainedScreenshotArtifact(row.artifact, row.file) : null; }); } function assertRetainedScreenshotReplayMatches( artifact: RetainedScreenshotArtifact, input: PrepareRetainedScreenshotArtifactInput, ): void { const exact = artifact.artifactId === input.artifactId && artifact.accountId === input.accountId && artifact.workspaceId === input.workspaceId && artifact.sessionId === input.sessionId && artifact.turnId === input.turnId && artifact.attemptId === input.attemptId && artifact.toolCallId === input.toolCallId && artifact.toolOutputId === input.toolOutputId && artifact.mediaType === input.mediaType && artifact.sizeBytes === input.sizeBytes && artifact.sha256 === input.sha256 && artifact.width === input.width && artifact.height === input.height && artifact.file.bucket === input.bucket && artifact.file.objectKey === input.objectKey; if (!exact) { throw new Error(`Retained screenshot settlement identity conflict: ${input.settlementKey}`); } } export async function getFileUpload( db: Database, workspaceId: string, uploadId: string, ): Promise<{ id: string; status: FileUploadStatus; expiresAt: Date; file: FileAsset; } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.fileUploads.id, status: schema.fileUploads.status, expiresAt: schema.fileUploads.expiresAt, file: schema.files, }) .from(schema.fileUploads) .innerJoin(schema.files, eq(schema.fileUploads.fileId, schema.files.id)) .where( and(eq(schema.fileUploads.workspaceId, workspaceId), eq(schema.fileUploads.id, uploadId)), ) .limit(1); return row ? { id: row.id, status: row.status as FileUploadStatus, expiresAt: row.expiresAt, file: mapFile(row.file), } : null; }); } export async function completeFileUpload( db: Database, workspaceId: string, uploadId: string, options: { /** * Digest the server computed from the stored bytes. Recorded only when the * file has none: a client digest is never replaced. */ computedSha256?: string | undefined; } = {}, ): Promise { return await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [uploadRow] = await tx .select() .from(schema.fileUploads) .where( and( eq(schema.fileUploads.workspaceId, workspaceId), eq(schema.fileUploads.id, uploadId), ), ) .for("update") .limit(1); if (!uploadRow) { throw new Error(`File upload not found: ${uploadId}`); } const [fileRow] = await tx .select() .from(schema.files) .where( and(eq(schema.files.workspaceId, workspaceId), eq(schema.files.id, uploadRow.fileId)), ) .for("update") .limit(1); if (!fileRow) { throw new Error(`File not found for upload: ${uploadId}`); } // The API route normally handles this fast path, but the second half of // a concurrent finalize race can enter this transaction after the first // caller committed. Locking makes the retry return the original ready // asset rather than writing a second transition or failing a client that // never received the first response. if (uploadRow.status === "completed" && fileRow.status === "ready") { return mapFile(fileRow); } if (uploadRow.status !== "pending") { throw new Error(`File upload is ${uploadRow.status}: ${uploadId}`); } const now = new Date(); const [updatedFile] = await tx .update(schema.files) .set({ status: "ready", ...(options.computedSha256 && !fileRow.sha256 ? { sha256: options.computedSha256 } : {}), updatedAt: now, }) .where(and(eq(schema.files.workspaceId, workspaceId), eq(schema.files.id, fileRow.id))) .returning(); await tx .update(schema.fileUploads) .set({ status: "completed", completedAt: now, updatedAt: now, }) .where( and( eq(schema.fileUploads.workspaceId, workspaceId), eq(schema.fileUploads.id, uploadId), ), ); if (!updatedFile) { throw new Error("Failed to complete file upload"); } return mapFile(updatedFile); }), ); } export async function markFileUploadFailed( db: Database, workspaceId: string, uploadId: string, fileId: string, uploadStatus: "failed" | "expired" = "failed", ): Promise { const now = new Date(); await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { await tx .update(schema.fileUploads) .set({ status: uploadStatus, updatedAt: now }) .where( and( eq(schema.fileUploads.workspaceId, workspaceId), eq(schema.fileUploads.id, uploadId), ), ); await tx .update(schema.files) .set({ status: "failed", updatedAt: now }) .where(and(eq(schema.files.workspaceId, workspaceId), eq(schema.files.id, fileId))); }), ); } export type FileUploadCleanupClaimResult = | { outcome: "claimed" } | { outcome: "completed"; file: FileAsset } | { outcome: "unavailable"; status: FileUploadStatus }; /** * Atomically fence a pending direct upload before deleting its provider object. * The lock order intentionally matches completeFileUpload (upload, then file), * so cleanup and finalize cannot leave a ready row pointing at a deleted key. */ export async function claimFileUploadCleanup( db: Database, input: { workspaceId: string; uploadId: string; fileId: string; }, ): Promise { return await withWorkspaceRls( db, input.workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [upload] = await tx .select({ status: schema.fileUploads.status, fileId: schema.fileUploads.fileId, }) .from(schema.fileUploads) .where( and( eq(schema.fileUploads.workspaceId, input.workspaceId), eq(schema.fileUploads.id, input.uploadId), ), ) .for("update") .limit(1); if (!upload || upload.fileId !== input.fileId) { return { outcome: "unavailable", status: "failed" }; } const [file] = await tx .select() .from(schema.files) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ) .for("update") .limit(1); if (!file) { return { outcome: "unavailable", status: upload.status as FileUploadStatus, }; } if (upload.status === "completed" && file.status === "ready") { return { outcome: "completed", file: mapFile(file) }; } if (upload.status !== "pending") { return { outcome: "unavailable", status: upload.status as FileUploadStatus, }; } const now = new Date(); await tx .update(schema.fileUploads) .set({ status: "cleanup_pending", updatedAt: now }) .where( and( eq(schema.fileUploads.workspaceId, input.workspaceId), eq(schema.fileUploads.id, input.uploadId), eq(schema.fileUploads.status, "pending"), ), ); await tx .update(schema.files) .set({ status: "failed", updatedAt: now }) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ); return { outcome: "claimed" }; }), ); } export type ExpiredFileUploadCleanupClaim = { uploadId: string; accountId: string; workspaceId: string; fileId: string; objectKey: string; }; /** * Claim a bounded cross-workspace batch of expired direct uploads for object * cleanup. The SECURITY DEFINER function is the sole FORCE-RLS bypass and * atomically moves each row to `cleanup_pending` under `FOR UPDATE SKIP * LOCKED`. A worker crash or provider-delete failure leaves the claim * reclaimable after `claimTimeoutMs`; object deletes are idempotent. */ export async function claimExpiredFileUploadCleanup( db: Database, input: { graceMs: number; claimTimeoutMs: number; limit: number; }, ): Promise { const rows = await rawRows<{ upload_id: string; account_id: string; workspace_id: string; file_id: string; object_key: string; }>( db, sql` select upload_id, account_id, workspace_id, file_id, object_key from opengeni_private.claim_expired_file_upload_cleanup( ${input.graceMs}, ${input.claimTimeoutMs}, ${input.limit} ) `, ); return rows.map((row) => ({ uploadId: row.upload_id, accountId: row.account_id, workspaceId: row.workspace_id, fileId: row.file_id, objectKey: row.object_key, })); } /** Settle one successfully deleted cleanup claim. Idempotent on its terminal state. */ export async function completeFileUploadCleanup( db: Database, input: { accountId: string; workspaceId: string; uploadId: string; fileId: string; terminalStatus: "failed" | "expired"; }, ): Promise { return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const [upload] = await tx .select({ owner: schema.fileUploads.privateFileOwnerSubjectId, fileId: schema.fileUploads.fileId, status: schema.fileUploads.status, }) .from(schema.fileUploads) .where( and( eq(schema.fileUploads.accountId, input.accountId), eq(schema.fileUploads.workspaceId, input.workspaceId), eq(schema.fileUploads.id, input.uploadId), ), ) .for("update") .limit(1); if ( !upload || upload.fileId !== input.fileId || (upload.status !== "cleanup_pending" && upload.status !== input.terminalStatus) ) return false; return withSessionRlsActorContext( { subjectId: "service:file-upload-cleanup", privateFileOwnerSubjectId: upload.owner }, () => completeFileUploadCleanupInOwnerScope(tx, input), ); }, ); } async function completeFileUploadCleanupInOwnerScope( db: Database, input: Parameters[1], ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [upload] = await tx .select({ status: schema.fileUploads.status, fileId: schema.fileUploads.fileId, }) .from(schema.fileUploads) .where( and( eq(schema.fileUploads.workspaceId, input.workspaceId), eq(schema.fileUploads.id, input.uploadId), ), ) .for("update") .limit(1); if (!upload || upload.fileId !== input.fileId) { return false; } if (upload.status === input.terminalStatus) { return true; } if (upload.status !== "cleanup_pending") { return false; } const now = new Date(); const settled = await tx .update(schema.fileUploads) .set({ status: input.terminalStatus, updatedAt: now }) .where( and( eq(schema.fileUploads.workspaceId, input.workspaceId), eq(schema.fileUploads.id, input.uploadId), eq(schema.fileUploads.status, "cleanup_pending"), ), ) .returning({ id: schema.fileUploads.id }); if (settled.length === 0) { return false; } await tx .update(schema.files) .set({ status: "failed", updatedAt: now }) .where( and(eq(schema.files.workspaceId, input.workspaceId), eq(schema.files.id, input.fileId)), ); return true; }), ); } /** Settle one successfully deleted global expiry-reaper claim. */ export async function completeExpiredFileUploadCleanup( db: Database, input: { accountId: string; workspaceId: string; uploadId: string; fileId: string; }, ): Promise { return await completeFileUploadCleanup(db, { ...input, terminalStatus: "expired", }); } const registryCapabilitySource = "registry" as CapabilitySource; export async function createImportBatch( db: Database, input: CreateImportBatchInput, ): Promise { const [row] = await db .insert(schema.importBatches) .values({ source: input.source, snapshotDate: input.snapshotDate, snapshotRef: input.snapshotRef ?? null, attributionNote: input.attributionNote, importedCount: input.importedCount ?? 0, skippedCount: input.skippedCount ?? 0, quarantinedCount: input.quarantinedCount ?? 0, logoFailureCount: input.logoFailureCount ?? 0, staleCount: input.staleCount ?? 0, details: input.details ?? {}, }) .returning(); if (!row) { throw new Error("Failed to create import batch"); } return mapImportBatch(row); } export async function findCompletedImportBatch( db: Database, input: { source: string; snapshotRef: string; importedCount: number }, ): Promise { const [row] = await db .select() .from(schema.importBatches) .where( and( eq(schema.importBatches.source, input.source), eq(schema.importBatches.snapshotRef, input.snapshotRef), eq(schema.importBatches.importedCount, input.importedCount), ), ) .orderBy(desc(schema.importBatches.updatedAt)) .limit(1); return row ? mapImportBatch(row) : null; } export async function updateImportBatchCounts( db: Database, id: string, input: UpdateImportBatchCountsInput, ): Promise { const [row] = await db .update(schema.importBatches) .set({ importedCount: input.importedCount, skippedCount: input.skippedCount, quarantinedCount: input.quarantinedCount, logoFailureCount: input.logoFailureCount, staleCount: input.staleCount, ...(input.details ? { details: input.details } : {}), updatedAt: new Date(), }) .where(eq(schema.importBatches.id, id)) .returning(); if (!row) { throw new Error(`Import batch not found: ${id}`); } return mapImportBatch(row); } export async function upsertRegistryCapabilityCatalogItem( db: Database, input: RegistryCapabilityCatalogItemInput, ): Promise { const now = new Date(); const metadata = { registry: "integrations.sh", providerDomain: input.providerDomain, scopesHint: input.scopesHint ?? [], ...input.metadata, }; const values = { id: input.id, accountId: null, workspaceId: null, kind: "mcp" as CapabilityKind, source: registryCapabilitySource, name: input.name, description: input.description ?? null, category: input.category ?? "integrations", tags: input.tags ?? ["mcp", "integration", input.tier], homepageUrl: input.homepageUrl ?? `https://${input.providerDomain}`, endpointUrl: input.mcpUrl, installUrl: input.installUrl ?? input.homepageUrl ?? `https://${input.providerDomain}`, authModel: input.authKind === "none" ? null : "credential_ref", providerDomain: input.providerDomain, surfaceType: "mcp", transport: input.transport, mcpUrl: input.mcpUrl, authKind: input.authKind, credentialFacts: input.credentialFacts, tier: input.tier, provenance: input.provenance, logoAssetPath: input.logoAssetPath ?? null, importBatchId: input.importBatchId, stale: false, staleAt: null, metadata, updatedAt: now, }; const updateValues = { id: values.id, kind: values.kind, name: values.name, description: values.description, category: values.category, tags: values.tags, homepageUrl: values.homepageUrl, endpointUrl: values.endpointUrl, installUrl: values.installUrl, authModel: values.authModel, surfaceType: values.surfaceType, transport: values.transport, authKind: values.authKind, credentialFacts: values.credentialFacts, tier: values.tier, provenance: values.provenance, logoAssetPath: input.clearLogoAsset ? null : sql`coalesce(excluded.logo_asset_path, ${schema.capabilityCatalogItems.logoAssetPath})`, importBatchId: values.importBatchId, stale: false, staleAt: null, metadata: values.metadata, updatedAt: values.updatedAt, }; const [row] = await db .insert(schema.capabilityCatalogItems) .values(values) .onConflictDoUpdate({ target: [ schema.capabilityCatalogItems.source, schema.capabilityCatalogItems.providerDomain, schema.capabilityCatalogItems.mcpUrl, ], set: updateValues, }) .returning(); if (!row) { throw new Error("Failed to upsert registry capability catalog item"); } return mapCapabilityCatalogItem(row); } export async function listRegistryCatalogSurfaceKeys( db: Database, ): Promise { const rows = await db .select({ id: schema.capabilityCatalogItems.id, providerDomain: schema.capabilityCatalogItems.providerDomain, mcpUrl: schema.capabilityCatalogItems.mcpUrl, }) .from(schema.capabilityCatalogItems) .where(eq(schema.capabilityCatalogItems.source, registryCapabilitySource)); return rows.flatMap((row) => row.providerDomain && row.mcpUrl ? [{ id: row.id, providerDomain: row.providerDomain, mcpUrl: row.mcpUrl }] : [], ); } export async function markStaleRegistryCatalogItems( db: Database, activeKeys: Iterable<{ providerDomain: string; mcpUrl: string }>, importBatchId: string, ): Promise { const active = new Set([...activeKeys].map((key) => `${key.providerDomain}\n${key.mcpUrl}`)); const existing = await listRegistryCatalogSurfaceKeys(db); const stale = existing.filter((row) => !active.has(`${row.providerDomain}\n${row.mcpUrl}`)); if (stale.length === 0) { return 0; } const now = new Date(); const updated = await db .update(schema.capabilityCatalogItems) .set({ stale: true, staleAt: now, importBatchId, updatedAt: now, }) .where( and( eq(schema.capabilityCatalogItems.source, registryCapabilitySource), inArray( schema.capabilityCatalogItems.id, stale.map((row) => row.id), ), ), ) .returning({ id: schema.capabilityCatalogItems.id }); return updated.length; } export async function upsertCapabilityCatalogItem( db: Database, input: CreateCapabilityCatalogItemInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); const values = { id: input.id, accountId: input.accountId, workspaceId: input.workspaceId, kind: input.kind, source: input.source, name: input.name, description: input.description ?? null, category: input.category ?? "custom", tags: input.tags ?? [], homepageUrl: input.homepageUrl ?? null, endpointUrl: input.endpointUrl ?? null, installUrl: input.installUrl ?? null, authModel: input.authModel ?? null, providerDomain: input.providerDomain ?? null, surfaceType: null, transport: null, mcpUrl: input.mcpUrl ?? null, authKind: input.authKind ?? null, credentialFacts: [], tier: null, provenance: null, logoAssetPath: null, importBatchId: null, stale: false, staleAt: null, metadata: input.metadata ?? {}, updatedAt: now, }; const updateValues = { kind: values.kind, source: values.source, name: values.name, description: values.description, category: values.category, tags: values.tags, homepageUrl: values.homepageUrl, endpointUrl: values.endpointUrl, installUrl: values.installUrl, authModel: values.authModel, providerDomain: values.providerDomain, surfaceType: values.surfaceType, transport: values.transport, mcpUrl: values.mcpUrl, authKind: values.authKind, credentialFacts: values.credentialFacts, tier: values.tier, provenance: values.provenance, // A workspace item's logo comes from its server's advertised icon // (setWorkspaceCapabilityCatalogItemLogo); editing the item keeps it. importBatchId: values.importBatchId, stale: values.stale, staleAt: values.staleAt, metadata: values.metadata, updatedAt: values.updatedAt, }; const insert = scopedDb.insert(schema.capabilityCatalogItems).values(values); const target = [schema.capabilityCatalogItems.workspaceId, schema.capabilityCatalogItems.id]; const [row] = input.createOnly ? await insert.onConflictDoNothing({ target }).returning() : await insert.onConflictDoUpdate({ target, set: updateValues }).returning(); if (!row && input.createOnly) { const [existing] = await scopedDb .select() .from(schema.capabilityCatalogItems) .where( and( eq(schema.capabilityCatalogItems.workspaceId, input.workspaceId), eq(schema.capabilityCatalogItems.id, input.id), ), ) .limit(1); if (existing) return mapCapabilityCatalogItem(existing); } if (!row) { throw new Error("Failed to upsert capability catalog item"); } return mapCapabilityCatalogItem(row); }, ); } /** * Sets the logo of a workspace-owned catalog item (a custom MCP server) to a * stored `catalog-assets/...` key. Shared registry rows are never changed from a * workspace connection. Returns whether a row changed. */ export async function setWorkspaceCapabilityCatalogItemLogo( db: Database, input: { accountId: string; workspaceId: string; id: string; logoAssetPath: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.capabilityCatalogItems) .set({ logoAssetPath: input.logoAssetPath, updatedAt: new Date() }) .where( and( eq(schema.capabilityCatalogItems.workspaceId, input.workspaceId), eq(schema.capabilityCatalogItems.id, input.id), ne(schema.capabilityCatalogItems.source, registryCapabilitySource), or( isNull(schema.capabilityCatalogItems.logoAssetPath), ne(schema.capabilityCatalogItems.logoAssetPath, input.logoAssetPath), ), ), ) .returning({ id: schema.capabilityCatalogItems.id }); return rows.length > 0; }, ); } export async function listCapabilityCatalogItems( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.capabilityCatalogItems) .where( or( eq(schema.capabilityCatalogItems.workspaceId, workspaceId), and( isNull(schema.capabilityCatalogItems.workspaceId), or( ne(schema.capabilityCatalogItems.source, registryCapabilitySource), eq(schema.capabilityCatalogItems.stale, false), ), ), ), ) .orderBy(asc(schema.capabilityCatalogItems.kind), asc(schema.capabilityCatalogItems.name)); const installations = await scopedDb .select() .from(schema.capabilityInstallations) .where(eq(schema.capabilityInstallations.workspaceId, workspaceId)); const installationByCapabilityId = new Map( installations.map((installation) => [installation.capabilityId, installation]), ); return rows.flatMap((row) => { const exposure = catalogExposureState(row, installationByCapabilityId.get(row.id) ?? null); return exposure === "blocked" ? [] : [mapCapabilityCatalogItem(row, exposure)]; }); }); } /** * Declarative OAuth profile carried by a global (registry-imported) catalog * row for an exact MCP URL, or null when no row declares one. Only global * rows are consulted: a workspace-created row must not steer another * workspace's OAuth flow, and the OAuth client applies the profile as a * narrowing constraint over its defaults. * * A stale row's profile still applies deliberately: staleness hides the row * from the browse surface, but dropping its declared fences on staleness * would loosen an ownership or origin constraint. Non-stale rows win when a * duplicate `mcp_url` exists under two provider domains; the remaining id * tie-break is only for determinism. The value is returned raw (whatever the * row carries) so the caller's validation decides how a malformed profile * fails; absence of the key is the only null. */ export async function getGlobalCatalogOAuthProfile( db: Database, workspaceId: string, mcpUrl: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ metadata: schema.capabilityCatalogItems.metadata, stale: schema.capabilityCatalogItems.stale, }) .from(schema.capabilityCatalogItems) .where( and( isNull(schema.capabilityCatalogItems.workspaceId), eq(schema.capabilityCatalogItems.mcpUrl, mcpUrl), ), ) .orderBy(asc(schema.capabilityCatalogItems.stale), asc(schema.capabilityCatalogItems.id)); const row = rows.find((candidate) => candidate.metadata.oauthProfile !== undefined); return row === undefined ? null : (row.metadata.oauthProfile ?? null); }); } export async function getCapabilityCatalogItem( db: Database, workspaceId: string, capabilityId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.capabilityCatalogItems) .where( and( eq(schema.capabilityCatalogItems.id, capabilityId), or( eq(schema.capabilityCatalogItems.workspaceId, workspaceId), isNull(schema.capabilityCatalogItems.workspaceId), ), ), ) .orderBy(asc(sql`(${schema.capabilityCatalogItems.workspaceId} is null)`)) .limit(1); if (!row) { return null; } const [installation] = await scopedDb .select() .from(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.capabilityId, capabilityId), ), ) .limit(1); const exposure = catalogExposureState(row, installation ?? null); return exposure === "blocked" ? null : mapCapabilityCatalogItem(row, exposure); }); } function portableSkillManifestIdentity(manifest: Record): string { // The version column is already the immutable version identity. Older rows // predate the duplicate manifest field, so including it in the digest would // make an unchanged Skill conflict with itself after an upgrade. const identity = { ...manifest }; delete identity.version; return stableJson(identity); } /** Replay before remote resolution; callers must provide the same canonical original request used at install. */ export async function replayPortableSkillInstall( db: Database, input: { accountId: string; workspaceId: string; actor: SkillActor; operationId: string; requestIdentity: Record; }, ): Promise { return withWorkspaceRls(db, input.workspaceId, async (tx) => { await lockSkillPublication(tx, input.workspaceId); if (input.actor.kind === "agent") await assertSkillReadAttempt(tx, { ...input, actor: input.actor }); await tx.execute( sql`SELECT pg_advisory_xact_lock(hashtextextended(${`skill-operation:${input.workspaceId}:${input.operationId}`},0))`, ); const [prior] = await tx .select() .from(schema.skillWriteReceipts) .where( and( eq(schema.skillWriteReceipts.workspaceId, input.workspaceId), eq(schema.skillWriteReceipts.operationId, input.operationId), ), ) .limit(1); if (!prior) return null; const envelope = ( prior.receipt as unknown as { portableInstall?: { requestHash: string; result: Omit; }; } ).portableInstall; if ( prior.accountId !== input.accountId || !envelope || envelope.requestHash !== createHash("sha256").update(stableJson(input.requestIdentity)).digest("hex") ) { throw new Error( "Skill operation key reused with different input or without a portable install receipt", ); } const skillReceipt = await applySkillLifecycle(tx, input, { operation: "install", operationId: input.operationId, skillFacetId: envelope.result.facetId, reason: "Install portable Skill through the unified registry head", portableInstall: envelope, }); return { ...envelope.result, skillReceipt }; }); } /** * Install one immutable, already-validated Skill through the authoritative * Plugin/Skill-Facet ownership model. Repeating an operation replays its original * result; a new operation cannot rewrite an immutable commit's content. */ export async function installPortableSkill( db: Database, input: InstallPortableSkillInput, ): Promise { if (!input.skillActor) throw new Error("Portable Skill installation requires a truthful unified Skill actor"); // Fail fast, before any write, with the named error every caller maps. const facetDescription = portableSkillFacetDescription(input.description); try { return await installPortableSkillRows(db, input, facetDescription); } catch (error) { if (!(error instanceof PortableSkillMetadataError) && isPortableSkillMetadataViolation(error)) throw new PortableSkillMetadataError("The Skill's metadata cannot be stored", { cause: error, }); throw error; } } async function installPortableSkillRows( db: Database, input: InstallPortableSkillInput, facetDescription: string, ): Promise { const skillActor = input.skillActor!; const skillOperationId = input.skillOperationId ?? randomUUID(); const { skillActor: _actor, skillOperationId: _operation, skillRequestIdentity: originalIdentity, ...resolvedIdentity } = input; const requestIdentity = originalIdentity ?? resolvedIdentity; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await lockSkillPublication(tx as unknown as Database, input.workspaceId); const replay = await replayPortableSkillInstall(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, actor: skillActor, operationId: skillOperationId, requestIdentity, }); if (replay) return replay; const now = new Date(); const version = input.version ?? input.sourceCommit; await lockCapabilityComponentIdentity( tx as unknown as Database, input.workspaceId, input.pluginKey, ); let [plugin] = await tx .select() .from(schema.capabilityPlugins) .where( and( eq(schema.capabilityPlugins.workspaceId, input.workspaceId), eq(schema.capabilityPlugins.pluginKey, input.pluginKey), ), ) .for("update") .limit(1); if (!plugin) { [plugin] = await tx .insert(schema.capabilityPlugins) .values({ pluginKey: input.pluginKey, accountId: input.accountId, workspaceId: input.workspaceId, name: input.name, description: input.description, category: input.category ?? "skills", tags: input.tags ?? ["skill", "imported", input.source], provenance: input.provenance ?? "workspace", }) .returning(); } else if (plugin.accountId !== input.accountId) { throw new Error("Portable Skill plugin tenant mismatch"); } else if (plugin.name !== input.name || plugin.description !== input.description) { [plugin] = await tx .update(schema.capabilityPlugins) .set({ name: input.name, description: input.description, category: input.category ?? "skills", tags: input.tags ?? ["skill", "imported", input.source], provenance: input.provenance ?? "workspace", updatedAt: now, }) .where(eq(schema.capabilityPlugins.id, plugin.id)) .returning(); } if (!plugin) throw new Error("Failed to create portable Skill plugin"); // Legacy source IDs fold path case. Preserve those IDs for existing // installations, but never let a distinct Git folder overwrite one. if (input.source === "github" || input.source === "skills_sh") { const [collision] = await tx .select({ id: schema.capabilityPluginVersions.id }) .from(schema.capabilityPluginVersions) .where( and( eq(schema.capabilityPluginVersions.pluginId, plugin.id), sql`lower(${schema.capabilityPluginVersions.manifest}->>'sourcePath') = lower(${input.sourcePath})`, sql`${schema.capabilityPluginVersions.manifest}->>'sourcePath' <> ${input.sourcePath}`, ), ) .limit(1); if (collision) throw new PortableSkillSourcePathConflictError( "This repository folder differs only by case from an existing Skill source. Legacy source IDs cannot distinguish these folders; use a uniquely named source folder.", ); } const manifest = { schemaVersion: 1, kind: "skill", source: input.source, sourceUrl: input.sourceUrl, repositoryUrl: input.repositoryUrl, version, sourceCommit: input.sourceCommit, sourcePath: input.sourcePath, ...(input.sourceProvenance ? { sourceProvenance: input.sourceProvenance } : {}), contentSha256: input.contentSha256, fileCount: input.files.length, totalBytes: input.totalBytes, }; const manifestDigest = createHash("sha256").update(stableJson(manifest)).digest("hex"); const [versionByName] = await tx .select() .from(schema.capabilityPluginVersions) .where( and( eq(schema.capabilityPluginVersions.pluginId, plugin.id), eq(schema.capabilityPluginVersions.version, version), ), ) .for("update") .limit(1); if ( versionByName && versionByName.manifestDigest !== manifestDigest && portableSkillManifestIdentity(versionByName.manifest) !== portableSkillManifestIdentity(manifest) ) { throw new Error(`Skill version ${version} conflicts with immutable stored content`); } let pluginVersion = versionByName; if (!pluginVersion) { [pluginVersion] = await tx .insert(schema.capabilityPluginVersions) .values({ pluginId: plugin.id, version, manifestDigest, manifest, status: "published", }) .returning(); } if (!pluginVersion) throw new Error("Failed to create portable Skill plugin version"); const activationMode = input.activationMode ?? "workspace_managed"; let [facet] = await tx .select() .from(schema.capabilityFacets) .where( and( eq(schema.capabilityFacets.pluginVersionId, pluginVersion.id), eq(schema.capabilityFacets.facetKey, "skill"), ), ) .limit(1); if (!facet) { [facet] = await tx .insert(schema.capabilityFacets) .values({ pluginVersionId: pluginVersion.id, facetKey: "skill", kind: "skill", activationMode, required: true, }) .returning(); } if (!facet) throw new Error("Failed to create portable Skill facet"); if (facet.activationMode !== activationMode) { throw new Error( `Portable Skill ${input.capabilityId} activation mode conflicts with immutable stored content`, ); } const [existingSkill] = await tx .select() .from(schema.capabilitySkillFacets) .where(eq(schema.capabilitySkillFacets.facetId, facet.id)) .limit(1); if ( existingSkill && (existingSkill.contentSha256 !== input.contentSha256 || existingSkill.capabilityId !== input.capabilityId) ) { throw new Error("Portable Skill facet conflicts with immutable stored content"); } if (!existingSkill) { await tx.insert(schema.capabilitySkillFacets).values({ facetId: facet.id, capabilityId: input.capabilityId, name: input.name, description: facetDescription, sourceUrl: input.sourceUrl, sourceCommit: input.sourceCommit, sourcePath: input.sourcePath, contentSha256: input.contentSha256, fileCount: input.files.length, totalBytes: input.totalBytes, license: input.license ?? null, }); await tx.insert(schema.capabilitySkillFiles).values( input.files.map((file) => ({ skillFacetId: facet.id, path: file.path, content: file.content, byteSize: file.byteSize, contentSha256: file.contentSha256, })), ); } let [pluginInstallation] = await tx .select() .from(schema.capabilityPluginInstallations) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, input.workspaceId), eq(schema.capabilityPluginInstallations.pluginId, plugin.id), ), ) .for("update") .limit(1); const owner = input.owner ?? { kind: "direct" as const, id: input.capabilityId, removable: true, }; const [existingOwner] = pluginInstallation ? await tx .select({ id: schema.capabilityComponentOwners.id }) .from(schema.capabilityComponentOwners) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.capabilityComponentOwners.facetInstallationId, ), ) .where( and( eq( schema.capabilityFacetInstallations.pluginInstallationId, pluginInstallation.id, ), eq(schema.capabilityComponentOwners.ownerKind, owner.kind), eq(schema.capabilityComponentOwners.ownerId, owner.id), ), ) .limit(1) : []; const changesInstalledVersion = Boolean( pluginInstallation && pluginInstallation.status !== "disabled" && (pluginInstallation.pluginVersionId !== pluginVersion.id || pluginInstallation.status !== "active"), ); const directInstall = owner.kind === "direct"; if (changesInstalledVersion && directInstall) { if (input.expectedInstallationVersion === undefined) { throw new PortableSkillInstallationVersionRequiredError( "Updating a Skill requires the previewed installation version", ); } if (pluginInstallation!.version !== input.expectedInstallationVersion) { throw new PortableSkillInstallationVersionConflictError( input.capabilityId, input.expectedInstallationVersion, pluginInstallation!.version, ); } } if (pluginInstallation && pluginInstallation.pluginVersionId !== pluginVersion.id) { await assertCapabilityComponentVersionCanChange(tx as unknown as Database, { workspaceId: input.workspaceId, pluginKey: input.pluginKey, pluginInstallationId: pluginInstallation.id, owner: { kind: owner.kind, id: owner.id, }, }); } if (!pluginInstallation) { [pluginInstallation] = await tx .insert(schema.capabilityPluginInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pluginId: plugin.id, pluginVersionId: pluginVersion.id, status: "active", installedBySubjectId: input.subjectId, }) .returning(); } else if ( pluginInstallation.pluginVersionId !== pluginVersion.id || pluginInstallation.status !== "active" ) { await tx .delete(schema.capabilityFacetInstallations) .where( eq(schema.capabilityFacetInstallations.pluginInstallationId, pluginInstallation.id), ); [pluginInstallation] = await tx .update(schema.capabilityPluginInstallations) .set({ pluginVersionId: pluginVersion.id, status: "active", version: pluginInstallation.version + 1, installedBySubjectId: input.subjectId, installedAt: now, updatedAt: now, }) .where(eq(schema.capabilityPluginInstallations.id, pluginInstallation.id)) .returning(); } if (!pluginInstallation) { throw new Error("Failed to create portable Skill plugin installation"); } let [facetInstallation] = await tx .select() .from(schema.capabilityFacetInstallations) .where( and( eq(schema.capabilityFacetInstallations.pluginInstallationId, pluginInstallation.id), eq(schema.capabilityFacetInstallations.facetId, facet.id), ), ) .limit(1); if (!facetInstallation) { [facetInstallation] = await tx .insert(schema.capabilityFacetInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pluginInstallationId: pluginInstallation.id, facetId: facet.id, status: "active", }) .returning(); } if (!facetInstallation) throw new Error("Failed to create portable Skill installation"); await tx .insert(schema.capabilityComponentOwners) .values({ accountId: input.accountId, workspaceId: input.workspaceId, facetInstallationId: facetInstallation.id, ownerKind: owner.kind, ownerId: owner.id, removable: owner.removable, }) .onConflictDoNothing(); const result = { created: !existingOwner, capabilityId: input.capabilityId, pluginId: plugin.id, pluginVersionId: pluginVersion.id, facetId: facet.id, pluginInstallationId: pluginInstallation.id, facetInstallationId: facetInstallation.id, installationVersion: pluginInstallation.version, source: input.source, version, sourceUrl: input.sourceUrl, sourceCommit: input.sourceCommit, contentSha256: input.contentSha256, name: input.name, }; const skillReceipt = await applySkillLifecycle( tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, actor: skillActor, }, { operation: "install", operationId: skillOperationId, skillFacetId: facet.id, reason: "Install portable Skill through the unified registry head", portableInstall: { requestHash: createHash("sha256").update(stableJson(requestIdentity)).digest("hex"), result, }, }, ); return { skillReceipt, ...result, }; }), ); } /** * Return exact text artifacts for active authoritative Skill installations. * Session-selected Skills are excluded from ambient runtime resolution unless * the caller is explicitly materializing one during session admission. */ export async function listInstalledPortableSkills( db: Database, workspaceId: string, options: { includeSessionSelected?: boolean } = {}, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [workspace] = await scopedDb .select({ accountId: schema.workspaces.accountId }) .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if (!workspace) return []; const currentSkills = new Map(); let after: { stableKey: string; id: string } | undefined; for (;;) { const page = await listSkillRecords( scopedDb, { accountId: workspace.accountId, workspaceId }, { limit: 1000, ...(after ? { after } : {}) }, ); for (const record of page) { if (record.source) currentSkills.set(record.source.skillFacetId, record); } if (page.length < 1000) break; const last = page[page.length - 1]!; after = { stableKey: last.stableKey, id: last.id }; } const rows = await scopedDb .select({ capabilityId: schema.capabilitySkillFacets.capabilityId, facetId: schema.capabilitySkillFacets.facetId, activationMode: schema.capabilityFacets.activationMode, manifest: schema.capabilityPluginVersions.manifest, version: schema.capabilityPluginVersions.version, name: schema.capabilitySkillFacets.name, description: schema.capabilitySkillFacets.description, sourceUrl: schema.capabilitySkillFacets.sourceUrl, sourceCommit: schema.capabilitySkillFacets.sourceCommit, sourcePath: schema.capabilitySkillFacets.sourcePath, contentSha256: schema.capabilitySkillFacets.contentSha256, path: schema.capabilitySkillFiles.path, content: schema.capabilitySkillFiles.content, }) .from(schema.capabilityPluginInstallations) .innerJoin( schema.capabilityPluginVersions, eq( schema.capabilityPluginVersions.id, schema.capabilityPluginInstallations.pluginVersionId, ), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.pluginInstallationId, schema.capabilityPluginInstallations.id, ), ) .innerJoin( schema.capabilityFacets, eq(schema.capabilityFacets.id, schema.capabilityFacetInstallations.facetId), ) .innerJoin( schema.capabilitySkillFacets, eq(schema.capabilitySkillFacets.facetId, schema.capabilityFacetInstallations.facetId), ) .innerJoin( schema.capabilitySkillFiles, eq(schema.capabilitySkillFiles.skillFacetId, schema.capabilitySkillFacets.facetId), ) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, workspaceId), eq(schema.capabilityPluginInstallations.status, "active"), eq(schema.capabilityFacetInstallations.status, "active"), sql`exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id = ${schema.capabilityFacetInstallations.id} and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} )`, ), ) .orderBy(asc(schema.capabilitySkillFacets.name), asc(schema.capabilitySkillFiles.path)); const skills = new Map(); for (const row of rows) { const current = currentSkills.get(row.facetId); if (!current || current.status !== "active" || !current.activeRevisionId) continue; if (row.activationMode !== "workspace_managed" && row.activationMode !== "session_selected") { throw new Error( `Installed Skill ${row.capabilityId} has invalid activation mode ${row.activationMode}`, ); } if (current.activationMode === "session_selected" && !options.includeSessionSelected) { continue; } const source = skillSourceFromManifest(row.manifest, row.capabilityId); const existing = skills.get(row.facetId); if (existing) { existing.files.push({ path: row.path, content: row.content }); continue; } skills.set(row.facetId, { capabilityId: row.capabilityId, source, version: row.version, name: row.name, description: row.description, activationMode: current.activationMode, sourceUrl: row.sourceUrl, sourceCommit: row.sourceCommit, sourcePath: row.sourcePath, contentSha256: row.contentSha256, files: [{ path: row.path, content: row.content }], }); } return [...skills.entries()].flatMap(([facetId, skill]) => { const current = currentSkills.get(facetId); if (!current || current.status !== "active" || !current.activeRevisionId) return []; const metadata = readSkillMetadata( current.files.find((file) => file.path === "SKILL.md")?.content ?? "", ); return [ { ...skill, // The active folder owns descriptors even after an upstream Skill // was renamed locally. Source labels remain provenance only. name: metadata.name, description: metadata.description, contentSha256: skillFilesContentHash(current.files), files: current.files, }, ]; }); }); } /** Return secret-free lifecycle summaries from the authoritative Skill ledger. */ export async function listInstalledSkills( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ facetInstallationId: schema.capabilityFacetInstallations.id, capabilityId: schema.capabilitySkillFacets.capabilityId, pluginKey: schema.capabilityPlugins.pluginKey, pluginName: schema.capabilityPlugins.name, pluginDescription: schema.capabilityPlugins.description, category: schema.capabilityPlugins.category, tags: schema.capabilityPlugins.tags, provenance: schema.capabilityPlugins.provenance, manifest: schema.capabilityPluginVersions.manifest, version: schema.capabilityPluginVersions.version, installationVersion: schema.capabilityPluginInstallations.version, installedAt: schema.capabilityPluginInstallations.installedAt, updatedAt: schema.capabilityPluginInstallations.updatedAt, sourceUrl: schema.capabilitySkillFacets.sourceUrl, sourceCommit: schema.capabilitySkillFacets.sourceCommit, sourcePath: schema.capabilitySkillFacets.sourcePath, contentSha256: schema.capabilitySkillFacets.contentSha256, fileCount: schema.capabilitySkillFacets.fileCount, totalBytes: schema.capabilitySkillFacets.totalBytes, license: schema.capabilitySkillFacets.license, ownerKind: schema.capabilityComponentOwners.ownerKind, ownerId: schema.capabilityComponentOwners.ownerId, ownerRemovable: schema.capabilityComponentOwners.removable, }) .from(schema.capabilityPluginInstallations) .innerJoin( schema.capabilityPlugins, eq(schema.capabilityPlugins.id, schema.capabilityPluginInstallations.pluginId), ) .innerJoin( schema.capabilityPluginVersions, eq( schema.capabilityPluginVersions.id, schema.capabilityPluginInstallations.pluginVersionId, ), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.pluginInstallationId, schema.capabilityPluginInstallations.id, ), ) .innerJoin( schema.capabilitySkillFacets, eq(schema.capabilitySkillFacets.facetId, schema.capabilityFacetInstallations.facetId), ) .innerJoin( schema.capabilityComponentOwners, eq( schema.capabilityComponentOwners.facetInstallationId, schema.capabilityFacetInstallations.id, ), ) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, workspaceId), eq(schema.capabilityPluginInstallations.status, "active"), eq(schema.capabilityFacetInstallations.status, "active"), effectiveCapabilityOwnerSql( schema.capabilityComponentOwners.ownerKind, schema.capabilityComponentOwners.ownerId, ), ), ) .orderBy( asc(schema.capabilityPlugins.name), asc(schema.capabilityComponentOwners.ownerKind), asc(schema.capabilityComponentOwners.ownerId), ); const summaries = new Map(); for (const row of rows) { const source = skillSourceFromManifest(row.manifest, row.capabilityId); const owner = portableSkillOwner(row.ownerKind, row.ownerId, row.ownerRemovable); const existing = summaries.get(row.facetInstallationId); if (existing) { if ( !existing.owners.some( (candidate) => candidate.kind === owner.kind && candidate.id === owner.id, ) ) { existing.owners.push(owner); } continue; } const repositoryUrl = row.manifest.repositoryUrl; const sourceProvenance = row.manifest.sourceProvenance; summaries.set(row.facetInstallationId, { capabilityId: row.capabilityId, pluginKey: row.pluginKey, installationVersion: row.installationVersion, name: row.pluginName, description: row.pluginDescription ?? "", category: row.category, tags: [...row.tags], provenance: typeof sourceProvenance === "string" && sourceProvenance.length > 0 ? sourceProvenance : row.provenance, source, version: row.version, sourceUrl: row.sourceUrl, repositoryUrl: typeof repositoryUrl === "string" && repositoryUrl.length > 0 ? repositoryUrl : row.sourceUrl, sourceCommit: row.sourceCommit, sourcePath: row.sourcePath, contentSha256: row.contentSha256, fileCount: row.fileCount, totalBytes: row.totalBytes, license: row.license, installedAt: row.installedAt.toISOString(), updatedAt: row.updatedAt.toISOString(), owners: [owner], }); } return [...summaries.values()]; }); } export async function getPortableSkillUninstallPreview( db: Database, workspaceId: string, capabilityId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const context = await portableSkillOwnerContext(scopedDb, workspaceId, capabilityId); if (!context) { return { capabilityId, installed: false, installationVersion: null, directOwner: null, remainingOwners: [], removesRuntimeSkill: false, }; } const owners = await portableSkillOwners(scopedDb, context.facetInstallationId); const directOwner = owners.find( (owner) => owner.kind === "direct" && owner.id === capabilityId, ); const remainingOwners = owners.filter( (owner) => !(owner.kind === "direct" && owner.id === capabilityId), ); return { capabilityId, installed: true, installationVersion: context.installationVersion, directOwner: directOwner ?? null, remainingOwners, removesRuntimeSkill: remainingOwners.length === 0, }; }); } export async function uninstallPortableSkill( db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; expectedInstallationVersion: number; skillActor?: SkillActor; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const context = await portableSkillOwnerContext( tx as unknown as Database, input.workspaceId, input.capabilityId, true, ); if (!context) { return { capabilityId: input.capabilityId, status: "not_installed", remainingOwners: [], }; } if (context.installationVersion !== input.expectedInstallationVersion) { throw new PortableSkillInstallationVersionConflictError( input.capabilityId, input.expectedInstallationVersion, context.installationVersion, ); } await tx .delete(schema.capabilityComponentOwners) .where( and( eq(schema.capabilityComponentOwners.facetInstallationId, context.facetInstallationId), eq(schema.capabilityComponentOwners.ownerKind, "direct"), eq(schema.capabilityComponentOwners.ownerId, input.capabilityId), ), ); const remainingOwners = await portableSkillOwners( tx as unknown as Database, context.facetInstallationId, ); if (remainingOwners.length > 0) { await tx .update(schema.capabilityPluginInstallations) .set({ version: context.installationVersion + 1, updatedAt: new Date(), }) .where(eq(schema.capabilityPluginInstallations.id, context.pluginInstallationId)); return { capabilityId: input.capabilityId, status: "retained_by_other_owners", remainingOwners, }; } const skillReleases = await releaseOrphanedSkillHeads(tx as unknown as Database, { workspaceId: input.workspaceId, facetInstallationIds: [context.facetInstallationId], ...(input.skillActor ? { skillActor: input.skillActor } : {}), }); const now = new Date(); await tx .delete(schema.capabilityFacetInstallations) .where(eq(schema.capabilityFacetInstallations.id, context.facetInstallationId)); const siblingFacets = await tx .select({ id: schema.capabilityFacetInstallations.id }) .from(schema.capabilityFacetInstallations) .where( eq( schema.capabilityFacetInstallations.pluginInstallationId, context.pluginInstallationId, ), ) .limit(1); await tx .update(schema.capabilityPluginInstallations) .set({ status: siblingFacets.length === 0 ? "disabled" : "active", version: context.installationVersion + 1, updatedAt: now, }) .where(eq(schema.capabilityPluginInstallations.id, context.pluginInstallationId)); return { capabilityId: input.capabilityId, status: "uninstalled", remainingOwners: [], ...(skillReleases.length ? { skillReleases } : {}), }; }), ); } async function portableSkillOwnerContext( db: Database, workspaceId: string, capabilityId: string, lock = false, ): Promise<{ pluginInstallationId: string; facetInstallationId: string; installationVersion: number; } | null> { let query = db .select({ pluginInstallationId: schema.capabilityPluginInstallations.id, facetInstallationId: schema.capabilityFacetInstallations.id, installationVersion: schema.capabilityPluginInstallations.version, }) .from(schema.capabilityComponentOwners) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.capabilityComponentOwners.facetInstallationId, ), ) .innerJoin( schema.capabilityPluginInstallations, eq( schema.capabilityPluginInstallations.id, schema.capabilityFacetInstallations.pluginInstallationId, ), ) .innerJoin( schema.capabilitySkillFacets, eq(schema.capabilitySkillFacets.facetId, schema.capabilityFacetInstallations.facetId), ) .where( and( eq(schema.capabilityComponentOwners.workspaceId, workspaceId), eq(schema.capabilityComponentOwners.ownerKind, "direct"), eq(schema.capabilityComponentOwners.ownerId, capabilityId), ), ) .limit(2); if (lock) query = query.for("update") as typeof query; const rows = await query; if (rows.length > 1) { throw new Error(`Portable Skill ${capabilityId} has duplicate direct owners`); } return rows[0] ?? null; } async function portableSkillOwners( db: Database, facetInstallationId: string, ): Promise { const rows = await db .select({ kind: schema.capabilityComponentOwners.ownerKind, id: schema.capabilityComponentOwners.ownerId, removable: schema.capabilityComponentOwners.removable, }) .from(schema.capabilityComponentOwners) .where(eq(schema.capabilityComponentOwners.facetInstallationId, facetInstallationId)) .orderBy( asc(schema.capabilityComponentOwners.ownerKind), asc(schema.capabilityComponentOwners.ownerId), ); return rows.map((row) => { if (row.kind !== "direct" && row.kind !== "plugin" && row.kind !== "migration") { throw new Error(`Unknown portable Skill owner kind: ${row.kind}`); } return { kind: row.kind, id: row.id, removable: row.removable }; }); } function portableSkillOwner(kind: string, id: string, removable: boolean): PortableSkillOwner { if (kind !== "direct" && kind !== "plugin" && kind !== "migration") { throw new Error(`Unknown Skill owner kind: ${kind}`); } return { kind, id, removable }; } function skillSourceFromManifest( manifestValue: Record, capabilityId: string, ): InstalledSkillSummary["source"] { const source = manifestValue.source; if (source === "library" || source === "github" || source === "skills_sh") { return source; } // Migration 0482 removed Packs but deliberately kept Skills that another // owner still holds. Their immutable plugin versions still record "pack". // Those Skills carried inline, Opengeni-managed content with no external // origin to re-import from, which "library" is the only public source to // express. Rejecting them failed every catalog read and turn in the workspace. if (source === "pack") { return "library"; } throw new Error(`Installed Skill ${capabilityId} has invalid immutable source metadata`); } export async function enableCapabilityInstallation( db: Database, input: EnableCapabilityInstallationInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); // Read the raw row (not the generic projection) so an omitted config // preserves stored credential-header ciphertext. const [existing] = await scopedDb .select() .from(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, input.workspaceId), eq(schema.capabilityInstallations.capabilityId, input.capabilityId), ), ) .limit(1); if (existing) { if (input.onlyIfUninstalled) return mapCapabilityInstallation(existing); const [row] = await scopedDb .update(schema.capabilityInstallations) .set({ kind: input.kind, status: "active", config: input.config ?? existing.config, metadata: input.metadata ?? existing.metadata, enabledAt: now, updatedAt: now, // Changing an installation hands it to whoever changed it. installedBySubjectId: input.installedBySubjectId ?? null, }) .where( and( eq(schema.capabilityInstallations.workspaceId, input.workspaceId), eq(schema.capabilityInstallations.capabilityId, input.capabilityId), ), ) .returning(); if (!row) { throw new Error(`Capability installation not found: ${input.capabilityId}`); } return mapCapabilityInstallation(row); } const insert = scopedDb.insert(schema.capabilityInstallations).values({ accountId: input.accountId, workspaceId: input.workspaceId, capabilityId: input.capabilityId, kind: input.kind, status: "active", config: input.config ?? {}, metadata: input.metadata ?? {}, installedBySubjectId: input.installedBySubjectId ?? null, }); const [row] = await ( input.onlyIfUninstalled ? insert.onConflictDoNothing() : insert ).returning(); if (!row && input.onlyIfUninstalled) { // A concurrent installation won. Never turn a create-only completion // into an update of its status, credentials, or restricted config. const current = await getCapabilityInstallation( scopedDb, input.workspaceId, input.capabilityId, ); if (current) return current; } if (!row) { throw new Error("Failed to enable capability installation"); } return mapCapabilityInstallation(row); }, ); } /** Who turned each MCP server on in a workspace, and whether it is on now. */ export async function listCapabilityInstallationInstallers( db: Database, workspaceId: string, ): Promise> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ capabilityId: schema.capabilityInstallations.capabilityId, status: schema.capabilityInstallations.status, installedBySubjectId: schema.capabilityInstallations.installedBySubjectId, }) .from(schema.capabilityInstallations) .where(eq(schema.capabilityInstallations.workspaceId, workspaceId)); return new Map( rows.map((row) => [ row.capabilityId, { status: row.status, installedBySubjectId: row.installedBySubjectId }, ]), ); }); } /** * Removes an MCP server's installation from a workspace, so it is no longer * on and can be turned on again from scratch (whoever does so becomes its * installer). With `memberRemoval` the caller must be the recorded installer * of an installation that is on: one an admin or another person turned on, * one with no recorded installer, or one an admin turned off stays with * admins ({@link IntegrationChangeRequiresAdminError}). Decided on the locked * row, in the removal transaction. Null when nothing is installed. */ export async function removeCapabilityInstallation( db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; subjectId: string; memberRemoval?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const where = and( eq(schema.capabilityInstallations.workspaceId, input.workspaceId), eq(schema.capabilityInstallations.capabilityId, input.capabilityId), ); const [existing] = await scopedDb .select() .from(schema.capabilityInstallations) .where(where) .limit(1) .for("update"); if (!existing) return null; if (input.memberRemoval) { if (existing.installedBySubjectId !== input.subjectId) throw new IntegrationChangeRequiresAdminError( "Only an admin can remove a server someone else added", ); if (existing.status !== "active") throw new IntegrationChangeRequiresAdminError( "An admin turned this server off. Only an admin can remove it.", ); } await scopedDb.delete(schema.capabilityInstallations).where(where); return mapCapabilityInstallation(existing); }, ); } /** * Deletes a workspace's own catalog entry and its installation here, if any, * in one transaction: for example a custom MCP server whose first Connect * failed. Connections are separate and stay. Returns whether the entry * existed. */ export async function deleteWorkspaceCatalogItem( db: Database, input: { accountId: string; workspaceId: string; capabilityId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .delete(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, input.workspaceId), eq(schema.capabilityInstallations.capabilityId, input.capabilityId), ), ); const deleted = await scopedDb .delete(schema.capabilityCatalogItems) .where( and( eq(schema.capabilityCatalogItems.workspaceId, input.workspaceId), eq(schema.capabilityCatalogItems.id, input.capabilityId), ), ) .returning({ id: schema.capabilityCatalogItems.id }); return deleted.length > 0; }, ); } export async function disableCapabilityInstallation( db: Database, workspaceId: string, capabilityId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .update(schema.capabilityInstallations) .set({ status: "disabled", updatedAt: new Date(), }) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.capabilityId, capabilityId), ), ) .returning(); if (!row) { throw new Error(`Capability installation not found: ${capabilityId}`); } return mapCapabilityInstallation(row); }); } /** Marks the turned-off installation that switches an organization connector off in one workspace. */ export const ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY = "organizationOverride"; export function isOrganizationConnectorOverride( installation: Pick, ): boolean { return ( installation.status === "disabled" && installation.metadata[ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY] === true ); } /** * Turns the organization's connector off in this workspace: a turned-off * installation of the same capability, which wins over the organization's * setup. An existing installation is returned unchanged. */ export async function turnOffOrganizationConnectorInWorkspace( db: Database, input: { accountId: string; workspaceId: string; capabilityId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .insert(schema.capabilityInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, capabilityId: input.capabilityId, kind: "mcp", status: "disabled", config: {}, metadata: { [ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY]: true }, }) .onConflictDoNothing(); const current = await getCapabilityInstallation( scopedDb, input.workspaceId, input.capabilityId, ); if (!current) throw new Error("Failed to turn the organization connector off"); return current; }, ); } /** * Removes this workspace's turned-off override, so the organization's * connector applies again. Any other installation is left alone (false). */ export async function restoreOrganizationConnectorInWorkspace( db: Database, workspaceId: string, capabilityId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const deleted = await scopedDb .delete(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.capabilityId, capabilityId), eq(schema.capabilityInstallations.status, "disabled"), sql`${schema.capabilityInstallations.metadata} -> ${ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY} = 'true'::jsonb`, ), ) .returning({ id: schema.capabilityInstallations.id }); return deleted.length > 0; }); } /** * An organization connector reaching this workspace, shaped as the * installation a workspace setup of it would be (header names only). */ export function organizationConnectorAsInstallation( connector: OrganizationConnectorRow, workspaceId: string, ): CapabilityInstallation { return { id: connector.id, accountId: connector.accountId, workspaceId, capabilityId: connector.capabilityId, kind: "mcp", status: "active", config: projectInstallationConfig(connector.config), metadata: { ...connector.metadata, organizationConnectorId: connector.id }, enabledAt: connector.updatedAt.toISOString(), updatedAt: connector.updatedAt.toISOString(), }; } export async function listCapabilityInstallations( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.capabilityInstallations) .where(eq(schema.capabilityInstallations.workspaceId, workspaceId)) .orderBy(desc(schema.capabilityInstallations.updatedAt)); return rows.map(mapCapabilityInstallation); }); } export async function getCapabilityInstallation( db: Database, workspaceId: string, capabilityId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.capabilityId, capabilityId), ), ) .limit(1); return row ? mapCapabilityInstallation(row) : null; }); } /** Drizzle expands a bare JS array into a parameter list, never a text[]. */ function capabilityTextArray(values: readonly string[]) { return values.length === 0 ? sql`ARRAY[]::text[]` : sql`ARRAY[${sql.join( values.map((value) => sql`${value}::text`), sql`, `, )}]::text[]`; } export async function listEnabledMcpCapabilityServers( db: Database, workspaceId: string, /** * Restrict the read to installations of these capabilities plus any catalog * item whose explicit `mcpServerId` mentions one of `serverIds`. Server ids * are computed below, so callers still filter the result by exact id. */ only?: { capabilityIds: readonly string[]; serverIds: readonly string[] }, ): Promise { return (await listEnabledMcpCapabilityRows(db, workspaceId, only)).flatMap( ({ item, installation }) => { const server = enabledMcpCapabilityServerFromRow(item, installation, "installation"); return server ? [server] : []; }, ); } /** * A connector enabled in an origin workspace, as the definition its members' * own (subject-scoped) connections can carry into their Personal workspace. * * Never carries workspace-held credential headers: only the connection * reference, which the caller narrows to the person's own accounts. A curated * (global catalog) connector is projected from its catalog definition alone, * so the origin workspace's per-installation configuration is not copied; a * custom connector defined by the origin workspace keeps its enabled * definition. This is a read of `originWorkspaceId`'s enabled set, NOT an * authorization: the caller must already have established that the person * still holds authority in the origin workspace. */ export type OriginMcpCapabilityServer = Omit & { connectionRef: McpServerConnectionRef; /** `global`: a curated/registry catalog row; `workspace`: the origin's own definition. */ catalogScope: "global" | "workspace"; }; export async function listOriginMcpCapabilityServersForPersonalExtension( db: Database, originWorkspaceId: string, ): Promise { return (await listEnabledMcpCapabilityRows(db, originWorkspaceId)).flatMap( ({ item, installation }) => { const catalogScope = item.workspaceId === null ? "global" : "workspace"; const server = enabledMcpCapabilityServerFromRow( item, installation, catalogScope === "global" ? "catalog" : "installation", ); const connectionRef = server?.connectionRef; if (!server || !connectionRef || connectionRef.authoritySource === "host") return []; const { headersEncrypted: _workspaceHeaders, ...definition } = server; return [{ ...definition, connectionRef, catalogScope }]; }, ); } type EnabledMcpCapabilityRow = { item: typeof schema.capabilityCatalogItems.$inferSelect; installation: typeof schema.capabilityInstallations.$inferSelect; }; async function listEnabledMcpCapabilityRows( db: Database, workspaceId: string, only?: { capabilityIds: readonly string[]; serverIds: readonly string[] }, ): Promise { if (only && only.capabilityIds.length === 0 && only.serverIds.length === 0) return []; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ item: schema.capabilityCatalogItems, installation: schema.capabilityInstallations, }) .from(schema.capabilityInstallations) .innerJoin( schema.capabilityCatalogItems, and( or( eq( schema.capabilityInstallations.workspaceId, schema.capabilityCatalogItems.workspaceId, ), isNull(schema.capabilityCatalogItems.workspaceId), ), eq(schema.capabilityInstallations.capabilityId, schema.capabilityCatalogItems.id), ), ) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.kind, "mcp"), eq(schema.capabilityInstallations.status, "active"), eq(schema.capabilityCatalogItems.stale, false), only ? sql`(${schema.capabilityInstallations.capabilityId} = any(${capabilityTextArray(only.capabilityIds)}) or exists ( select 1 from unnest(${capabilityTextArray(only.serverIds)}) as target(id) where strpos(coalesce(${schema.capabilityCatalogItems.metadata} ->> 'mcpServerId', ''), target.id) > 0 ))` : undefined, sql`( ${schema.capabilityInstallations.metadata} ->> 'facetInstallationId' is null or exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id::text = ${schema.capabilityInstallations.metadata} ->> 'facetInstallationId' and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} ) )`, ), ) .orderBy(asc(schema.capabilityCatalogItems.name)); // A workspace-scoped catalog row and a global registry row can share the // same capability id; the join then matches one installation twice. Keep // one row per installation, preferring the workspace-scoped catalog row // (same precedence as getCapabilityCatalogItem). const preferredByInstallation = new Map(); for (const row of rows) { const existing = preferredByInstallation.get(row.installation.id); if (!existing || (existing.item.workspaceId === null && row.item.workspaceId !== null)) { preferredByInstallation.set(row.installation.id, row); } } const own = [...preferredByInstallation.values()]; const organization = (await organizationConnectorCapabilityRows(scopedDb, workspaceId)).filter( ({ item }) => !only || capabilityRowMatchesOnly(item, only), ); if (organization.length === 0) return own; return await inCatalogNameOrder(scopedDb, [...own, ...organization]); }); } /** The same narrowing as the installation query's `only` filter, for an organization row. */ function capabilityRowMatchesOnly( item: EnabledMcpCapabilityRow["item"], only: { capabilityIds: readonly string[]; serverIds: readonly string[] }, ): boolean { if (only.capabilityIds.includes(item.id)) return true; const explicit = typeof item.metadata.mcpServerId === "string" ? item.metadata.mcpServerId : ""; return only.serverIds.some((id) => explicit.includes(id)); } /** * Rows in the order the installation query gives (`order by name`, ties kept * as listed), so a connector the organization serves sits where the * workspace's own setup of it would. The database sorts, with its collation. */ async function inCatalogNameOrder( scopedDb: Database, rows: readonly EnabledMcpCapabilityRow[], ): Promise { const order = await rawRows<{ position: number }>( scopedDb, sql`select (entry.position - 1)::int as position from unnest(${capabilityTextArray(rows.map(({ item }) => item.name))}) with ordinality as entry(name, position) order by entry.name, entry.position`, ); return order.map(({ position }) => rows[position]!); } /** * The organization's connectors that reach this workspace (row security * decides reach), as the rows a workspace installation of each would give: * the global catalog item for a catalog connector, or a definition of this * workspace's own for a custom server, so a custom server gets no catalog * approval floor, exactly like a workspace's custom server. Any installation * of the same capability in this workspace, on or off, wins: a turned-off * row is how a workspace turns the organization's connector off. */ async function organizationConnectorCapabilityRows( scopedDb: Database, workspaceId: string, ): Promise { const connectors = await scopedDb .select() .from(schema.organizationConnectors) .where( and( eq(schema.organizationConnectors.status, "active"), eq(schema.organizationConnectors.kind, "mcp"), sql`not exists ( select 1 from ${schema.capabilityInstallations} installation where installation.workspace_id = ${workspaceId}::uuid and installation.capability_id = ${schema.organizationConnectors.capabilityId} )`, ), ) .orderBy(asc(schema.organizationConnectors.capabilityId)); if (connectors.length === 0) return []; const catalogIds = connectors .filter((connector) => connector.customDefinition === null) .map((connector) => connector.capabilityId); const catalogItems = catalogIds.length === 0 ? [] : await scopedDb .select() .from(schema.capabilityCatalogItems) .where( and( isNull(schema.capabilityCatalogItems.workspaceId), eq(schema.capabilityCatalogItems.kind, "mcp"), eq(schema.capabilityCatalogItems.stale, false), inArray(schema.capabilityCatalogItems.id, catalogIds), ), ); const catalogItemById = new Map(catalogItems.map((item) => [item.id, item])); return connectors.flatMap((connector) => { const item = connector.customDefinition ? organizationCustomCatalogItem(connector, workspaceId) : catalogItemById.get(connector.capabilityId); if (!item) return []; return [ { item, installation: { id: connector.id, accountId: connector.accountId, workspaceId, capabilityId: connector.capabilityId, kind: "mcp", status: "active", config: connector.config, metadata: connector.metadata, installedBySubjectId: null, enabledAt: connector.updatedAt, updatedAt: connector.updatedAt, }, }, ]; }); } /** A custom organization MCP server's definition; an API integration's has no MCP endpoint. */ function organizationMcpServerDefinition( definition: OrganizationConnectorRow["customDefinition"], ): { name: string; description?: string | null; endpointUrl: string } { if (!definition || "kind" in definition) return { name: definition?.name ?? "", description: null, endpointUrl: "" }; return definition; } /** A custom organization server, defined for the reading workspace. */ function organizationCustomCatalogItem( connector: Pick< OrganizationConnectorRow, "capabilityId" | "accountId" | "customDefinition" | "config" | "createdAt" | "updatedAt" >, workspaceId: string | null, ): EnabledMcpCapabilityRow["item"] { const definition = organizationMcpServerDefinition(connector.customDefinition); return { id: connector.capabilityId, accountId: connector.accountId, workspaceId, kind: "mcp", source: "manual", name: definition.name, description: definition.description ?? null, category: "custom", tags: [], homepageUrl: null, endpointUrl: definition.endpointUrl, installUrl: null, authModel: null, providerDomain: null, surfaceType: null, transport: null, mcpUrl: null, authKind: ["each_person", "auto_connect"].includes(organizationConnectorLogin(connector.config)) ? "oauth2" : null, credentialFacts: [], tier: null, provenance: null, logoAssetPath: null, importBatchId: null, stale: false, staleAt: null, metadata: {}, createdAt: connector.createdAt, updatedAt: connector.updatedAt, }; } /** * The catalog item a custom organization server is listed as in * `workspaceId`, or as the organization defines it (`null`, for * administration and checks before it is saved). */ export function organizationConnectorCatalogItem( connector: Pick< OrganizationConnectorRow, "capabilityId" | "accountId" | "customDefinition" | "config" | "createdAt" | "updatedAt" >, workspaceId: string | null, ): CapabilityCatalogItem { return mapCapabilityCatalogItem(organizationCustomCatalogItem(connector, workspaceId), "trusted"); } /** * Curated and registry catalog connectors (no workspace) trusted for * exposure, by id: the catalog an organization can add connectors from. */ export async function listTrustedGlobalMcpCatalogItems( db: Database, accountId: string, ids: readonly string[], ): Promise { if (ids.length === 0) return []; const rows = await withRlsContext(db, { accountId, workspaceId: null }, async (scopedDb) => scopedDb .select() .from(schema.capabilityCatalogItems) .where( and( isNull(schema.capabilityCatalogItems.workspaceId), eq(schema.capabilityCatalogItems.kind, "mcp"), eq(schema.capabilityCatalogItems.stale, false), inArray(schema.capabilityCatalogItems.id, [...ids]), ), ), ); return rows.flatMap((row) => catalogExposureState(row, null) === "trusted" ? [mapCapabilityCatalogItem(row, "trusted")] : [], ); } /** * `definition: "installation"` is the workspace's own enabled server: catalog * defaults overlaid with the installation's configuration and stored * credentials. `"catalog"` projects the catalog definition alone (no * installation configuration, no stored headers) and keeps only the * installation's connection reference. */ function enabledMcpCapabilityServerFromRow( item: EnabledMcpCapabilityRow["item"], installation: EnabledMcpCapabilityRow["installation"], definition: "installation" | "catalog", ): EnabledMcpCapabilityServer | null { if ( catalogExposureState(item, installation) === "blocked" || !item.endpointUrl || !mcpConnectivityOk(installation.metadata) ) { return null; } const headersEncrypted = definition === "installation" ? encryptedHeadersConfig(installation.config.headersEncrypted) : undefined; const connectionRef = connectionRefConfig(installation.config.connectionRef); if (item.authModel && !headersEncrypted && !connectionRef) { // Credential-gated MCPs are runnable only when either legacy static // credential headers or the connections broker ref were stored at enable // time. return null; } const metadata = item.metadata; const config: Record = definition === "installation" ? installation.config : {}; const allowedTools = stringArrayConfig(config.allowedTools ?? metadata.allowedTools); const timeoutMs = positiveIntegerConfig(config.timeoutMs ?? metadata.timeoutMs); const cacheToolsList = booleanConfig(config.cacheToolsList ?? metadata.cacheToolsList); const requireApproval = resolveMcpApprovalRecommendation( config.requireApproval, metadata.requireApproval, ); return { capabilityId: item.id, id: mcpServerIdForCapability(item.id, metadata), name: item.name, ...(item.category ? { category: item.category } : {}), url: item.endpointUrl, ...(allowedTools ? { allowedTools } : {}), ...(timeoutMs ? { timeoutMs } : {}), ...(cacheToolsList !== undefined ? { cacheToolsList } : {}), ...(requireApproval !== undefined ? { requireApproval } : {}), ...(item.workspaceId === null ? { approvalFloor: sessionMcpApprovalPolicyConfig(metadata.requireApproval) ?? false } : {}), ...(headersEncrypted ? { headersEncrypted } : {}), ...(connectionRef ? { connectionRef } : {}), }; } const ecmaScriptTrimCharacters = "\u0009\u000a\u000b\u000c\u000d\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"; const registryApiKeyContractValidSql = sql`coalesce(( jsonb_typeof(${schema.capabilityCatalogItems.metadata} -> 'authContract') = 'object' and jsonb_typeof(${schema.capabilityCatalogItems.metadata} -> 'authContract' -> 'headerName') = 'string' and (${schema.capabilityCatalogItems.metadata} -> 'authContract' ->> 'headerName') ~ ${"^[A-Za-z0-9!#$%&'*+.^_`|~-]+$"} and jsonb_typeof(${schema.capabilityCatalogItems.metadata} -> 'authContract' -> 'scheme') = 'string' and length(btrim( ${schema.capabilityCatalogItems.metadata} -> 'authContract' ->> 'scheme', ${ecmaScriptTrimCharacters} )) > 0 ), false)`; /** * Metadata-only projection of runnable capability MCP server ids. The query * deliberately computes credential-presence booleans in PostgreSQL and never * selects stored header ciphertext or connection-reference contents. */ export async function listEnabledMcpCapabilityServerIds( db: Database, workspaceId: string, ): Promise { const rows = await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb .select({ installationId: schema.capabilityInstallations.id, itemId: schema.capabilityCatalogItems.id, itemWorkspaceId: schema.capabilityCatalogItems.workspaceId, itemSource: schema.capabilityCatalogItems.source, itemAuthKind: schema.capabilityCatalogItems.authKind, itemAuthModel: schema.capabilityCatalogItems.authModel, itemMcpProbePresent: sql`${schema.capabilityCatalogItems.metadata} ? 'mcpProbe'`, itemMcpProbeStatus: sql< string | null >`${schema.capabilityCatalogItems.metadata} -> 'mcpProbe' ->> 'status'`, itemRegistryApiKeyContractValid: registryApiKeyContractValidSql, itemMcpServerId: sql< string | null >`${schema.capabilityCatalogItems.metadata} ->> 'mcpServerId'`, endpointPresent: sql`coalesce(length(${schema.capabilityCatalogItems.endpointUrl}), 0) > 0`, mcpConnectivityStatus: sql< string | null >`${schema.capabilityInstallations.metadata} -> 'mcpConnectivity' ->> 'status'`, hasEncryptedHeaders: sql`exists ( select 1 from jsonb_each_text( case when jsonb_typeof(${schema.capabilityInstallations.config} -> 'headersEncrypted') = 'object' then ${schema.capabilityInstallations.config} -> 'headersEncrypted' else '{}'::jsonb end ) header where length(header.value) > 0 )`, hasConnectionRef: sql`( jsonb_typeof(${schema.capabilityInstallations.config} -> 'connectionRef') = 'object' and jsonb_typeof(${schema.capabilityInstallations.config} -> 'connectionRef' -> 'providerDomain') = 'string' and length(${schema.capabilityInstallations.config} -> 'connectionRef' ->> 'providerDomain') > 0 )`, }) .from(schema.capabilityInstallations) .innerJoin( schema.capabilityCatalogItems, and( or( eq( schema.capabilityInstallations.workspaceId, schema.capabilityCatalogItems.workspaceId, ), isNull(schema.capabilityCatalogItems.workspaceId), ), eq(schema.capabilityInstallations.capabilityId, schema.capabilityCatalogItems.id), ), ) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.kind, "mcp"), eq(schema.capabilityInstallations.status, "active"), eq(schema.capabilityCatalogItems.stale, false), sql`( ${schema.capabilityInstallations.metadata} ->> 'facetInstallationId' is null or exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id::text = ${schema.capabilityInstallations.metadata} ->> 'facetInstallationId' and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} ) )`, ), ) .orderBy(asc(schema.capabilityCatalogItems.name)), ); const preferredByInstallation = new Map(); for (const row of rows) { const existing = preferredByInstallation.get(row.installationId); if (!existing || (existing.itemWorkspaceId === null && row.itemWorkspaceId !== null)) { preferredByInstallation.set(row.installationId, row); } } const own = [...preferredByInstallation.values()].flatMap(runnableMcpServerIdFromMetadata); const organization = (await organizationConnectorServerIdRows(db, workspaceId)).flatMap( runnableMcpServerIdFromMetadata, ); return organization.length === 0 ? own : [...own, ...organization]; } type McpServerIdMetadataRow = { itemId: string; itemSource: string; itemAuthKind: string | null; itemAuthModel: string | null; itemMcpProbePresent: boolean; itemMcpProbeStatus: string | null; itemRegistryApiKeyContractValid: boolean; itemMcpServerId: string | null; endpointPresent: boolean; mcpConnectivityStatus: string | null; hasEncryptedHeaders: boolean; hasConnectionRef: boolean; }; function runnableMcpServerIdFromMetadata(row: McpServerIdMetadataRow): string[] { const metadata = row.itemMcpServerId !== null ? { mcpServerId: row.itemMcpServerId } : {}; const trusted = row.itemSource !== registryCapabilitySource || (row.itemMcpProbePresent && row.itemMcpProbeStatus === "real" && row.itemAuthKind !== null && row.itemAuthKind !== "unknown" && (row.itemAuthKind !== "api_key" || row.itemRegistryApiKeyContractValid)); const connectivityOk = row.mcpConnectivityStatus === "ok" || row.mcpConnectivityStatus === "auth_deferred"; const legacyActive = !trusted && row.itemSource === registryCapabilitySource && !row.itemMcpProbePresent && row.itemAuthKind !== null && row.itemAuthKind !== "unknown" && connectivityOk && (!row.itemAuthModel || row.hasEncryptedHeaders || row.hasConnectionRef); if ( (!trusted && !legacyActive) || !row.endpointPresent || !connectivityOk || (row.itemAuthModel && !row.hasEncryptedHeaders && !row.hasConnectionRef) ) { return []; } return [mcpServerIdForCapability(row.itemId, metadata)]; } /** * `listEnabledMcpCapabilityServerIds` for the organization's connectors that * reach the workspace and that no installation here overrides: the same * credential-presence booleans, computed in PostgreSQL, never the stored * header ciphertext or connection reference. */ async function organizationConnectorServerIdRows( db: Database, workspaceId: string, ): Promise { const connector = schema.organizationConnectors; const rows = await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb .select({ itemId: connector.capabilityId, custom: sql`${connector.customDefinition} is not null`, customEndpointPresent: sql`coalesce(length(${connector.customDefinition} ->> 'endpointUrl'), 0) > 0`, catalogItemPresent: sql`${schema.capabilityCatalogItems.id} is not null`, itemSource: schema.capabilityCatalogItems.source, itemAuthKind: schema.capabilityCatalogItems.authKind, itemAuthModel: schema.capabilityCatalogItems.authModel, itemMcpProbePresent: sql`coalesce(${schema.capabilityCatalogItems.metadata} ? 'mcpProbe', false)`, itemMcpProbeStatus: sql< string | null >`${schema.capabilityCatalogItems.metadata} -> 'mcpProbe' ->> 'status'`, itemRegistryApiKeyContractValid: registryApiKeyContractValidSql, itemMcpServerId: sql< string | null >`${schema.capabilityCatalogItems.metadata} ->> 'mcpServerId'`, catalogEndpointPresent: sql`coalesce(length(${schema.capabilityCatalogItems.endpointUrl}), 0) > 0`, mcpConnectivityStatus: sql< string | null >`${connector.metadata} -> 'mcpConnectivity' ->> 'status'`, hasEncryptedHeaders: sql`exists ( select 1 from jsonb_each_text( case when jsonb_typeof(${connector.config} -> 'headersEncrypted') = 'object' then ${connector.config} -> 'headersEncrypted' else '{}'::jsonb end ) header where length(header.value) > 0 )`, hasConnectionRef: sql`( jsonb_typeof(${connector.config} -> 'connectionRef') = 'object' and jsonb_typeof(${connector.config} -> 'connectionRef' -> 'providerDomain') = 'string' and length(${connector.config} -> 'connectionRef' ->> 'providerDomain') > 0 )`, }) .from(connector) .leftJoin( schema.capabilityCatalogItems, and( isNull(connector.customDefinition), isNull(schema.capabilityCatalogItems.workspaceId), eq(schema.capabilityCatalogItems.kind, "mcp"), eq(schema.capabilityCatalogItems.stale, false), eq(schema.capabilityCatalogItems.id, connector.capabilityId), ), ) .where( and( eq(connector.status, "active"), eq(connector.kind, "mcp"), sql`not exists ( select 1 from ${schema.capabilityInstallations} installation where installation.workspace_id = ${workspaceId}::uuid and installation.capability_id = ${connector.capabilityId} )`, ), ) .orderBy(asc(connector.capabilityId)), ); return rows.flatMap((row) => { if (row.custom) // A custom organization server is defined like a workspace's own custom // server: a manual source with no catalog credential contract. return [ { itemId: row.itemId, itemSource: "manual", itemAuthKind: null, itemAuthModel: null, itemMcpProbePresent: false, itemMcpProbeStatus: null, itemRegistryApiKeyContractValid: false, itemMcpServerId: null, endpointPresent: row.customEndpointPresent, mcpConnectivityStatus: row.mcpConnectivityStatus, hasEncryptedHeaders: row.hasEncryptedHeaders, hasConnectionRef: row.hasConnectionRef, }, ]; if (!row.catalogItemPresent || row.itemSource === null) return []; return [ { itemId: row.itemId, itemSource: row.itemSource, itemAuthKind: row.itemAuthKind, itemAuthModel: row.itemAuthModel, itemMcpProbePresent: row.itemMcpProbePresent, itemMcpProbeStatus: row.itemMcpProbeStatus, itemRegistryApiKeyContractValid: row.itemRegistryApiKeyContractValid, itemMcpServerId: row.itemMcpServerId, endpointPresent: row.catalogEndpointPresent, mcpConnectivityStatus: row.mcpConnectivityStatus, hasEncryptedHeaders: row.hasEncryptedHeaders, hasConnectionRef: row.hasConnectionRef, }, ]; }); } /** * Decrypts an enabled capability MCP's stored credential headers. Returns * null when the server has none, and "unavailable" when headers exist but * cannot be recovered (missing key or failed decryption) — in which case the * server must be skipped rather than connected without credentials. */ export function decryptedCapabilityHeaders( server: EnabledMcpCapabilityServer, encryptionKey: Uint8Array | null, ): Record | null | "unavailable" { if (!server.headersEncrypted || Object.keys(server.headersEncrypted).length === 0) { return null; } if (!encryptionKey) { return "unavailable"; } try { return Object.fromEntries( Object.entries(server.headersEncrypted).map(([name, value]) => [ name, decryptEnvironmentValue(encryptionKey, value), ]), ); } catch { return "unavailable"; } } /** * Returns the encrypted credential-header map stored on a capability * installation, or null when none is stored. This is the only read path for * the ciphertext besides listEnabledMcpCapabilityServers; the generic * installation mapping projects it to header names. */ export async function getStoredCapabilityHeaderCiphertext( db: Database, workspaceId: string, capabilityId: string, ): Promise | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ config: schema.capabilityInstallations.config }) .from(schema.capabilityInstallations) .where( and( eq(schema.capabilityInstallations.workspaceId, workspaceId), eq(schema.capabilityInstallations.capabilityId, capabilityId), ), ) .limit(1); return row ? (encryptedHeadersConfig(row.config.headersEncrypted) ?? null) : null; }); } export function mcpServerIdForCapability( capabilityId: string, metadata: Record = {}, ): string { const explicit = typeof metadata.mcpServerId === "string" ? metadata.mcpServerId.trim() : ""; if (/^[A-Za-z0-9_-]+$/.test(explicit)) { return explicit; } const body = capabilityId .replace(/^[^:]+:/, "") .toLowerCase() .replace(/[^a-z0-9_-]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 44) || "mcp"; return `cap-${body}-${shortHash(capabilityId)}`; } function connectionExactSubject(subjectId?: string | null): SQL { return subjectId ? eq(schema.connections.subjectId, subjectId) : isNull(schema.connections.subjectId); } function personalSlackCanonicalConnectionOrder(): SQL[] { return [ sql`case ${schema.connections.status} when 'active' then 0 when 'needs_reauth' then 1 when 'error' then 2 when 'revoked' then 3 else 4 end`, desc(schema.connections.updatedAt), desc(schema.connections.createdAt), desc(schema.connections.id), ]; } const connectionAccessPolicyColumns = { allowedModelIds: schema.connections.allowedModelIds, allowedWorkspaceIds: schema.connections.allowedWorkspaceIds, allowPersonalWorkspaces: schema.connections.allowPersonalWorkspaces, accessPolicyVersion: schema.connections.accessPolicyVersion, accessPolicyUpdatedBy: schema.connections.accessPolicyUpdatedBy, accessPolicyUpdatedAt: schema.connections.accessPolicyUpdatedAt, }; // Internal-only: credential replacement preserves the locked connection's access policy. // Public connection creation must not accept these administration-owned fields. type ConnectionAccessPolicySnapshot = Pick< typeof schema.connections.$inferSelect, | "allowedModelIds" | "allowedWorkspaceIds" | "allowPersonalWorkspaces" | "accessPolicyVersion" | "accessPolicyUpdatedBy" | "accessPolicyUpdatedAt" >; function connectionAccessPolicySnapshot( row: ConnectionAccessPolicySnapshot, ): ConnectionAccessPolicySnapshot { return { allowedModelIds: row.allowedModelIds, allowedWorkspaceIds: row.allowedWorkspaceIds, allowPersonalWorkspaces: row.allowPersonalWorkspaces, accessPolicyVersion: row.accessPolicyVersion, accessPolicyUpdatedBy: row.accessPolicyUpdatedBy, accessPolicyUpdatedAt: row.accessPolicyUpdatedAt, }; } async function createConnectionInScope( db: Database, input: CreateConnectionInput, accessPolicy?: ConnectionAccessPolicySnapshot, ): Promise { const [row] = await db .insert(schema.connections) .values({ ...accessPolicy, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, providerDomain: input.providerDomain, kind: input.kind, status: input.status ?? "active", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes ?? [], expiresAt: input.expiresAt ?? null, verifiedInstallAt: input.verifiedInstallAt ?? null, verifiedInstallVersion: input.verifiedInstallVersion ?? null, metadata: input.metadata ?? {}, accountIdentityKey: input.accountIdentityKey ?? null, label: input.label ?? null, createdBySubjectId: input.createdBySubjectId ?? null, updatedBySubjectId: input.updatedBySubjectId ?? input.createdBySubjectId ?? null, }) .returning(connectionMetadataColumns) .catch(rethrowAccountIdentityConflict); if (!row) { throw new Error("Failed to create connection"); } return mapConnectionMetadata(row); } export class ConnectionCreateIdempotencyError extends Error { constructor() { super("Connection operationId was already used with different input"); this.name = "ConnectionCreateIdempotencyError"; } } export async function getConnectionCreationResult( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; operationId: string }, ) { return withRlsContext(db, input, async (tx) => { await setSubjectRlsContext(tx, input.subjectId); const [receipt] = await tx .select({ id: schema.connections.id }) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.createdBySubjectId, input.subjectId), eq(schema.connections.createOperationId, input.operationId), ), ) .limit(1); return receipt ? getConnectionMetadata(tx, input.workspaceId, receipt.id, input.subjectId) : null; }); } export async function createConnectionIdempotently( db: Database, input: CreateConnectionInput & { operation?: { id: string; requestDigest: string }; /** Runs inside the first creation transaction, never on operation replay. */ onCreated?: ( tx: Database, connection: Awaited>, ) => Promise; }, ) { const operation = input.operation; if (!operation) { if (input.onCreated) throw new Error("Initial connection setup requires an operationId"); return createConnection(db, input); } const actor = input.createdBySubjectId; if (!actor) throw new Error("Idempotent connection creation requires an initiating subject"); return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { await setSubjectRlsContext(tx, actor); await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`connection-create:${input.workspaceId}:${actor}:${operation.id}`}, 0))`, ); const [existing] = await tx .select({ id: schema.connections.id, digest: schema.connections.createRequestDigest, }) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.createdBySubjectId, actor), eq(schema.connections.createOperationId, operation.id), ), ) .limit(1); if (existing) { if (existing.digest !== operation.requestDigest) throw new ConnectionCreateIdempotencyError(); const connection = await getConnectionMetadata(tx, input.workspaceId, existing.id, actor); if (!connection) throw new ConnectionCreateIdempotencyError(); return connection; } const connection = await createConnection(tx, input); await input.onCreated?.(tx, connection); const [receipt] = await tx .update(schema.connections) .set({ createOperationId: operation.id, createRequestDigest: operation.requestDigest, }) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, connection.id), ), ) .returning({ id: schema.connections.id }); if (!receipt) throw new Error("Connection creation receipt was not persisted"); return connection; }, ); } /** * The key that makes a connection one verified provider account of one * integration: `parts` name the integration (backend, provider, resource) and * then the account as the provider identifies it. Each owner (a person within * an organization, or a workspace) holds at most one live connection per key; * a second insert or reactivation fails with ConnectionAccountAlreadyConnectedError. * Writers stamp it only for an account they verified: an unknown account is * never deduplicated on a guess. */ export function connectionAccountIdentityKey(parts: readonly string[]): string { if (parts.length < 2 || parts.some((part) => typeof part !== "string" || !part)) throw new Error("A connection account identity needs its integration and account"); return createHash("sha256").update(JSON.stringify(parts)).digest("hex"); } /** Another live connection of the same owner already holds this account. */ export class ConnectionAccountAlreadyConnectedError extends Error { constructor() { super("This account is already connected"); this.name = "ConnectionAccountAlreadyConnectedError"; } } /** Whether an error is the live-account uniqueness check (migration 1481). */ export function isConnectionAccountIdentityConflict(error: unknown): boolean { if (error instanceof ConnectionAccountAlreadyConnectedError) return true; return ( nestedPostgresSqlState(error) === "23505" && safeDatabaseErrorFacts(error).constraint === "connections_live_account_identity_uq" ); } function rethrowAccountIdentityConflict(error: unknown): never { throw isConnectionAccountIdentityConflict(error) ? new ConnectionAccountAlreadyConnectedError() : error; } export async function createConnection( db: Database, input: CreateConnectionInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) { await setSubjectRlsContext(scopedDb, input.subjectId); } return await createConnectionInScope(scopedDb, input); }, ); } export type WorkspaceProviderApiKeyConnectionKind = | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "elevenlabs"; type WorkspaceProviderApiKeyConnectionSpec = { providerDomain: string; credentialRole: string; operationIdMetadataKey: string; operationDigestMetadataKey: string; label: string; }; export function workspaceProviderApiKeyConnectionSpec( providerKind: WorkspaceProviderApiKeyConnectionKind, ): WorkspaceProviderApiKeyConnectionSpec { if (providerKind === "anthropic" || providerKind === "claude_subscription") { return { providerDomain: "api.anthropic.com", credentialRole: providerKind, operationIdMetadataKey: `${providerKind}CredentialOperationId`, operationDigestMetadataKey: `${providerKind}CredentialOperationDigest`, label: providerKind === "anthropic" ? "Anthropic API" : "Claude subscription", }; } if (providerKind === "elevenlabs") { return { providerDomain: WORKSPACE_ELEVENLABS_CONNECTION_DOMAIN, credentialRole: WORKSPACE_ELEVENLABS_CONNECTION_ROLE, operationIdMetadataKey: "elevenlabsCredentialOperationId", operationDigestMetadataKey: "elevenlabsCredentialOperationDigest", label: "ElevenLabs", }; } if (providerKind === "opper") { return { providerDomain: WORKSPACE_OPPER_CONNECTION_DOMAIN, credentialRole: WORKSPACE_OPPER_CONNECTION_ROLE, operationIdMetadataKey: OPPER_CREDENTIAL_OPERATION_ID_METADATA_KEY, operationDigestMetadataKey: OPPER_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, label: "Opper", }; } return providerKind === "vercel_gateway" ? { providerDomain: VERCEL_AI_GATEWAY_CONNECTION_DOMAIN, credentialRole: VERCEL_AI_GATEWAY_CONNECTION_ROLE, operationIdMetadataKey: VERCEL_AI_GATEWAY_CREDENTIAL_OPERATION_ID_METADATA_KEY, operationDigestMetadataKey: VERCEL_AI_GATEWAY_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, label: "Vercel AI Gateway", } : { providerDomain: WORKSPACE_OPENROUTER_CONNECTION_DOMAIN, credentialRole: WORKSPACE_OPENROUTER_CONNECTION_ROLE, operationIdMetadataKey: OPENROUTER_CREDENTIAL_OPERATION_ID_METADATA_KEY, operationDigestMetadataKey: OPENROUTER_CREDENTIAL_OPERATION_DIGEST_METADATA_KEY, label: "OpenRouter", }; } async function lockWorkspaceProviderApiKeyConnection( db: Database, workspaceId: string, providerKind: WorkspaceProviderApiKeyConnectionKind, ): Promise { const lockKey = providerKind === "vercel_gateway" ? `workspace-vercel-ai-gateway:${workspaceId}` : `workspace-${providerKind}:${workspaceId}`; await db.execute(sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`); } export async function upsertWorkspaceProviderApiKeyConnection( db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: UpsertWorkspaceProviderApiKeyConnectionInput, ): Promise { const spec = workspaceProviderApiKeyConnectionSpec(providerKind); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockWorkspaceProviderApiKeyConnection(tx, input.workspaceId, providerKind); const rows = await tx .select({ ...connectionMetadataColumns, ...connectionAccessPolicyColumns }) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), isNull(schema.connections.subjectId), sql`lower(${schema.connections.providerDomain}) = lower(${spec.providerDomain})`, eq(schema.connections.kind, "api_key"), sql`${schema.connections.metadata} ->> 'credentialRole' = ${spec.credentialRole}`, ), ) .orderBy( desc(sql`(${schema.connections.status} = 'active')`), desc(schema.connections.updatedAt), desc(schema.connections.createdAt), desc(schema.connections.id), ) .for("update"); const metadata = { ...(input.metadata ?? {}), credentialRole: spec.credentialRole, [spec.operationIdMetadataKey]: input.operationId, [spec.operationDigestMetadataKey]: input.requestDigest, }; const operationRow = rows.find( (row) => row.metadata[spec.operationIdMetadataKey] === input.operationId, ); if (operationRow) { return operationRow.metadata[spec.operationDigestMetadataKey] === input.requestDigest ? mapConnectionMetadata(operationRow) : null; } if (rows.some((row) => row.status !== "revoked")) return null; return await createConnectionInScope( tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: null, providerDomain: spec.providerDomain, kind: "api_key", status: "active", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes ?? [], expiresAt: input.expiresAt ?? null, metadata, createdBySubjectId: input.updatedBySubjectId, updatedBySubjectId: input.updatedBySubjectId, }, // Reconnecting cannot reset an administrator's restrictions. Rows are newest first. rows[0] ? connectionAccessPolicySnapshot(rows[0]) : undefined, ); }), ); } export async function rotateWorkspaceProviderApiKeyConnection( db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: RotateWorkspaceProviderApiKeyConnectionInput, ): Promise { const spec = workspaceProviderApiKeyConnectionSpec(providerKind); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockWorkspaceProviderApiKeyConnection(tx, input.workspaceId, providerKind); const rows = await tx .select({ ...connectionMetadataColumns, ...connectionAccessPolicyColumns }) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), isNull(schema.connections.subjectId), sql`lower(${schema.connections.providerDomain}) = lower(${spec.providerDomain})`, eq(schema.connections.kind, "api_key"), sql`${schema.connections.metadata} ->> 'credentialRole' = ${spec.credentialRole}`, ), ) .orderBy(desc(schema.connections.updatedAt), desc(schema.connections.id)) .for("update"); const operationRow = rows.find( (row) => row.metadata[spec.operationIdMetadataKey] === input.operationId, ); if (operationRow) { return operationRow.status !== "revoked" && operationRow.metadata[spec.operationDigestMetadataKey] === input.requestDigest ? mapConnectionMetadata(operationRow) : null; } const targetRow = rows.find((row) => row.id === input.connectionId); if ( !targetRow || targetRow.status === "revoked" || targetRow.version !== input.expectedVersion ) { return null; } const metadata = { ...(input.metadata ?? {}), credentialRole: spec.credentialRole, [spec.operationIdMetadataKey]: input.operationId, [spec.operationDigestMetadataKey]: input.requestDigest, }; for (const row of rows.filter((candidate) => candidate.status !== "revoked")) { const revoked = await revokeConnectionInScope( tx, input.workspaceId, row.id, input.updatedBySubjectId, row.version, ); if (!revoked) { throw new Error(`${spec.label} connection changed during rotation`); } } return await createConnectionInScope( tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: null, providerDomain: spec.providerDomain, kind: "api_key", status: "active", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes ?? [], expiresAt: input.expiresAt ?? null, metadata, createdBySubjectId: input.updatedBySubjectId, updatedBySubjectId: input.updatedBySubjectId, }, connectionAccessPolicySnapshot(targetRow), ); }), ); } export async function revokeWorkspaceProviderApiKeyConnections( db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: RevokeWorkspaceProviderApiKeyConnectionsInput, ): Promise { const spec = workspaceProviderApiKeyConnectionSpec(providerKind); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockWorkspaceProviderApiKeyConnection(tx, input.workspaceId, providerKind); const [targetRow] = await tx .select(connectionMetadataColumns) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), isNull(schema.connections.subjectId), ), ) .for("update") .limit(1); if ( !targetRow || targetRow.providerDomain.toLowerCase() !== spec.providerDomain || targetRow.kind !== "api_key" || targetRow.metadata.credentialRole !== spec.credentialRole ) { return null; } // A replay of an already-committed DELETE is idempotent for that exact // connection generation. It must not sweep a newer provider connection // that was established after the original response was lost. if (targetRow.status === "revoked") { return mapConnectionMetadata(targetRow); } if (targetRow.version !== input.expectedVersion) { return null; } const providerRows = await tx .select(connectionMetadataColumns) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), isNull(schema.connections.subjectId), sql`lower(${schema.connections.providerDomain}) = lower(${spec.providerDomain})`, eq(schema.connections.kind, "api_key"), ne(schema.connections.status, "revoked"), sql`${schema.connections.metadata} ->> 'credentialRole' = ${spec.credentialRole}`, ), ) .orderBy(desc(schema.connections.updatedAt), desc(schema.connections.id)) .for("update"); let result = mapConnectionMetadata(targetRow); const alsoRevokedConnectionIds: string[] = []; for (const row of providerRows) { const revoked = await revokeConnectionInScope( tx, input.workspaceId, row.id, input.updatedBySubjectId, row.version, ); if (!revoked) { throw new Error(`${spec.label} connection changed during disconnect`); } if (row.id === input.connectionId) result = revoked; else alsoRevokedConnectionIds.push(row.id); } // The target was live (an already revoked one returned above): one // record for the disconnect, naming the older rows it also retired. if (input.audit) { await auditConnectionDisconnectInScope(tx, result, input.audit, { ...(alsoRevokedConnectionIds.length > 0 ? { alsoRevokedConnectionIds } : {}), }); } return result; }), ); } /** Compatibility wrapper for the existing Vercel AI Gateway create/replay contract. */ export async function upsertWorkspaceVercelAiGatewayConnection( db: Database, input: UpsertWorkspaceVercelAiGatewayConnectionInput, ): Promise { return await upsertWorkspaceProviderApiKeyConnection(db, "vercel_gateway", input); } export async function upsertWorkspaceOpenRouterConnection( db: Database, input: UpsertWorkspaceOpenRouterConnectionInput, ): Promise { return await upsertWorkspaceProviderApiKeyConnection(db, "openrouter", input); } /** Compatibility wrapper for the existing Vercel AI Gateway rotation contract. */ export async function rotateWorkspaceVercelAiGatewayConnection( db: Database, input: RotateWorkspaceVercelAiGatewayConnectionInput, ): Promise { return await rotateWorkspaceProviderApiKeyConnection(db, "vercel_gateway", input); } export async function rotateWorkspaceOpenRouterConnection( db: Database, input: RotateWorkspaceOpenRouterConnectionInput, ): Promise { return await rotateWorkspaceProviderApiKeyConnection(db, "openrouter", input); } /** Compatibility wrapper for the existing Vercel AI Gateway revoke contract. */ export async function revokeWorkspaceVercelAiGatewayConnections( db: Database, input: RevokeWorkspaceVercelAiGatewayConnectionsInput, ): Promise { return await revokeWorkspaceProviderApiKeyConnections(db, "vercel_gateway", input); } export async function revokeWorkspaceOpenRouterConnections( db: Database, input: RevokeWorkspaceOpenRouterConnectionsInput, ): Promise { return await revokeWorkspaceProviderApiKeyConnections(db, "openrouter", input); } /** * Serialize one provider-principal/owner connection generation. Distinct OAuth * starts for the same principal converge on one row, while an explicit * reconnect remains fenced to the exact Connection version captured in state. */ export async function persistProviderOAuthConnection( db: Database, input: PersistProviderOAuthConnectionInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) { await setSubjectRlsContext(scopedDb, input.subjectId); } return await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const ownerKey = input.subjectId ?? "workspace"; if (input.authorize) { await input.authorize(tx); await setRlsContext(tx, { accountId: input.accountId, workspaceId: input.workspaceId }); await setSubjectRlsContext(tx, input.subjectId ?? input.visibleToSubjectId ?? ""); } if (input.requireLiveUserAuthority) { if (!input.subjectId) { throw new Error("Live user authority requires a subject-owned connection"); } // Serialize with organization-membership lifecycle commands before // deriving authority and firing the connection-authority trigger. await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ); const [membership] = await tx .select({ accountId: schema.workspaceMemberships.accountId, permissions: schema.workspaceMemberships.permissions, }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, input.workspaceId), eq(schema.workspaceMemberships.subjectId, input.subjectId), membershipOutsidePersonalWorkspace(), ), ) .for("update") .limit(1); const hasLiveAuthority = await subjectHasLiveWorkspaceAuthorityInScope(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, }); if (!hasLiveAuthority) { throw new Error("Connection owner no longer has live workspace authority"); } if (membership) { const permissions = normalizeWorkspaceMembershipPermissions(membership.permissions); if ( membership.accountId !== input.accountId || (input.requiredLiveUserPermission && !permissions.includes(input.requiredLiveUserPermission) && !permissions.includes("workspace:admin")) ) { throw new Error("Connection owner no longer has the required workspace permission"); } } else if (!input.allowCanonicalPersonalWorkspaceOwner) { throw new Error("Connection owner has no lockable workspace membership"); } } if (input.exclusiveProviderPrincipalPerOwner) { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`provider-oauth-owner:${input.workspaceId}:${ownerKey}:${input.providerDomain}:${input.providerFamily}`}, 0))`, ); const [conflict] = await tx .select({ id: schema.connections.id }) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), connectionExactSubject(input.subjectId ?? null), eq(schema.connections.providerDomain, input.providerDomain), eq(schema.connections.kind, "oauth2"), ne(schema.connections.status, "revoked"), sql`${schema.connections.metadata} ->> 'credentialRole' = ${input.credentialRole}`, sql`${schema.connections.metadata} ->> 'providerFamily' = ${input.providerFamily}`, sql`${schema.connections.metadata} ->> 'providerPrincipalId' is distinct from ${input.providerPrincipalId}`, ), ) .limit(1); if (conflict) return null; } await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`provider-oauth-connection:${input.workspaceId}:${ownerKey}:${input.providerDomain}:${input.providerFamily}:${input.providerPrincipalId}`}, 0))`, ); const exactOwner = connectionExactSubject(input.subjectId ?? null); // One live connection per owner, workspace and provider principal. const accountIdentityKey = connectionAccountIdentityKey([ "provider-oauth", input.workspaceId, input.providerDomain, input.providerFamily, input.credentialRole, input.providerPrincipalId, ]); const requested = input.requestedConnectionId ? ( await tx .select(connectionMetadataColumns) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.requestedConnectionId), exactOwner, ), ) .for("update") .limit(1) )[0] : null; if ( input.requestedConnectionId && (!requested || requested.version !== input.requestedConnectionVersion || requested.providerDomain !== input.providerDomain || requested.kind !== "oauth2" || requested.metadata.credentialRole !== input.credentialRole || requested.metadata.providerFamily !== input.providerFamily || requested.metadata.providerPrincipalId !== input.providerPrincipalId) ) { return null; } const existing = requested ?? ( await tx .select(connectionMetadataColumns) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), exactOwner, eq(schema.connections.providerDomain, input.providerDomain), eq(schema.connections.kind, "oauth2"), sql`${schema.connections.metadata} ->> 'credentialRole' = ${input.credentialRole}`, sql`${schema.connections.metadata} ->> 'providerFamily' = ${input.providerFamily}`, sql`${schema.connections.metadata} ->> 'providerPrincipalId' = ${input.providerPrincipalId}`, ), ) // A live row first: reactivating a revoked duplicate would // collide with the live row that holds the account. .orderBy( sql`${schema.connections.status} = 'revoked'`, desc(schema.connections.updatedAt), desc(schema.connections.id), ) .for("update") .limit(1) )[0]; if (!existing) { const created = await createConnectionInScope(tx, { ...input, accountIdentityKey }); if (input.requireLiveUserAuthority && !created.authorityId) { throw new Error("Connection owner authority was not bound"); } return created; } if ( !input.requestedConnectionId && existing.grantedScopes.some((scope) => !(input.grantedScopes ?? []).includes(scope)) ) { return null; } const existingDefinitionIds = Array.isArray(existing.metadata.authorizedDefinitionIds) ? existing.metadata.authorizedDefinitionIds.filter( (value): value is string => typeof value === "string", ) : []; const incomingDefinitionIds = Array.isArray(input.metadata?.authorizedDefinitionIds) ? input.metadata.authorizedDefinitionIds.filter( (value): value is string => typeof value === "string", ) : []; const preservedMetadata = Object.fromEntries( (input.preserveExistingMetadataKeys ?? []) .filter((key) => Object.prototype.hasOwnProperty.call(existing.metadata, key)) .map((key) => [key, existing.metadata[key]]), ); const updated = await updateConnectionInScope(tx, { workspaceId: input.workspaceId, connectionId: existing.id, visibleToSubjectId: input.visibleToSubjectId, expectedVersion: existing.version, subjectId: input.subjectId ?? null, providerDomain: input.providerDomain, kind: "oauth2", status: input.status ?? "active", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes ?? [], expiresAt: input.expiresAt ?? null, accountIdentityKey, // Matched on the same provider principal: the same account. previousAccountIdentityKey: accountIdentityKey, metadata: { ...existing.metadata, ...(input.metadata ?? {}), ...preservedMetadata, ...(existingDefinitionIds.length > 0 || incomingDefinitionIds.length > 0 ? { authorizedDefinitionIds: [ ...new Set([...existingDefinitionIds, ...incomingDefinitionIds]), ].sort(), } : {}), }, updatedBySubjectId: input.updatedBySubjectId ?? input.createdBySubjectId ?? null, }); if (input.requireLiveUserAuthority && updated && !updated.authorityId) { throw new Error("Connection owner authority was not bound"); } return updated; }); }, ); } function personalGitHubRepositorySelectionStateFromDatabase( value: unknown, ): PersonalGitHubRepositorySelectionState | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const record = value as Record; if (!Array.isArray(record.repositories)) return null; return { connectionAuthorityGeneration: Number(record.connectionAuthorityGeneration), credentialBindingId: String(record.credentialBindingId), providerPrincipalId: String(record.providerPrincipalId), selectionGeneration: Number(record.selectionGeneration), allRepositoriesAccess: record.allRepositoriesAccess === "read" || record.allRepositoriesAccess === "write" ? record.allRepositoriesAccess : null, allRepositoriesGeneration: record.allRepositoriesGeneration === null || record.allRepositoriesGeneration === undefined ? null : Number(record.allRepositoriesGeneration), repositories: record.repositories.map((item) => { const repository = item as Record; return { repositoryId: String(repository.repositoryId), fullName: String(repository.fullName), canonicalUrl: String(repository.canonicalUrl), defaultBranch: String(repository.defaultBranch), visibility: repository.visibility as "public" | "private" | "internal", private: repository.private === true, archived: repository.archived === true, disabled: repository.disabled === true, permissions: repository.permissions as PersonalGitHubRepositoryPermissions, selectedAccess: repository.selectedAccess as "read" | "write", selectionGeneration: Number(repository.selectionGeneration), selectedAt: String(repository.selectedAt), lastVerifiedAt: String(repository.lastVerifiedAt), }; }), }; } export async function getPersonalGitHubRepositorySelectionState( db: Database, input: { accountId: string; originWorkspaceId: string; subjectId: string; connectionId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.originWorkspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); const rows = await scopedDb.execute(sql<{ state: unknown }>` select get_self_personal_github_repository_selection( ${input.accountId}::uuid, ${input.originWorkspaceId}::uuid, ${input.subjectId}, ${input.connectionId}::uuid ) as state `); return personalGitHubRepositorySelectionStateFromDatabase( (rows as unknown as Array<{ state?: unknown }>)[0]?.state, ); }, ); } async function mutatePersonalGitHubRepositorySelections( db: Database, input: PersonalGitHubRepositorySelectionMutationInput, verifyOnly: boolean, ): Promise { try { const result = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.originWorkspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); const rows = await scopedDb.execute(sql<{ state: unknown }>` select mutate_self_personal_github_repository_selection( ${input.accountId}::uuid, ${input.originWorkspaceId}::uuid, ${input.subjectId}, ${input.connectionId}::uuid, ${input.expectedConnectionAuthorityGeneration}, ${input.expectedSelectionGeneration}, ${input.idempotencyKey}, ${JSON.stringify( input.allRepositoriesAccess === undefined ? input.repositories : { repositories: input.repositories, allRepositoriesAccess: input.allRepositoriesAccess, }, )}::jsonb, ${verifyOnly} ) as state `); return personalGitHubRepositorySelectionStateFromDatabase( (rows as unknown as Array<{ state?: unknown }>)[0]?.state, ); }, ); if (!result) throw new PersonalGitHubRepositorySelectionUnavailableError(); return result; } catch (error) { if ( error instanceof PersonalGitHubRepositorySelectionUnavailableError || error instanceof PersonalGitHubRepositorySelectionChangedError || error instanceof PersonalGitHubRepositorySelectionIdempotencyError ) { throw error; } const state = nestedPostgresSqlState(error); if (state === "23505") throw new PersonalGitHubRepositorySelectionIdempotencyError(); if (state === "40001") throw new PersonalGitHubRepositorySelectionChangedError(); if (state === "42501") throw new PersonalGitHubRepositorySelectionUnavailableError(); throw error; } } export async function replacePersonalGitHubRepositorySelections( db: Database, input: PersonalGitHubRepositorySelectionMutationInput, ): Promise { return await mutatePersonalGitHubRepositorySelections(db, input, false); } export async function verifyPersonalGitHubRepositorySelections( db: Database, input: PersonalGitHubRepositorySelectionMutationInput, ): Promise { return await mutatePersonalGitHubRepositorySelections(db, input, true); } /** * A new credential advances the connection's authority generation, so work * accepted with the old one stops using it, unless it is the same verified * account signing in again: the stored row already holds this account's key, * and the new grant keeps every scope the row had. Then it is a fresh token * for the same authority, and accepted turns keep working through the * reconnect. A different account, a narrower grant, an unverified account, a * status change (the connections trigger advances it) or an owner change * (immutable) still advance it. */ function sameAccountReconnectGeneration(input: UpdateConnectionInput) { const next = sql`${schema.connections.authorityGeneration} + 1`; const incoming = input.accountIdentityKey !== undefined ? input.accountIdentityKey : input.vouchedAccountIdentityKey; if (!incoming) return next; // A row saved before keys existed carries none; the writer then vouches // for the stored row's account with the key it derives from that row. const stored = input.previousAccountIdentityKey ? sql`coalesce(${schema.connections.accountIdentityKey}, ${input.previousAccountIdentityKey})` : sql`${schema.connections.accountIdentityKey}`; const keepsScopes = input.grantedScopes === undefined ? sql`true` : sql`${JSON.stringify(input.grantedScopes)}::jsonb @> ${schema.connections.grantedScopes}`; return sql`case when ${stored} = ${incoming} and ${keepsScopes} then ${schema.connections.authorityGeneration} else ${next} end`; } async function updateConnectionInScope( db: Database, input: UpdateConnectionInput, ): Promise { const set = { updatedAt: new Date(), ...(input.providerDomain !== undefined ? { providerDomain: input.providerDomain } : {}), ...(input.subjectId !== undefined ? { subjectId: input.subjectId } : {}), ...(input.kind !== undefined ? { kind: input.kind } : {}), ...(input.status !== undefined ? { status: input.status } : {}), ...(input.credentialEncrypted !== undefined ? { credentialEncrypted: input.credentialEncrypted, version: sql`${schema.connections.version} + 1`, authorityGeneration: sameAccountReconnectGeneration(input), lastError: null, } : {}), ...(input.grantedScopes !== undefined ? { grantedScopes: input.grantedScopes } : {}), ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}), ...(input.verifiedInstallAt !== undefined ? { verifiedInstallAt: input.verifiedInstallAt } : {}), ...(input.verifiedInstallVersion !== undefined ? { verifiedInstallVersion: input.verifiedInstallVersion } : {}), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}), // A credential replaced by a writer that verified no account no longer // vouches for the stored one: it loses the key (and its unique slot). ...(input.accountIdentityKey !== undefined ? { accountIdentityKey: input.accountIdentityKey } : input.credentialEncrypted !== undefined ? { accountIdentityKey: null } : {}), ...(input.label !== undefined ? { label: input.label } : {}), ...(input.updatedBySubjectId !== undefined ? { updatedBySubjectId: input.updatedBySubjectId } : {}), }; const [row] = await db .update(schema.connections) .set(set) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), connectionSubjectVisibility(input.visibleToSubjectId), ...(input.expectedVersion !== undefined ? [eq(schema.connections.version, input.expectedVersion)] : []), ), ) .returning(connectionMetadataColumns) .catch(rethrowAccountIdentityConflict); return row ? mapConnectionMetadata(row) : null; } export async function updateConnection( db: Database, input: UpdateConnectionInput, ): Promise { return await withConnectionSubjectRls( db, input.workspaceId, input.visibleToSubjectId, async (scopedDb) => await updateConnectionInScope(scopedDb, input), ); } async function updateSlackBotDocumentDestinationInScope( db: Database, input: UpdateSlackBotDocumentDestinationInput, ): Promise { const [row] = await db .update(schema.connections) .set({ metadata: input.metadata, version: sql`${schema.connections.version} + 1`, // The install-verification trigger intentionally invalidates proof when // metadata or version changes without a deliberate proof transition. // Carry the proof to the exact new CAS generation in the same statement. verifiedInstallVersion: sql`${schema.connections.version} + 1`, updatedBySubjectId: input.updatedBySubjectId, updatedAt: new Date(), }) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), connectionSubjectVisibility(input.visibleToSubjectId), isNull(schema.connections.subjectId), eq(schema.connections.providerDomain, "slack.com"), eq(schema.connections.kind, "app_install"), eq(schema.connections.version, input.expectedVersion), eq(schema.connections.verifiedInstallVersion, input.expectedVersion), isNotNull(schema.connections.verifiedInstallAt), ), ) .returning(connectionMetadataColumns); return row ? mapConnectionMetadata(row) : null; } /** * Updates only pre-validated workspace Slack-bot destination metadata while * atomically advancing its install proof to the new connection generation. * A stale version or already-invalid proof returns null without writing. */ export async function updateSlackBotDocumentDestination( db: Database, input: UpdateSlackBotDocumentDestinationInput, ): Promise { return await withConnectionSubjectRls( db, input.workspaceId, input.visibleToSubjectId, async (scopedDb) => await updateSlackBotDocumentDestinationInScope(scopedDb, input), ); } async function transitionConnectionStateInScope( db: Database, input: TransitionConnectionStateInput, ): Promise { const [row] = await db .update(schema.connections) .set({ ...(input.status !== undefined ? { status: input.status } : {}), metadata: input.metadata, ...(input.lastError !== undefined ? { lastError: input.lastError } : {}), version: sql`${schema.connections.version} + 1`, ...(input.updatedBySubjectId !== undefined ? { updatedBySubjectId: input.updatedBySubjectId } : {}), updatedAt: new Date(), }) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), connectionSubjectVisibility(input.visibleToSubjectId), eq(schema.connections.version, input.expectedVersion), ), ) .returning(connectionMetadataColumns); return row ? mapConnectionMetadata(row) : null; } /** * Applies a metadata/status lifecycle transition behind the connection's * existing `(id, version)` fence. Unlike ordinary metadata edits, every * transition advances the version so concurrent refresh, disconnect, * reconnect, source-selection, and lifecycle operations cannot overwrite one * another from stale snapshots. */ export async function transitionConnectionState( db: Database, input: TransitionConnectionStateInput, ): Promise { return await withConnectionSubjectRls( db, input.workspaceId, input.visibleToSubjectId, async (scopedDb) => await transitionConnectionStateInScope(scopedDb, input), ); } const connectionDisconnectOperationColumns = { accountId: schema.connectionDisconnectOperations.accountId, workspaceId: schema.connectionDisconnectOperations.workspaceId, connectionId: schema.connectionDisconnectOperations.connectionId, subjectId: schema.connectionDisconnectOperations.subjectId, idempotencyKey: schema.connectionDisconnectOperations.idempotencyKey, expectedVersion: schema.connectionDisconnectOperations.expectedVersion, resultVersion: schema.connectionDisconnectOperations.resultVersion, }; /** * Disconnects one exact subject-owned connection generation and records the * caller's durable operation identity in the same transaction. Exact retries * converge only while the produced generation remains current; a reconnect or * any other later transition fences the old operation permanently. */ export async function disconnectConnectionIdempotently( db: Database, input: DisconnectConnectionIdempotentlyInput, ): Promise { return await withConnectionSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => { const [connectionRow] = await scopedDb .select(connectionMetadataColumns) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), eq(schema.connections.subjectId, input.subjectId), ), ) .for("update"); if (!connectionRow) return null; const connection = mapConnectionMetadata(connectionRow); const [replayed] = await scopedDb .select(connectionDisconnectOperationColumns) .from(schema.connectionDisconnectOperations) .where( and( eq(schema.connectionDisconnectOperations.workspaceId, input.workspaceId), eq(schema.connectionDisconnectOperations.subjectId, input.subjectId), eq(schema.connectionDisconnectOperations.idempotencyKey, input.idempotencyKey), ), ) .limit(1); if (replayed) { if ( replayed.accountId !== input.accountId || replayed.connectionId !== input.connectionId || replayed.expectedVersion !== input.expectedVersion ) { throw new ConnectionDisconnectIdempotencyError(); } if (connection.version !== replayed.resultVersion) { throw new ConnectionDisconnectGenerationError(); } return connection; } if (connection.version !== input.expectedVersion) { throw new ConnectionDisconnectGenerationError(); } const [inserted] = await scopedDb .insert(schema.connectionDisconnectOperations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, subjectId: input.subjectId, idempotencyKey: input.idempotencyKey, expectedVersion: input.expectedVersion, resultVersion: input.expectedVersion + 1, }) .onConflictDoNothing() .returning(connectionDisconnectOperationColumns); if (!inserted) { const [conflictingKey] = await scopedDb .select(connectionDisconnectOperationColumns) .from(schema.connectionDisconnectOperations) .where( and( eq(schema.connectionDisconnectOperations.workspaceId, input.workspaceId), eq(schema.connectionDisconnectOperations.subjectId, input.subjectId), eq(schema.connectionDisconnectOperations.idempotencyKey, input.idempotencyKey), ), ) .limit(1); if ( !conflictingKey || conflictingKey.accountId !== input.accountId || conflictingKey.connectionId !== input.connectionId || conflictingKey.expectedVersion !== input.expectedVersion ) { throw new ConnectionDisconnectIdempotencyError(); } if (connection.version !== conflictingKey.resultVersion) { throw new ConnectionDisconnectGenerationError(); } return connection; } const [updated] = await scopedDb .update(schema.connections) .set({ status: "revoked", metadata: input.metadata, ...(input.lastError !== undefined ? { lastError: input.lastError } : {}), version: sql`${schema.connections.version} + 1`, ...(input.updatedBySubjectId !== undefined ? { updatedBySubjectId: input.updatedBySubjectId } : {}), updatedAt: new Date(), }) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), eq(schema.connections.subjectId, input.subjectId), eq(schema.connections.version, input.expectedVersion), ), ) .returning(connectionMetadataColumns); if (!updated) { throw new ConnectionDisconnectGenerationError(); } const disconnected = mapConnectionMetadata(updated); if (input.audit && connection.status !== "revoked") { await auditConnectionDisconnectInScope(scopedDb, disconnected, input.audit); } return disconnected; }, ); } /** * Record one connection's disconnect (`connection.disconnected`) inside the * transaction that revoked it. Only non-secret facts: the provider domain, * the connection kind, its ownership and its credential role. */ async function auditConnectionDisconnectInScope( tx: Database, connection: ConnectionMetadataWithVerification, actor: DisconnectAuditActor, details: Record = {}, ): Promise { const credentialRole = connection.metadata.credentialRole; await insertDisconnectAuditEventInScope(tx, { accountId: connection.accountId, workspaceId: connection.workspaceId, action: CONNECTION_DISCONNECTED_AUDIT_ACTION, actor, target: { type: "connection", id: connection.id, providerDomain: connection.providerDomain }, details: { connectionKind: connection.kind, ownership: connection.subjectId === null ? "workspace" : "personal", ...(typeof credentialRole === "string" ? { credentialRole } : {}), ...details, }, }); } /** * Revoke one connection and, when `audit` names the actor, record the * disconnect in the same transaction. Only a transition from a live status is * audited: re-revoking an already revoked row records nothing. */ async function revokeConnectionAuditedInScope( db: Database, workspaceId: string, connectionId: string, updatedBySubjectId: string | null | undefined, expectedVersion: number | undefined, audit: DisconnectAuditActor | null | undefined, replacementCredentialEncrypted?: string, ): Promise { if (!audit) { return await revokeConnectionInScope( db, workspaceId, connectionId, updatedBySubjectId, expectedVersion, replacementCredentialEncrypted, ); } const [prior] = await db .select({ status: schema.connections.status }) .from(schema.connections) .where( and( eq(schema.connections.workspaceId, workspaceId), eq(schema.connections.id, connectionId), connectionSubjectVisibility(updatedBySubjectId), ), ) .for("update"); const revoked = await revokeConnectionInScope( db, workspaceId, connectionId, updatedBySubjectId, expectedVersion, replacementCredentialEncrypted, ); if (revoked && prior && prior.status !== "revoked") { await auditConnectionDisconnectInScope(db, revoked, audit); } return revoked; } async function revokeConnectionInScope( db: Database, workspaceId: string, connectionId: string, updatedBySubjectId?: string | null, expectedVersion?: number, /** * When set, the stored credential is replaced in the same write, so the * revoked row no longer holds the provider's tokens (the column is NOT NULL, * so callers pass an encrypted credential without tokens). */ replacementCredentialEncrypted?: string, ): Promise { const [row] = await db .update(schema.connections) .set({ status: "revoked", ...(replacementCredentialEncrypted !== undefined ? { credentialEncrypted: replacementCredentialEncrypted } : {}), // The version bump invalidates any in-flight refresh's (id, version) CAS, // so a racing refresh cannot commit and flip the row back to active. version: sql`${schema.connections.version} + 1`, // Status-only revocation does not replace the verified credential or bot // identity. Carry the marker to the same new CAS version so the dedicated // reinstall path can still recognize (but not use) the inactive row. verifiedInstallVersion: sql`case when ${schema.connections.verifiedInstallAt} is null then null else ${schema.connections.version} + 1 end`, updatedBySubjectId: updatedBySubjectId ?? null, updatedAt: new Date(), }) .where( and( eq(schema.connections.workspaceId, workspaceId), eq(schema.connections.id, connectionId), // Same visibility rule as get/update: shared rows plus the caller's own // subject rows. Cross-subject revocation (admin janitorial) arrives with // the subject-connections UX in I5, deliberately not before. connectionSubjectVisibility(updatedBySubjectId), ...(expectedVersion !== undefined ? [eq(schema.connections.version, expectedVersion)] : []), ), ) .returning(connectionMetadataColumns); return row ? mapConnectionMetadata(row) : null; } export async function revokeConnection( db: Database, workspaceId: string, connectionId: string, updatedBySubjectId?: string | null, expectedVersion?: number, options: { /** A person's, key's or agent's disconnect: audited in the same transaction. */ audit?: DisconnectAuditActor | null; /** * Replaces the stored credential in the same write (for example an * encrypted credential without tokens once the provider grant is revoked). * Omitted: status-only revocation keeps the stored credential. */ replacementCredentialEncrypted?: string | undefined; } = {}, ): Promise { return await withConnectionSubjectRls( db, workspaceId, updatedBySubjectId, async (scopedDb) => await revokeConnectionAuditedInScope( scopedDb, workspaceId, connectionId, updatedBySubjectId, expectedVersion, options.audit, options.replacementCredentialEncrypted, ), ); } export type SlackInstallationRoute = { accountId: string; workspaceId: string; connectionId: string; botId: string; botUserId: string; }; export class SlackInstallationBindingConflictError extends Error { constructor( readonly reason: | "conflicting_workspace" | "conflicting_principal" | "legacy_quarantine" | "stale_reinstall", ) { super( reason === "legacy_quarantine" ? "Slack team has conflicting legacy installations and is quarantined" : reason === "stale_reinstall" ? "Slack installation changed during reinstall; start again" : "Slack team is already bound to a different Opengeni installation", ); this.name = "SlackInstallationBindingConflictError"; } } type SlackInstallationBindingInspection = { outcome: | "available" | "same_binding" | "conflicting_workspace" | "conflicting_principal" | "legacy_quarantine"; connectionId: string | null; connectionVersion: number | null; }; async function inspectSlackInstallationBindingInScope( db: Database, input: { slackTeamId: string; botId: string; botUserId: string }, ): Promise { const [row] = await db.execute<{ outcome: SlackInstallationBindingInspection["outcome"]; connection_id: string | null; connection_version: number | string | null; }>( sql`select * from opengeni_private.inspect_slack_installation_binding( ${input.slackTeamId}, ${input.botId}, ${input.botUserId} )`, ); if (!row) throw new Error("Slack installation binding inspection returned no row"); return { outcome: row.outcome, connectionId: row.connection_id, connectionVersion: row.connection_version == null ? null : Number(row.connection_version), }; } export async function listSlackInstallationBindings( db: Database, input: { accountId: string; workspaceId: string }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .select({ binding: schema.slackInstallationBindings, accountName: schema.managedAccounts.name, workspaceName: schema.workspaces.name, connectionStatus: schema.connections.status, connectionVersion: schema.connections.version, }) .from(schema.slackInstallationBindings) .innerJoin( schema.managedAccounts, eq(schema.managedAccounts.id, schema.slackInstallationBindings.accountId), ) .innerJoin( schema.workspaces, eq(schema.workspaces.id, schema.slackInstallationBindings.workspaceId), ) .innerJoin( schema.connections, eq(schema.connections.id, schema.slackInstallationBindings.connectionId), ) .where(eq(schema.slackInstallationBindings.workspaceId, input.workspaceId)) .orderBy( asc(schema.slackInstallationBindings.state), desc(schema.slackInstallationBindings.updatedAt), desc(schema.slackInstallationBindings.id), ); return rows.map( ({ binding, accountName, workspaceName, connectionStatus, connectionVersion }) => ({ id: binding.id, accountId: binding.accountId, accountName, workspaceId: binding.workspaceId, workspaceName, connectionId: binding.connectionId, connectionStatus: connectionStatus as ConnectionStatus, connectionVersion, slackTeamId: binding.slackTeamId, slackTeamName: binding.slackTeamName, botId: binding.botId, botUserId: binding.botUserId, botDisplayName: binding.botDisplayName as | "Opengeni" | "Opengeni Staging" | "OpenGeni" | "OpenGeni Staging", state: binding.state, quarantineReason: binding.quarantineReason, version: binding.version, createdAt: binding.createdAt.toISOString(), updatedAt: binding.updatedAt.toISOString(), }), ); }); } export type SlackBotUserLink = { id: string; accountId: string; workspaceId: string; connectionId: string; slackTeamId: string; slackUserId: string; subjectId: string; linkedBySubjectId: string; /** * The exact Slack interaction id that durably claimed this identity's * one-time onboarding hint, or `null` when the hint has not been shown. */ firstTaskHintInteractionId: string | null; /** When this person muted occasional update messages about new agents. */ updatesMutedAt: Date | null; createdAt: Date; updatedAt: Date; }; export type SlackInteractionTriggerKind = | "app_mention" | "dm" | "reaction" | "slash_command" | "message_shortcut" | "thread_reply" | "block_action"; export type SlackInteractionInboxEntry = { id: string; accountId: string; workspaceId: string; connectionId: string; providerEventId: string; providerMessageId: string; slackTeamId: string; slackUserId: string; slackChannelId: string; slackMessageTs: string; slackThreadTs: string | null; triggerKind: SlackInteractionTriggerKind; text: string; hasFiles: boolean; status: "pending" | "processing" | "processed" | "failed"; claimHolderId: string | null; claimExpiresAt: Date | null; attemptCount: number; retryAt: Date | null; lastErrorCode: string | null; reactionContextCheckpoint: unknown | null; /** A request passed on to one exact Slack agent by another chat. */ targetSlackAgentId?: string | null; handoffFromInteractionId?: string | null; handoffFromSlackAgentId?: string | null; processedAt: Date | null; createdAt: Date; updatedAt: Date; }; export type SlackAppHomeRefresh = { id: string; accountId: string; workspaceId: string; connectionId: string; slackTeamId: string; slackUserId: string; providerEventId: string; providerViewHash: string | null; desiredRevision: number; processedRevision: number; claimHolderId: string | null; claimExpiresAt: Date | null; attemptCount: number; retryAt: Date | null; lastErrorCode: string | null; createdAt: Date; updatedAt: Date; }; export type SlackInteraction = { id: string; accountId: string; workspaceId: string; connectionId: string; slackTeamId: string; slackChannelId: string; slackThreadTs: string; routeKey: string; triggeringProviderEventId: string; initiatingSlackUserId: string | null; owningSubjectId: string; visibility: "private" | "workspace"; sessionReservationId: string; sessionId: string | null; lastDeliveredSessionEventSequence: number; deliveryClaimHolderId: string | null; deliveryClaimExpiresAt: Date | null; deliveryAttemptCount: number; deliveryRetryAt: Date | null; deliveryLastErrorCode: string | null; ackSlackMessageTs: string | null; /** * Frozen once: whether this interaction's acknowledgement renders the * one-time onboarding hint. `null` means the decision is unresolved. */ firstTaskHint: boolean | null; /** * The routed workspace's name, frozen when the interaction bound. * * Null means "do not say where this went": either routing is off, or the * person had exactly one workspace to begin with, and a constant footer on * every message would be noise. It is frozen rather than looked up at post * time because a rename between the original post and a reconciliation would * make the ledger's byte comparison raise. */ routedWorkspaceLabel: string | null; /** * One line naming what the bound session started with, frozen when the * session bound so an acknowledgement repair renders the same bytes. Null * means no line. No longer written; kept so interactions that already posted * it re-render identically. */ sessionDefaultsLine: string | null; /** * The opening sentence of the task's first Slack message, frozen when the * session binds so every re-render (repair, Stop/Resume, settle) produces the * same bytes for the digest-bound post and update ledgers. * * Also the message-format discriminator: null means the interaction keeps the * format it had before this field existed (Status button, task controls card, * and a workspace line on every message). */ startMessageLine: string | null; /** The Slack agent this chat was started for. Null for plain Opengeni. */ slackAgentId: string | null; /** The agent whose chat passed this thread on, which it never hands back to. */ handoffFromSlackAgentId: string | null; /** The latest Slack message this chat was given, and who sent it. */ lastInboundProviderEventId: string | null; lastInboundSlackUserId: string | null; progressCount: number; terminalDeliveryState: "open" | "completed" | "failed" | "cancelled" | "blocked"; createdAt: Date; updatedAt: Date; }; export type SlackInteractionProgressDelivery = { id: string; accountId: string; workspaceId: string; interactionId: string; sessionEventSequence: number; slot: number; operationId: string; createdAt: Date; }; export type SlackInteractionActionKind = | "approval_approve" | "approval_reject" | "human_input_select" | "human_input_skip" | "session_status" | "session_pause" | "session_resume" | "shared_result_publish"; export type SlackInteractionActionHandle = { id: string; accountId: string; workspaceId: string; connectionId: string; interactionId: string; sessionId: string; sessionEventSequence: number; actionKind: SlackInteractionActionKind; actionKey: string; targetId: string | null; targetValue: string | null; authorizedSubjectId: string; authorizedSlackUserId: string; messageOperationId: string; status: "pending" | "completed" | "stale"; result: string | null; expiresAt: Date; completedAt: Date | null; createdAt: Date; updatedAt: Date; }; export async function resolveSlackInstallationRoute( db: Database, slackTeamId: string, ): Promise { const rows = await db.execute<{ account_id: string; workspace_id: string; connection_id: string; bot_id: string; bot_user_id: string; }>(sql`select * from opengeni_private.resolve_slack_installation(${slackTeamId})`); const row = rows[0]; return row ? { accountId: row.account_id, workspaceId: row.workspace_id, connectionId: row.connection_id, botId: row.bot_id, botUserId: row.bot_user_id, } : null; } export async function saveSlackBotUserLink( db: Database, // The one-time onboarding hint claim is deliberately not writable here: a // re-link of the same Slack identity keeps whatever was already shown. input: Omit< SlackBotUserLink, "id" | "createdAt" | "updatedAt" | "firstTaskHintInteractionId" | "updatesMutedAt" >, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .insert(schema.slackBotUserLinks) .values(input) .onConflictDoUpdate({ target: [schema.slackBotUserLinks.connectionId, schema.slackBotUserLinks.slackUserId], set: { accountId: input.accountId, workspaceId: input.workspaceId, slackTeamId: input.slackTeamId, subjectId: input.subjectId, linkedBySubjectId: input.linkedBySubjectId, updatedAt: sql`now()`, }, }) .returning(); if (!row) throw new Error("Slack identity link write returned no row"); return mapSlackBotUserLink(row); }); } export async function getSlackBotUserLink( db: Database, workspaceId: string, connectionId: string, slackUserId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackBotUserLinks) .where( and( eq(schema.slackBotUserLinks.workspaceId, workspaceId), eq(schema.slackBotUserLinks.connectionId, connectionId), eq(schema.slackBotUserLinks.slackUserId, slackUserId), ), ) .limit(1); return row ? mapSlackBotUserLink(row) : null; }); } /** * Resolve, exactly once, whether one Slack interaction's acknowledgement * renders the one-time onboarding hint, and freeze that answer on the * interaction row. * * `slack_bot_post_operations` binds one operation id to one request digest that * covers the message text, so an acknowledgement re-rendered after a crash, a * lost provider response, or a replica race must produce the same bytes or the * ledger rejects it. Rendering therefore reads a frozen fact instead of asking * a mutable question: the first call decides, every later call replays the * stored decision, and unlinking plus relinking the Slack identity cannot flip * an acknowledgement that was already rendered. * * The per-identity claim row is the single source of truth and is replay-stable: * the frozen answer is exactly "this identity's one claim names THIS * interaction". At most one interaction per Slack identity per installation is * therefore granted the hint, whichever resolver wins the claim, and the freeze * is a separate compare-and-set whose losers read back the stored byte rather * than their own recomputed one. This is deliberately not one transaction: the * claim is a home-tenancy row and the freeze is a target-tenancy row, and one * transaction carries one RLS scope. Failure raises instead of degrading to "no * hint": a caller must never bind a post operation to text that depends on an * unresolved answer. */ export async function resolveSlackInteractionFirstTaskHint( db: Database, input: { /** HOME: the installation workspace that owns the identity link. */ workspaceId: string; connectionId: string; slackUserId: string; interactionId: string; /** * TARGET: the workspace that owns the interaction row. Defaults to HOME, * which is what every caller means until routing exists. */ interactionWorkspaceId?: string; }, ): Promise { const identityWorkspaceId = input.workspaceId; const interactionWorkspaceId = input.interactionWorkspaceId ?? input.workspaceId; // `slack_bot_user_links` is a HOME row and `slack_interactions` is a TARGET // row. One transaction carries one RLS scope, so this cannot be a single // scoped transaction once the two differ. It does not need to be: the // per-identity claim is itself the source of truth, and it is replay-stable. // // The frozen answer is `the identity's one claim names THIS interaction`. Two // resolvers of the same interaction therefore always agree, whichever wins the // claim; two resolvers of different interactions elect exactly one winner; and // a crash between the claim and the freeze re-derives the same answer on the // next call. Failure still raises rather than degrading to "no hint": a caller // must never bind a post operation to text that depends on an unresolved // answer. const frozen = await withWorkspaceRls(db, interactionWorkspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ firstTaskHint: schema.slackInteractions.firstTaskHint }) .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.workspaceId, interactionWorkspaceId), eq(schema.slackInteractions.id, input.interactionId), ), ) .limit(1); if (!row) throw new Error("Slack first-task hint requires a durable interaction row"); return row.firstTaskHint; }); if (frozen !== null) return frozen; const granted = await withWorkspaceRls(db, identityWorkspaceId, async (scopedDb) => { const claimed = await scopedDb .update(schema.slackBotUserLinks) .set({ firstTaskHintInteractionId: input.interactionId }) .where( and( eq(schema.slackBotUserLinks.workspaceId, identityWorkspaceId), eq(schema.slackBotUserLinks.connectionId, input.connectionId), eq(schema.slackBotUserLinks.slackUserId, input.slackUserId), isNull(schema.slackBotUserLinks.firstTaskHintInteractionId), ), ) .returning({ id: schema.slackBotUserLinks.id }); if (claimed.length > 0) return true; // Lost the claim, or replaying after a crash between the claim and the // freeze. The claim itself says which it was. const [existing] = await scopedDb .select({ firstTaskHintInteractionId: schema.slackBotUserLinks.firstTaskHintInteractionId, }) .from(schema.slackBotUserLinks) .where( and( eq(schema.slackBotUserLinks.workspaceId, identityWorkspaceId), eq(schema.slackBotUserLinks.connectionId, input.connectionId), eq(schema.slackBotUserLinks.slackUserId, input.slackUserId), ), ) .limit(1); return existing?.firstTaskHintInteractionId === input.interactionId; }); return await withWorkspaceRls(db, interactionWorkspaceId, async (scopedDb) => { const [written] = await scopedDb .update(schema.slackInteractions) .set({ firstTaskHint: granted, updatedAt: sql`now()` }) .where( and( eq(schema.slackInteractions.workspaceId, interactionWorkspaceId), eq(schema.slackInteractions.id, input.interactionId), isNull(schema.slackInteractions.firstTaskHint), ), ) .returning({ firstTaskHint: schema.slackInteractions.firstTaskHint }); if (written) return written.firstTaskHint ?? granted; // Another resolver of this exact interaction froze first. It computed the // same predicate, but return the stored byte rather than a recomputed one so // the digest-bound post ledger can never see two answers. const [current] = await scopedDb .select({ firstTaskHint: schema.slackInteractions.firstTaskHint }) .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.workspaceId, interactionWorkspaceId), eq(schema.slackInteractions.id, input.interactionId), ), ) .limit(1); if (!current) throw new Error("Slack first-task hint requires a durable interaction row"); return current.firstTaskHint ?? granted; }); } export async function deleteSlackBotUserLink( db: Database, workspaceId: string, connectionId: string, slackUserId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .delete(schema.slackBotUserLinks) .where( and( eq(schema.slackBotUserLinks.workspaceId, workspaceId), eq(schema.slackBotUserLinks.connectionId, connectionId), eq(schema.slackBotUserLinks.slackUserId, slackUserId), ), ) .returning({ id: schema.slackBotUserLinks.id }); return rows.length > 0; }); } export async function enqueueSlackAppHomeRefresh( db: Database, input: Pick< SlackAppHomeRefresh, | "accountId" | "workspaceId" | "connectionId" | "slackTeamId" | "slackUserId" | "providerEventId" | "providerViewHash" >, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .insert(schema.slackAppHomeRefreshes) .values(input) .onConflictDoUpdate({ target: [ schema.slackAppHomeRefreshes.connectionId, schema.slackAppHomeRefreshes.slackUserId, ], set: { accountId: input.accountId, workspaceId: input.workspaceId, slackTeamId: input.slackTeamId, providerEventId: input.providerEventId, providerViewHash: input.providerViewHash, desiredRevision: sql`case when ${schema.slackAppHomeRefreshes.providerEventId} = excluded.provider_event_id then ${schema.slackAppHomeRefreshes.desiredRevision} else ${schema.slackAppHomeRefreshes.desiredRevision} + 1 end`, retryAt: sql`case when ${schema.slackAppHomeRefreshes.providerEventId} = excluded.provider_event_id then ${schema.slackAppHomeRefreshes.retryAt} else null end`, lastErrorCode: sql`case when ${schema.slackAppHomeRefreshes.providerEventId} = excluded.provider_event_id then ${schema.slackAppHomeRefreshes.lastErrorCode} else null end`, updatedAt: sql`now()`, }, }) .returning(); if (!row) throw new Error("Slack App Home refresh write returned no row"); return mapSlackAppHomeRefresh(row); }); } export async function claimSlackAppHomeRefresh( db: Database, claimHolderId: string, claimLeaseMs: number, ): Promise { const rows = await db.execute( sql`select * from opengeni_private.claim_slack_app_home_refresh(${claimHolderId}::uuid, ${claimLeaseMs})`, ); return rows[0] ? mapSlackAppHomeRefresh(rows[0]) : null; } export async function renewSlackAppHomeRefreshClaim( db: Database, input: { refresh: Pick; claimHolderId: string; claimLeaseMs: number; }, ): Promise { if (input.claimLeaseMs < 1_000 || input.claimLeaseMs > 300_000) { throw new Error("invalid Slack App Home claim lease"); } return await withRlsContext(db, input.refresh, async (scopedDb) => { const rows = await scopedDb .update(schema.slackAppHomeRefreshes) .set({ claimExpiresAt: sql`now() + make_interval(secs => ${input.claimLeaseMs}::double precision / 1000)`, }) .where( and( eq(schema.slackAppHomeRefreshes.id, input.refresh.id), eq(schema.slackAppHomeRefreshes.claimHolderId, input.claimHolderId), gt(schema.slackAppHomeRefreshes.claimExpiresAt, sql`now()`), ), ) .returning({ id: schema.slackAppHomeRefreshes.id }); return rows.length === 1; }); } export async function settleSlackAppHomeRefresh( db: Database, input: { refresh: Pick; claimHolderId: string; errorCode?: string | null; }, ): Promise { return await withRlsContext(db, input.refresh, async (scopedDb) => { const rows = await scopedDb .update(schema.slackAppHomeRefreshes) .set({ processedRevision: input.refresh.desiredRevision, claimHolderId: null, claimExpiresAt: null, retryAt: null, attemptCount: 0, lastErrorCode: input.errorCode?.slice(0, 128) ?? null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackAppHomeRefreshes.id, input.refresh.id), eq(schema.slackAppHomeRefreshes.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackAppHomeRefreshes.id }); return rows.length === 1; }); } export async function releaseSlackAppHomeRefresh( db: Database, input: { refresh: Pick; claimHolderId: string; errorCode: string; retryAt: Date; }, ): Promise { return await withRlsContext(db, input.refresh, async (scopedDb) => { const rows = await scopedDb .update(schema.slackAppHomeRefreshes) .set({ claimHolderId: null, claimExpiresAt: null, retryAt: sql`case when ${schema.slackAppHomeRefreshes.desiredRevision} > ${input.refresh.desiredRevision} then null else ${input.retryAt.toISOString()}::timestamptz end`, attemptCount: sql`case when ${schema.slackAppHomeRefreshes.desiredRevision} > ${input.refresh.desiredRevision} then 0 else ${schema.slackAppHomeRefreshes.attemptCount} end`, lastErrorCode: sql`case when ${schema.slackAppHomeRefreshes.desiredRevision} > ${input.refresh.desiredRevision} then null else ${input.errorCode.slice(0, 128)} end`, updatedAt: sql`now()`, }) .where( and( eq(schema.slackAppHomeRefreshes.id, input.refresh.id), eq(schema.slackAppHomeRefreshes.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackAppHomeRefreshes.id }); return rows.length === 1; }); } export async function enqueueSlackInteractionInbox( db: Database, input: Omit< SlackInteractionInboxEntry, | "id" | "status" | "claimHolderId" | "claimExpiresAt" | "attemptCount" | "retryAt" | "lastErrorCode" | "reactionContextCheckpoint" | "processedAt" | "createdAt" | "updatedAt" >, ): Promise<{ inserted: boolean; entry: SlackInteractionInboxEntry }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [created] = await scopedDb .insert(schema.slackInteractionInbox) .values(input) .onConflictDoNothing() .returning(); if (created) return { inserted: true, entry: mapSlackInteractionInbox(created) }; const [existing] = await scopedDb .select() .from(schema.slackInteractionInbox) .where( and( eq(schema.slackInteractionInbox.connectionId, input.connectionId), or( eq(schema.slackInteractionInbox.providerEventId, input.providerEventId), eq(schema.slackInteractionInbox.providerMessageId, input.providerMessageId), ), ), ) .limit(1); if (!existing) throw new Error("Slack inbox idempotency conflict could not be resolved"); return { inserted: false, entry: mapSlackInteractionInbox(existing) }; }, ); } export async function claimSlackInteractionInbox( db: Database, claimHolderId: string, claimLeaseMs: number, ): Promise { const rows = await db.execute( sql`select * from opengeni_private.claim_slack_interaction_inbox(${claimHolderId}::uuid, ${claimLeaseMs})`, ); return rows[0] ? mapSlackInteractionInbox(rows[0]) : null; } export async function settleSlackInteractionInbox( db: Database, input: { entry: Pick; claimHolderId: string; outcome: "processed" | "failed"; errorCode?: string | null; }, ): Promise { return await withRlsContext(db, input.entry, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractionInbox) .set({ status: input.outcome, claimHolderId: null, claimExpiresAt: null, retryAt: null, reactionContextCheckpoint: null, processedAt: sql`now()`, lastErrorCode: input.errorCode ?? null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractionInbox.id, input.entry.id), eq(schema.slackInteractionInbox.claimHolderId, input.claimHolderId), eq(schema.slackInteractionInbox.status, "processing"), ), ) .returning({ id: schema.slackInteractionInbox.id }); return rows.length === 1; }); } export async function saveSlackInteractionInboxReactionCheckpoint( db: Database, input: { entry: Pick< SlackInteractionInboxEntry, "id" | "accountId" | "workspaceId" | "connectionId" | "providerEventId" | "providerMessageId" >; claimHolderId: string; checkpoint: unknown; }, ): Promise { return await withRlsContext(db, input.entry, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractionInbox) .set({ reactionContextCheckpoint: input.checkpoint, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractionInbox.id, input.entry.id), eq(schema.slackInteractionInbox.accountId, input.entry.accountId), eq(schema.slackInteractionInbox.workspaceId, input.entry.workspaceId), eq(schema.slackInteractionInbox.connectionId, input.entry.connectionId), eq(schema.slackInteractionInbox.providerEventId, input.entry.providerEventId), eq(schema.slackInteractionInbox.providerMessageId, input.entry.providerMessageId), eq(schema.slackInteractionInbox.triggerKind, "reaction"), eq(schema.slackInteractionInbox.claimHolderId, input.claimHolderId), eq(schema.slackInteractionInbox.status, "processing"), ), ) .returning({ id: schema.slackInteractionInbox.id }); return rows.length === 1; }); } export async function releaseSlackInteractionInbox( db: Database, input: { entry: Pick; claimHolderId: string; errorCode: string; retryAt: Date; }, ): Promise { return await withRlsContext(db, input.entry, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractionInbox) .set({ status: "pending", claimHolderId: null, claimExpiresAt: null, retryAt: input.retryAt, lastErrorCode: input.errorCode, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractionInbox.id, input.entry.id), eq(schema.slackInteractionInbox.claimHolderId, input.claimHolderId), eq(schema.slackInteractionInbox.status, "processing"), ), ) .returning({ id: schema.slackInteractionInbox.id }); return rows.length === 1; }); } export async function getOrCreateSlackInteraction( db: Database, input: Omit< SlackInteraction, | "id" | "initiatingSlackUserId" | "sessionReservationId" | "sessionId" | "lastDeliveredSessionEventSequence" | "deliveryClaimHolderId" | "deliveryClaimExpiresAt" | "deliveryAttemptCount" | "deliveryRetryAt" | "deliveryLastErrorCode" | "ackSlackMessageTs" // Owned by `resolveSlackInteractionFirstTaskHint`, never by the creator. | "firstTaskHint" | "routedWorkspaceLabel" // Owned by `bindSlackInteractionSession`, frozen with the bound session. | "sessionDefaultsLine" | "startMessageLine" | "slackAgentId" | "handoffFromSlackAgentId" | "lastInboundProviderEventId" | "lastInboundSlackUserId" | "progressCount" | "terminalDeliveryState" | "createdAt" | "updatedAt" > & { initiatingSlackUserId?: string | null; routedWorkspaceLabel?: string | null; slackAgentId?: string | null; handoffFromSlackAgentId?: string | null; }, ): Promise<{ created: boolean; interaction: SlackInteraction }> { const outcome = await withRlsContext(db, input, async (scopedDb) => { const [created] = await scopedDb .insert(schema.slackInteractions) .values({ ...input, initiatingSlackUserId: input.initiatingSlackUserId ?? null, routedWorkspaceLabel: input.routedWorkspaceLabel ?? null, slackAgentId: input.slackAgentId ?? null, handoffFromSlackAgentId: input.handoffFromSlackAgentId ?? null, }) .onConflictDoNothing() .returning(); if (created) { return { created: true, interaction: mapSlackInteraction(created), } as const; } const [existing] = await scopedDb .select() .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.connectionId, input.connectionId), eq(schema.slackInteractions.routeKey, input.routeKey), ), ) .limit(1); return existing ? ({ created: false, interaction: mapSlackInteraction(existing), } as const) : ({ created: false, interaction: null } as const); }); if (outcome.interaction) { return { created: outcome.created, interaction: outcome.interaction }; } // The route unique index is connection-global while the recovery SELECT above // runs under the intended tenancy. A thread that already belongs to another // workspace in this organization therefore conflicts without being visible // here. Re-probe the connection-global route and adopt the existing row's // tenancy: a mapped thread keeps the workspace it was created in. const probed = await probeSlackInteractionTenancy(db, { accountId: input.accountId, connectionId: input.connectionId, routeKey: input.routeKey, }); const adopted = probed ? await getSlackInteractionById(db, { accountId: probed.accountId, workspaceId: probed.workspaceId, interactionId: probed.interactionId, }) : null; if (!adopted) throw new Error("Slack route idempotency conflict could not be resolved"); return { created: false, interaction: adopted }; } /** * Connection-scoped thread continuation. `slack_interactions_route_uq` is * `(connection_id, route_key)`, so one Slack thread maps to exactly one * interaction across every workspace this installation can address. The * content-free tenancy probe resolves which workspace that is; the full row is * then read under that workspace's own RLS scope, so nothing is widened. * * `accountId` is the organization the caller is acting for, and the probe is * fenced on it: crossing workspaces within one organization is the whole point, * crossing organizations never is. */ export async function getSlackInteractionByConnectionRoute( db: Database, input: { accountId: string; connectionId: string; routeKey: string }, ): Promise { const probed = await probeSlackInteractionTenancy(db, input); if (!probed) return null; return await getSlackInteractionById(db, { accountId: probed.accountId, workspaceId: probed.workspaceId, interactionId: probed.interactionId, }); } /** * Workspace-fenced route lookup. * * This is NOT the thread-continuation read: `slack_interactions_route_uq` is * `(connection_id, route_key)` and therefore connection-global, so a thread that * belongs to another workspace this installation can address is invisible here. * Use `getSlackInteractionByConnectionRoute` for continuation. */ export async function getSlackInteractionByRoute( db: Database, workspaceId: string, connectionId: string, routeKey: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.workspaceId, workspaceId), eq(schema.slackInteractions.connectionId, connectionId), eq(schema.slackInteractions.routeKey, routeKey), ), ) .limit(1); return row ? mapSlackInteraction(row) : null; }); } export async function getSlackInteractionById( db: Database, input: { accountId: string; workspaceId: string; interactionId: string }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), eq(schema.slackInteractions.id, input.interactionId), ), ) .limit(1); return row ? mapSlackInteraction(row) : null; }); } export async function reserveSlackInteractionActionHandles( db: Database, input: { interaction: Pick< SlackInteraction, | "id" | "accountId" | "workspaceId" | "connectionId" | "sessionId" | "owningSubjectId" | "initiatingSlackUserId" >; sessionEventSequence: number; messageOperationId: string; expiresAt: Date; actions: Array<{ actionKind: SlackInteractionActionKind; actionKey: string; targetId?: string | null; targetValue?: string | null; }>; }, ): Promise { if ( !input.interaction.sessionId || !input.interaction.initiatingSlackUserId || !Number.isSafeInteger(input.sessionEventSequence) || input.sessionEventSequence < 0 || input.actions.length < 1 || input.actions.length > 25 ) { throw new RangeError("invalid Slack action handle reservation"); } const sessionId = input.interaction.sessionId; const initiatingSlackUserId = input.interaction.initiatingSlackUserId; if (!sessionId || !initiatingSlackUserId) { throw new RangeError("Slack action handle reservation requires a bound requester"); } return await withRlsContext( db, input.interaction, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [interaction] = await tx .select() .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.accountId, input.interaction.accountId), eq(schema.slackInteractions.workspaceId, input.interaction.workspaceId), eq(schema.slackInteractions.id, input.interaction.id), ), ) .for("update") .limit(1); if ( !interaction || interaction.connectionId !== input.interaction.connectionId || interaction.sessionId !== input.interaction.sessionId || interaction.owningSubjectId !== input.interaction.owningSubjectId || interaction.initiatingSlackUserId !== input.interaction.initiatingSlackUserId ) { throw new Error("Slack interaction action authority changed"); } for (const action of input.actions) { await tx .insert(schema.slackInteractionActionHandles) .values({ accountId: input.interaction.accountId, workspaceId: input.interaction.workspaceId, connectionId: input.interaction.connectionId, interactionId: input.interaction.id, sessionId, sessionEventSequence: input.sessionEventSequence, actionKind: action.actionKind, actionKey: action.actionKey, targetId: action.targetId ?? null, targetValue: action.targetValue ?? null, authorizedSubjectId: input.interaction.owningSubjectId, authorizedSlackUserId: initiatingSlackUserId, messageOperationId: input.messageOperationId, expiresAt: input.expiresAt, }) .onConflictDoNothing({ target: [ schema.slackInteractionActionHandles.interactionId, schema.slackInteractionActionHandles.sessionEventSequence, schema.slackInteractionActionHandles.actionKey, ], }); } const rows = await tx .select() .from(schema.slackInteractionActionHandles) .where( and( eq(schema.slackInteractionActionHandles.interactionId, input.interaction.id), eq( schema.slackInteractionActionHandles.sessionEventSequence, input.sessionEventSequence, ), inArray( schema.slackInteractionActionHandles.actionKey, input.actions.map((action) => action.actionKey), ), ), ); const byKey = new Map(rows.map((row) => [row.actionKey, row])); return input.actions.map((action) => { const row = byKey.get(action.actionKey); if ( !row || row.actionKind !== action.actionKind || row.targetId !== (action.targetId ?? null) || row.targetValue !== (action.targetValue ?? null) || row.messageOperationId !== input.messageOperationId ) { throw new Error("Slack action handle identity conflict"); } return mapSlackInteractionActionHandle(row); }); }), ); } export async function getSlackInteractionActionHandle( db: Database, input: { accountId: string; workspaceId: string; handleId: string }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackInteractionActionHandles) .where( and( eq(schema.slackInteractionActionHandles.accountId, input.accountId), eq(schema.slackInteractionActionHandles.workspaceId, input.workspaceId), eq(schema.slackInteractionActionHandles.id, input.handleId), ), ) .limit(1); return row ? mapSlackInteractionActionHandle(row) : null; }); } /** * The still-pending handles one interaction rendered on one exact message, * oldest first. The message is identified by the post operation that created * it, which is what every handle on it carries as `messageOperationId`. */ export async function listPendingSlackInteractionMessageActionHandles( db: Database, input: { accountId: string; workspaceId: string; interactionId: string; messageOperationId: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.slackInteractionActionHandles) .where( and( eq(schema.slackInteractionActionHandles.accountId, input.accountId), eq(schema.slackInteractionActionHandles.workspaceId, input.workspaceId), eq(schema.slackInteractionActionHandles.interactionId, input.interactionId), eq(schema.slackInteractionActionHandles.messageOperationId, input.messageOperationId), eq(schema.slackInteractionActionHandles.status, "pending"), ), ) .orderBy( asc(schema.slackInteractionActionHandles.createdAt), asc(schema.slackInteractionActionHandles.id), ); return rows.map(mapSlackInteractionActionHandle); }); } export async function settleSlackInteractionActionHandles( db: Database, input: { accountId: string; workspaceId: string; handleId: string; result: string; stale?: boolean; /** * Settle every other pending handle rendered on the same message as * superseded (the default: one card, one decision). A message whose single * button is replaced in place by a freshly reserved one (Stop becoming * Resume) passes false, so the replacement stays pending. */ supersedeSiblings?: boolean; }, ): Promise { return await withRlsContext( db, input, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [current] = await tx .select() .from(schema.slackInteractionActionHandles) .where( and( eq(schema.slackInteractionActionHandles.accountId, input.accountId), eq(schema.slackInteractionActionHandles.workspaceId, input.workspaceId), eq(schema.slackInteractionActionHandles.id, input.handleId), ), ) .for("update") .limit(1); if (!current) return null; if (current.status === "pending") { if (input.supersedeSiblings !== false) { await tx .update(schema.slackInteractionActionHandles) .set({ status: "stale", result: "superseded", completedAt: sql`now()`, updatedAt: sql`now()`, }) .where( and( eq( schema.slackInteractionActionHandles.messageOperationId, current.messageOperationId, ), eq(schema.slackInteractionActionHandles.status, "pending"), ), ); } const [settled] = await tx .update(schema.slackInteractionActionHandles) .set({ status: input.stale ? "stale" : "completed", result: input.result.slice(0, 64), completedAt: sql`now()`, updatedAt: sql`now()`, }) .where(eq(schema.slackInteractionActionHandles.id, current.id)) .returning(); return settled ? mapSlackInteractionActionHandle(settled) : null; } return mapSlackInteractionActionHandle(current); }), ); } /** * Resolve an already-durable Slack task to its canonical interaction. * * Client event ids are unique only inside one session, so this lookup also * fences the exact workspace and Slack connection. The reservation id is the * canonical Slack session identity both before and after binding; joining it * lets a retry repair a crash after the task committed but before the route was * bound. Two matches indicate a cross-session collision and fail closed rather * than choosing an arbitrary route. */ export async function getSlackInteractionByClientEventId( db: Database, workspaceId: string, connectionId: string, clientEventId: string, ): Promise<{ interaction: SlackInteraction; eventSessionId: string } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ interaction: schema.slackInteractions, eventSessionId: schema.sessionEvents.sessionId, }) .from(schema.slackInteractions) .innerJoin( schema.sessionEvents, and( eq(schema.sessionEvents.workspaceId, schema.slackInteractions.workspaceId), eq(schema.sessionEvents.sessionId, schema.slackInteractions.sessionReservationId), ), ) .where( and( eq(schema.slackInteractions.workspaceId, workspaceId), eq(schema.slackInteractions.connectionId, connectionId), eq(schema.sessionEvents.clientEventId, clientEventId), eq(schema.sessionEvents.type, "user.message"), ), ) .limit(2); if (rows.length > 1) { throw new Error("Slack client event id resolved to multiple canonical interactions"); } const row = rows[0]; if (!row) return null; return { interaction: mapSlackInteraction(row.interaction), eventSessionId: row.eventSessionId, }; }); } /** Exact bound session only: a child never inherits its root's Slack destination. */ export async function getSlackInteractionForSession( db: Database, input: { accountId: string; workspaceId: string; sessionId: string }, ): Promise { return await withRlsContext(db, input, async (tx) => { const [row] = await tx .select({ interaction: schema.slackInteractions }) .from(schema.slackInteractions) .innerJoin( schema.sessions, and( eq(schema.sessions.accountId, schema.slackInteractions.accountId), eq(schema.sessions.workspaceId, schema.slackInteractions.workspaceId), eq(schema.sessions.id, schema.slackInteractions.sessionId), ), ) .where( and( eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), eq(schema.slackInteractions.sessionId, input.sessionId), sql`( ${schema.slackInteractions.visibility} <> 'private' or nullif(current_setting('opengeni.subject_id', true), '') is null or ${schema.slackInteractions.owningSubjectId} = nullif(current_setting('opengeni.subject_id', true), '') or ${schema.slackInteractions.owningSubjectId} = nullif(current_setting('opengeni.initiating_human_subject_id', true), '') )`, ), ) .limit(1); return row ? mapSlackInteraction(row.interaction) : null; }); } export async function getSlackInteractionSessionAccess( db: Database, workspaceId: string, rootSessionId: string, ): Promise | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ owningSubjectId: schema.slackInteractions.owningSubjectId, visibility: schema.slackInteractions.visibility, }) .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.workspaceId, workspaceId), eq(schema.slackInteractions.sessionReservationId, rootSessionId), ), ) .limit(1); return row ?? null; }); } /** * The person a private Slack interaction (a bot DM or a private handoff) * reserved this session's root for, or null. Session authorization fences such * a session to that person, so the files it produces belong to them alone, as * an Only-me session's do. A session that does not exist yet is its own root, * which covers a Slack session that is about to be created on its reservation. */ export async function getSlackPrivateSessionOwnerSubjectId( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ owning_subject_id: string }>( scopedDb, sql` select slack.owning_subject_id from ${schema.slackInteractions} slack where slack.workspace_id = ${workspaceId} and slack.visibility = 'private' and slack.session_reservation_id = coalesce( ( select session.root_session_id from ${schema.sessions} session where session.workspace_id = ${workspaceId} and session.id = ${sessionId}::uuid ), ${sessionId}::uuid ) limit 1 `, ); return row?.owning_subject_id ?? null; }); } export async function bindSlackInteractionSession( db: Database, input: Pick & { sessionId: string; /** * Written only by the bind that wins; a replayed bind of the same session * returns the line the first bind froze and never rewrites it. */ startMessageLine?: string | null; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .update(schema.slackInteractions) .set({ sessionId: input.sessionId, startMessageLine: input.startMessageLine ?? null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.owningSubjectId, input.owningSubjectId), eq(schema.slackInteractions.sessionReservationId, input.sessionId), isNull(schema.slackInteractions.sessionId), ), ) .returning(); if (row) return mapSlackInteraction(row); const [existing] = await scopedDb .select() .from(schema.slackInteractions) .where(eq(schema.slackInteractions.id, input.id)) .limit(1); return existing?.sessionId === input.sessionId ? mapSlackInteraction(existing) : null; }); } export type SlackInteractionProgressClaim = | { kind: "claimed"; created: boolean; progressCount: number; delivery: SlackInteractionProgressDelivery; } | { kind: "limit_reached"; progressCount: number } | { kind: "not_owned" }; export type SlackInteractionProgressDeliveryEvidence = { sessionEventSequence: number; operationId: string; text: string; turnId: string | null; }; /** * Read the at-most-three durable progress identities for terminal-delivery * reconciliation. A reserved operation may still be provider-started after a * response loss, so callers must retry the same operation id rather than * inventing a second final post. */ export async function listSlackInteractionProgressDeliveryEvidence( db: Database, input: { accountId: string; workspaceId: string; interactionId: string; sessionId: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .select({ sessionEventSequence: schema.slackInteractionProgressDeliveries.sessionEventSequence, operationId: schema.slackInteractionProgressDeliveries.operationId, payload: schema.sessionEvents.payload, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, turnId: schema.sessionEvents.turnId, }) .from(schema.slackInteractionProgressDeliveries) .innerJoin( schema.sessionEvents, and( eq( schema.sessionEvents.workspaceId, schema.slackInteractionProgressDeliveries.workspaceId, ), eq(schema.sessionEvents.sessionId, input.sessionId), eq( schema.sessionEvents.sequence, schema.slackInteractionProgressDeliveries.sessionEventSequence, ), ), ) .where( and( eq(schema.slackInteractionProgressDeliveries.accountId, input.accountId), eq(schema.slackInteractionProgressDeliveries.workspaceId, input.workspaceId), eq(schema.slackInteractionProgressDeliveries.interactionId, input.interactionId), eq(schema.sessionEvents.type, "agent.message.completed"), or( isNull(schema.sessionEvents.turnAssociation), eq(schema.sessionEvents.turnAssociation, "current"), ), isNull(schema.sessionEvents.duplicateOfEventId), ), ) .orderBy(desc(schema.slackInteractionProgressDeliveries.sessionEventSequence)) .limit(3); return rows.map((row) => { const payload = fromPostgresLosslessJson(row.payload, row.payloadCodecVersion); const text = payload && typeof payload === "object" && !Array.isArray(payload) ? (payload as Record).text : null; return { sessionEventSequence: row.sessionEventSequence, operationId: row.operationId, text: typeof text === "string" ? text : "", turnId: row.turnId, }; }); }); } /** * Reserve one globally bounded progress slot before any Slack provider call. * The interaction row lock serializes replicas and expired delivery claim * successors; the event row preserves one operation UUID across every retry. */ export async function claimSlackInteractionProgressDelivery( db: Database, input: { accountId: string; workspaceId: string; interactionId: string; claimHolderId: string; sessionEventSequence: number; maxProgress: number; }, ): Promise { if ( !Number.isSafeInteger(input.sessionEventSequence) || input.sessionEventSequence < 1 || !Number.isSafeInteger(input.maxProgress) || input.maxProgress < 1 || input.maxProgress > 3 ) { throw new RangeError("invalid Slack progress delivery claim bounds"); } return await withRlsContext(db, input, async (scopedDb) => { const [interaction] = await scopedDb .select({ progressCount: schema.slackInteractions.progressCount, deliveryClaimHolderId: schema.slackInteractions.deliveryClaimHolderId, terminalDeliveryState: schema.slackInteractions.terminalDeliveryState, }) .from(schema.slackInteractions) .where( and( eq(schema.slackInteractions.id, input.interactionId), eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), ), ) .for("update") .limit(1); if ( !interaction || interaction.deliveryClaimHolderId !== input.claimHolderId || interaction.terminalDeliveryState !== "open" ) { return { kind: "not_owned" }; } const [existing] = await scopedDb .select() .from(schema.slackInteractionProgressDeliveries) .where( and( eq(schema.slackInteractionProgressDeliveries.interactionId, input.interactionId), eq( schema.slackInteractionProgressDeliveries.sessionEventSequence, input.sessionEventSequence, ), ), ) .limit(1); if (existing) { return { kind: "claimed", created: false, progressCount: interaction.progressCount, delivery: mapSlackInteractionProgressDelivery(existing), }; } if (interaction.progressCount >= input.maxProgress) { return { kind: "limit_reached", progressCount: interaction.progressCount, }; } const slot = interaction.progressCount + 1; const [delivery] = await scopedDb .insert(schema.slackInteractionProgressDeliveries) .values({ accountId: input.accountId, workspaceId: input.workspaceId, interactionId: input.interactionId, sessionEventSequence: input.sessionEventSequence, slot, operationId: crypto.randomUUID(), }) .returning(); if (!delivery) throw new Error("Slack progress delivery claim returned no row"); const [updated] = await scopedDb .update(schema.slackInteractions) .set({ progressCount: slot, updatedAt: sql`now()` }) .where( and( eq(schema.slackInteractions.id, input.interactionId), eq(schema.slackInteractions.deliveryClaimHolderId, input.claimHolderId), eq(schema.slackInteractions.progressCount, interaction.progressCount), ), ) .returning({ progressCount: schema.slackInteractions.progressCount }); if (!updated) throw new Error("Slack progress delivery lost its durable interaction claim"); return { kind: "claimed", created: true, progressCount: updated.progressCount, delivery: mapSlackInteractionProgressDelivery(delivery), }; }); } export async function rekeySlackInteractionRoute( db: Database, input: Pick & { routeKey: string; slackChannelId?: string; slackThreadTs: string; ackSlackMessageTs: string; repairUnacknowledgedPrivateShortcutDelivery?: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const repairableDelivery = sql`( ${schema.slackInteractions.ackSlackMessageTs} is null and ${schema.slackInteractions.visibility} = 'private' and ${schema.slackInteractions.triggeringProviderEventId} like 'shortcut:%' and ${schema.slackInteractions.terminalDeliveryState} = 'failed' and ${schema.slackInteractions.deliveryLastErrorCode} in ('channel_not_found', 'not_in_channel') )`; const [row] = await scopedDb .update(schema.slackInteractions) .set({ routeKey: input.routeKey, ...(input.slackChannelId ? { slackChannelId: input.slackChannelId } : {}), slackThreadTs: input.slackThreadTs, ackSlackMessageTs: input.ackSlackMessageTs, ...(input.repairUnacknowledgedPrivateShortcutDelivery ? { terminalDeliveryState: sql`case when ${repairableDelivery} then 'open' else ${schema.slackInteractions.terminalDeliveryState} end`, deliveryClaimHolderId: sql`case when ${repairableDelivery} then null else ${schema.slackInteractions.deliveryClaimHolderId} end`, deliveryClaimExpiresAt: sql`case when ${repairableDelivery} then null else ${schema.slackInteractions.deliveryClaimExpiresAt} end`, deliveryAttemptCount: sql`case when ${repairableDelivery} then 0 else ${schema.slackInteractions.deliveryAttemptCount} end`, deliveryRetryAt: sql`case when ${repairableDelivery} then null else ${schema.slackInteractions.deliveryRetryAt} end`, deliveryLastErrorCode: sql`case when ${repairableDelivery} then null else ${schema.slackInteractions.deliveryLastErrorCode} end`, } : {}), updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), ), ) .returning(); return row ? mapSlackInteraction(row) : null; }); } /** * Free a thread's route key so another chat can take the thread over: a * handoff to another Slack agent, or a person naming a different agent in the * thread. The old chat keeps its channel and thread, so anything it still * delivers lands in the same thread; it just no longer receives new messages. * * Idempotent for one interaction: the retired key is derived from its id. */ export async function retireSlackInteractionRoute( db: Database, input: Pick, /** * Why the chat lost its thread. A hand-off retires to `:moved:`, which * lets the same chat finish an interrupted hand-off; a person moving the * thread to another agent retires to `:switched:`, which does not. */ reason: "handoff" | "switch" = "handoff", ): Promise { // Idempotent: a key that is already retired stays as it is. const alreadyRetired = input.routeKey.endsWith(`:moved:${input.id}`) || input.routeKey.endsWith(`:switched:${input.id}`); const suffix = reason === "switch" ? `:switched:${input.id}` : `:moved:${input.id}`; const retiredKey = alreadyRetired ? input.routeKey : `${input.routeKey.slice(0, 200)}${suffix}`; return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .update(schema.slackInteractions) .set({ routeKey: retiredKey, updatedAt: sql`now()` }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), ), ) .returning(); return row ? mapSlackInteraction(row) : null; }); } /** Remember the latest Slack message a chat was given and who sent it. */ export async function recordSlackInteractionInbound( db: Database, input: Pick & { providerEventId: string; slackUserId: string; }, ): Promise { await withRlsContext(db, input, async (scopedDb) => { await scopedDb .update(schema.slackInteractions) .set({ lastInboundProviderEventId: input.providerEventId, lastInboundSlackUserId: input.slackUserId, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.accountId, input.accountId), eq(schema.slackInteractions.workspaceId, input.workspaceId), ), ); }); } /** * The Slack event a turn is answering, by its `slack:` * client event id. A delivered user message has no `turn_id`; the turn points * back at it through `trigger_event_id`, so that is read first. * * `turnFound` is false only when the turn is unknown. A known turn started by * something other than a Slack message has a null `providerEventId`. */ export async function getSlackProviderEventIdForTurn( db: Database, input: { workspaceId: string; sessionId: string; turnId: string }, ): Promise<{ turnFound: boolean; providerEventId: string | null }> { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [trigger] = await scopedDb .select({ clientEventId: schema.sessionEvents.clientEventId }) .from(schema.sessionTurns) .leftJoin( schema.sessionEvents, and( eq(schema.sessionEvents.id, schema.sessionTurns.triggerEventId), eq(schema.sessionEvents.workspaceId, schema.sessionTurns.workspaceId), eq(schema.sessionEvents.sessionId, schema.sessionTurns.sessionId), ), ) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), ), ) .limit(1); if (trigger?.clientEventId?.startsWith("slack:")) { return { turnFound: true, providerEventId: trigger.clientEventId.slice("slack:".length) }; } const [row] = await scopedDb .select({ clientEventId: schema.sessionEvents.clientEventId }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), sql`${schema.sessionEvents.clientEventId} like 'slack:%'`, ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); const fromTurnId = row?.clientEventId ? row.clientEventId.slice("slack:".length) : null; return { turnFound: trigger !== undefined || fromTurnId !== null, providerEventId: fromTurnId }; }); } /** The inbox row of one Slack event, read under the installation's HOME tenancy. */ export async function getSlackInteractionInboxByProviderEvent( db: Database, home: { accountId: string; workspaceId: string }, input: { connectionId: string; providerEventId: string }, ): Promise { return await withRlsContext(db, home, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackInteractionInbox) .where( and( eq(schema.slackInteractionInbox.connectionId, input.connectionId), eq(schema.slackInteractionInbox.providerEventId, input.providerEventId), ), ) .limit(1); return row ? mapSlackInteractionInbox(row) : null; }); } export async function claimSlackInteractionDelivery( db: Database, claimHolderId: string, claimLeaseMs: number, ): Promise { const rows = await db.execute( sql`select * from opengeni_private.claim_slack_interaction_delivery(${claimHolderId}::uuid, ${claimLeaseMs})`, ); return rows[0] ? mapSlackInteraction(rows[0]) : null; } export async function reopenSlackInteractionDelivery( db: Database, input: Pick, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractions) .set({ terminalDeliveryState: "open", deliveryAttemptCount: 0, deliveryRetryAt: null, deliveryLastErrorCode: null, updatedAt: sql`now()`, }) .where(eq(schema.slackInteractions.id, input.id)) .returning({ id: schema.slackInteractions.id }); return rows.length === 1; }); } /** * Reopen a settled Slack thread delivery so the chat's next answer posts in * the thread again, skipping everything up to `afterSequence` (what the chat * did elsewhere meanwhile). Used when a one-time automation wakes a chat that * started in Slack, with `afterSequence` just before the wake's * `system.update.pending` event. A delivery that is still open (an earlier * answer is still being delivered) is marked instead: when a pass settles a * turn, it stays open while the wake still waits for a turn or went to a turn * that has not ended yet, and closes as usual once the wake's turn ended (see * closeSlackInteractionDelivery). Returns "reopened", "marked", or null when * the delivery is gone. */ export async function reopenSlackInteractionDeliveryAfter( db: Database, input: Pick & { afterSequence: number }, ): Promise<"reopened" | "marked" | null> { const afterSequence = Math.max(0, Math.trunc(input.afterSequence)); return await withRlsContext(db, input, async (scopedDb) => { const reopenSettled = async () => await scopedDb .update(schema.slackInteractions) .set({ terminalDeliveryState: "open", deliveryReopenAfterSequence: null, deliveryAttemptCount: 0, deliveryRetryAt: null, deliveryLastErrorCode: null, lastDeliveredSessionEventSequence: sql`greatest(${schema.slackInteractions.lastDeliveredSessionEventSequence}, ${afterSequence})`, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), sql`${schema.slackInteractions.terminalDeliveryState} <> 'open'`, ), ) .returning({ id: schema.slackInteractions.id }); if ((await reopenSettled()).length === 1) return "reopened"; const marked = await scopedDb .update(schema.slackInteractions) .set({ deliveryReopenAfterSequence: sql`greatest(coalesce(${schema.slackInteractions.deliveryReopenAfterSequence}, 0), ${afterSequence})`, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.terminalDeliveryState, "open"), ), ) .returning({ id: schema.slackInteractions.id }); if (marked.length === 1) return "marked"; // It settled between the two statements: reopen it now. return (await reopenSettled()).length === 1 ? "reopened" : null; }); } export async function advanceSlackInteractionDelivery( db: Database, input: Pick & { claimHolderId: string; sequence: number; ackSlackMessageTs?: string | null; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractions) .set({ lastDeliveredSessionEventSequence: input.sequence, ...(input.ackSlackMessageTs !== undefined ? { ackSlackMessageTs: input.ackSlackMessageTs } : {}), deliveryAttemptCount: 0, deliveryRetryAt: null, deliveryLastErrorCode: null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.deliveryClaimHolderId, input.claimHolderId), lte(schema.slackInteractions.lastDeliveredSessionEventSequence, input.sequence), ), ) .returning({ id: schema.slackInteractions.id }); return rows.length === 1; }); } export async function releaseSlackInteractionDelivery( db: Database, input: Pick & { claimHolderId: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractions) .set({ deliveryClaimHolderId: null, deliveryClaimExpiresAt: null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.deliveryClaimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackInteractions.id }); return rows.length === 1; }); } export async function deferSlackInteractionDelivery( db: Database, input: Pick & { claimHolderId: string; retryAt: Date; errorCode: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractions) .set({ deliveryClaimHolderId: null, deliveryClaimExpiresAt: null, deliveryRetryAt: input.retryAt, deliveryLastErrorCode: input.errorCode.slice(0, 128), updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.deliveryClaimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackInteractions.id }); return rows.length === 1; }); } export async function closeSlackInteractionDelivery( db: Database, input: Pick & { claimHolderId: string; sequence: number; state: Exclude; errorCode?: string | null; /** * The pass settled a turn (its terminal event is at or before `sequence`). * If a wake was marked meanwhile (see reopenSlackInteractionDeliveryAfter) * and its update is still pending, or went to a turn that has not ended * by `sequence`, the delivery stays open for the woken answer, skipping to * the wake. A wake whose turn already ended here closes as usual. The * database decides that (trigger slack_interactions_delivery_stays_open_for_wake_v1, * migration 1532), so every release's close behaves the same; a close * with an `errorCode` (a failed delivery) always closes. Kept for callers. */ settledTurn?: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackInteractions) .set({ lastDeliveredSessionEventSequence: input.sequence, terminalDeliveryState: input.state, deliveryReopenAfterSequence: null, deliveryClaimHolderId: null, deliveryClaimExpiresAt: null, deliveryRetryAt: null, deliveryLastErrorCode: input.errorCode?.slice(0, 128) ?? null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackInteractions.id, input.id), eq(schema.slackInteractions.deliveryClaimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackInteractions.id }); return rows.length === 1; }); } function mapSlackBotUserLink(row: typeof schema.slackBotUserLinks.$inferSelect): SlackBotUserLink { return row; } export type SlackThreadContextMessage = { slackUserId: string; slackMessageTs: string; text: string; hasFiles: boolean; }; /** Numeric order of two Slack message timestamps (`seconds.micros`). */ export function compareSlackMessageTs(left: string, right: string): number { const [leftSeconds = "", leftFraction = ""] = left.split("."); const [rightSeconds = "", rightFraction = ""] = right.split("."); const order = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); const seconds = order(leftSeconds.padStart(20, "0"), rightSeconds.padStart(20, "0")); if (seconds !== 0) return seconds; return order(leftFraction.padEnd(12, "0"), rightFraction.padEnd(12, "0")); } /** * The untagged messages people posted in one Slack thread since Opengeni was * last invoked there, oldest first. * * In channels an untagged thread reply never starts a turn; its signed inbox * row is the record. When someone next mentions the bot in that thread, this * read supplies those rows as context without a rate-limited Slack history * call. The walk goes back from `beforeMessageTs` and stops at the previous * mention (the last invocation), at rows older than `notBefore` (the * interaction's creation, whose own invocation already imported the earlier * thread), or at `limit` messages, reported as `truncated`. Rows carry HOME * tenancy, the installation that received them. */ export async function listSlackThreadMessagesSinceLastInvocation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; slackChannelId: string; slackThreadTs: string; beforeMessageTs: string; notBefore: Date; /** * The invoking mention's own inbox row time. Rows recorded after it are * never read, so a busy thread or a retried mention cannot push the * messages before it out of the read window. */ notAfter: Date; limit: number; }, ): Promise<{ messages: SlackThreadContextMessage[]; truncated: boolean }> { const limit = Math.max(1, Math.min(Math.floor(input.limit), 100)); const rows = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb .select({ triggerKind: schema.slackInteractionInbox.triggerKind, slackUserId: schema.slackInteractionInbox.slackUserId, slackMessageTs: schema.slackInteractionInbox.slackMessageTs, text: schema.slackInteractionInbox.text, hasFiles: schema.slackInteractionInbox.hasFiles, }) .from(schema.slackInteractionInbox) .where( and( eq(schema.slackInteractionInbox.accountId, input.accountId), eq(schema.slackInteractionInbox.workspaceId, input.workspaceId), eq(schema.slackInteractionInbox.connectionId, input.connectionId), eq(schema.slackInteractionInbox.slackChannelId, input.slackChannelId), eq(schema.slackInteractionInbox.slackThreadTs, input.slackThreadTs), gte(schema.slackInteractionInbox.createdAt, input.notBefore), lte(schema.slackInteractionInbox.createdAt, input.notAfter), inArray(schema.slackInteractionInbox.triggerKind, ["thread_reply", "app_mention"]), ), ) .orderBy( desc(schema.slackInteractionInbox.createdAt), desc(schema.slackInteractionInbox.id), ) // Mentions interleave with replies, so read past the message limit to // find the boundary; anything beyond is reported as truncated. .limit(limit * 2 + 1), ); const newestFirst = rows .filter((row) => compareSlackMessageTs(row.slackMessageTs, input.beforeMessageTs) < 0) .sort((left, right) => compareSlackMessageTs(right.slackMessageTs, left.slackMessageTs)); const messages: SlackThreadContextMessage[] = []; let truncated = false; for (const row of newestFirst) { if (row.triggerKind === "app_mention") break; if (messages.length >= limit) { truncated = true; break; } messages.push({ slackUserId: row.slackUserId, slackMessageTs: row.slackMessageTs, text: row.text, hasFiles: row.hasFiles, }); } if (!truncated && messages.length === newestFirst.length && rows.length > limit * 2) { // The read window filled without reaching the previous mention. truncated = true; } return { messages: messages.reverse(), truncated }; } function mapSlackInteractionInbox( row: typeof schema.slackInteractionInbox.$inferSelect | Record, ): SlackInteractionInboxEntry { return { id: slackRowString(row, "id", "id"), accountId: slackRowString(row, "accountId", "account_id"), workspaceId: slackRowString(row, "workspaceId", "workspace_id"), connectionId: slackRowString(row, "connectionId", "connection_id"), providerEventId: slackRowString(row, "providerEventId", "provider_event_id"), providerMessageId: slackRowString(row, "providerMessageId", "provider_message_id"), slackTeamId: slackRowString(row, "slackTeamId", "slack_team_id"), slackUserId: slackRowString(row, "slackUserId", "slack_user_id"), slackChannelId: slackRowString(row, "slackChannelId", "slack_channel_id"), slackMessageTs: slackRowString(row, "slackMessageTs", "slack_message_ts"), slackThreadTs: slackRowNullableString(row, "slackThreadTs", "slack_thread_ts"), triggerKind: slackRowString(row, "triggerKind", "trigger_kind") as SlackInteractionTriggerKind, text: slackRowString(row, "text", "text"), hasFiles: slackRowBoolean(row, "hasFiles", "has_files"), status: slackRowString(row, "status", "status") as SlackInteractionInboxEntry["status"], claimHolderId: slackRowNullableString(row, "claimHolderId", "claim_holder_id"), claimExpiresAt: slackRowNullableDate(row, "claimExpiresAt", "claim_expires_at"), attemptCount: slackRowNumber(row, "attemptCount", "attempt_count"), retryAt: slackRowNullableDate(row, "retryAt", "retry_at"), lastErrorCode: slackRowNullableString(row, "lastErrorCode", "last_error_code"), reactionContextCheckpoint: slackRowValue(row, "reactionContextCheckpoint", "reaction_context_checkpoint") ?? null, targetSlackAgentId: slackRowNullableString(row, "targetSlackAgentId", "target_slack_agent_id"), handoffFromInteractionId: slackRowNullableString( row, "handoffFromInteractionId", "handoff_from_interaction_id", ), handoffFromSlackAgentId: slackRowNullableString( row, "handoffFromSlackAgentId", "handoff_from_slack_agent_id", ), processedAt: slackRowNullableDate(row, "processedAt", "processed_at"), createdAt: slackRowDate(row, "createdAt", "created_at"), updatedAt: slackRowDate(row, "updatedAt", "updated_at"), }; } function mapSlackAppHomeRefresh( row: typeof schema.slackAppHomeRefreshes.$inferSelect | Record, ): SlackAppHomeRefresh { return { id: slackRowString(row, "id", "id"), accountId: slackRowString(row, "accountId", "account_id"), workspaceId: slackRowString(row, "workspaceId", "workspace_id"), connectionId: slackRowString(row, "connectionId", "connection_id"), slackTeamId: slackRowString(row, "slackTeamId", "slack_team_id"), slackUserId: slackRowString(row, "slackUserId", "slack_user_id"), providerEventId: slackRowString(row, "providerEventId", "provider_event_id"), providerViewHash: slackRowNullableString(row, "providerViewHash", "provider_view_hash"), desiredRevision: slackRowNumber(row, "desiredRevision", "desired_revision"), processedRevision: slackRowNumber(row, "processedRevision", "processed_revision"), claimHolderId: slackRowNullableString(row, "claimHolderId", "claim_holder_id"), claimExpiresAt: slackRowNullableDate(row, "claimExpiresAt", "claim_expires_at"), attemptCount: slackRowNumber(row, "attemptCount", "attempt_count"), retryAt: slackRowNullableDate(row, "retryAt", "retry_at"), lastErrorCode: slackRowNullableString(row, "lastErrorCode", "last_error_code"), createdAt: slackRowDate(row, "createdAt", "created_at"), updatedAt: slackRowDate(row, "updatedAt", "updated_at"), }; } function mapSlackInteraction( row: typeof schema.slackInteractions.$inferSelect | Record, ): SlackInteraction { return { id: slackRowString(row, "id", "id"), accountId: slackRowString(row, "accountId", "account_id"), workspaceId: slackRowString(row, "workspaceId", "workspace_id"), connectionId: slackRowString(row, "connectionId", "connection_id"), slackTeamId: slackRowString(row, "slackTeamId", "slack_team_id"), slackChannelId: slackRowString(row, "slackChannelId", "slack_channel_id"), slackThreadTs: slackRowString(row, "slackThreadTs", "slack_thread_ts"), routeKey: slackRowString(row, "routeKey", "route_key"), triggeringProviderEventId: slackRowString( row, "triggeringProviderEventId", "triggering_provider_event_id", ), initiatingSlackUserId: slackRowNullableString( row, "initiatingSlackUserId", "initiating_slack_user_id", ), owningSubjectId: slackRowString(row, "owningSubjectId", "owning_subject_id"), visibility: slackRowString(row, "visibility", "visibility") as SlackInteraction["visibility"], sessionReservationId: slackRowString(row, "sessionReservationId", "session_reservation_id"), sessionId: slackRowNullableString(row, "sessionId", "session_id"), lastDeliveredSessionEventSequence: slackRowNumber( row, "lastDeliveredSessionEventSequence", "last_delivered_session_event_sequence", ), deliveryClaimHolderId: slackRowNullableString( row, "deliveryClaimHolderId", "delivery_claim_holder_id", ), deliveryClaimExpiresAt: slackRowNullableDate( row, "deliveryClaimExpiresAt", "delivery_claim_expires_at", ), deliveryAttemptCount: slackRowNumber(row, "deliveryAttemptCount", "delivery_attempt_count"), deliveryRetryAt: slackRowNullableDate(row, "deliveryRetryAt", "delivery_retry_at"), deliveryLastErrorCode: slackRowNullableString( row, "deliveryLastErrorCode", "delivery_last_error_code", ), ackSlackMessageTs: slackRowNullableString(row, "ackSlackMessageTs", "ack_slack_message_ts"), firstTaskHint: slackRowNullableBoolean(row, "firstTaskHint", "first_task_hint"), routedWorkspaceLabel: slackRowNullableString( row, "routedWorkspaceLabel", "routed_workspace_label", ), sessionDefaultsLine: slackRowNullableString( row, "sessionDefaultsLine", "session_defaults_line", ), startMessageLine: slackRowNullableString(row, "startMessageLine", "start_message_line"), slackAgentId: slackRowNullableString(row, "slackAgentId", "slack_agent_id"), handoffFromSlackAgentId: slackRowNullableString( row, "handoffFromSlackAgentId", "handoff_from_slack_agent_id", ), lastInboundProviderEventId: slackRowNullableString( row, "lastInboundProviderEventId", "last_inbound_provider_event_id", ), lastInboundSlackUserId: slackRowNullableString( row, "lastInboundSlackUserId", "last_inbound_slack_user_id", ), progressCount: slackRowNumber(row, "progressCount", "progress_count"), terminalDeliveryState: slackRowString( row, "terminalDeliveryState", "terminal_delivery_state", ) as SlackInteraction["terminalDeliveryState"], createdAt: slackRowDate(row, "createdAt", "created_at"), updatedAt: slackRowDate(row, "updatedAt", "updated_at"), }; } function mapSlackInteractionActionHandle( row: typeof schema.slackInteractionActionHandles.$inferSelect, ): SlackInteractionActionHandle { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, connectionId: row.connectionId, interactionId: row.interactionId, sessionId: row.sessionId, sessionEventSequence: row.sessionEventSequence, actionKind: row.actionKind, actionKey: row.actionKey, targetId: row.targetId, targetValue: row.targetValue, authorizedSubjectId: row.authorizedSubjectId, authorizedSlackUserId: row.authorizedSlackUserId, messageOperationId: row.messageOperationId, status: row.status, result: row.result, expiresAt: row.expiresAt, completedAt: row.completedAt, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } function mapSlackInteractionProgressDelivery( row: typeof schema.slackInteractionProgressDeliveries.$inferSelect | Record, ): SlackInteractionProgressDelivery { return { id: slackRowString(row, "id", "id"), accountId: slackRowString(row, "accountId", "account_id"), workspaceId: slackRowString(row, "workspaceId", "workspace_id"), interactionId: slackRowString(row, "interactionId", "interaction_id"), sessionEventSequence: slackRowNumber(row, "sessionEventSequence", "session_event_sequence"), slot: slackRowNumber(row, "slot", "slot"), operationId: slackRowString(row, "operationId", "operation_id"), createdAt: slackRowDate(row, "createdAt", "created_at"), }; } function slackRowValue(row: Record, camelKey: string, snakeKey: string): unknown { return row[camelKey] ?? row[snakeKey]; } function slackRowString(row: Record, camelKey: string, snakeKey: string): string { const value = slackRowValue(row, camelKey, snakeKey); if (typeof value !== "string") throw new Error(`Slack row omitted ${snakeKey}`); return value; } function slackRowBoolean( row: Record, camelKey: string, snakeKey: string, ): boolean { const value = slackRowValue(row, camelKey, snakeKey); if (typeof value !== "boolean") throw new Error(`Slack row malformed ${snakeKey}`); return value; } function slackRowNullableBoolean( row: Record, camelKey: string, snakeKey: string, ): boolean | null { const value = slackRowValue(row, camelKey, snakeKey); if (value === null || value === undefined) return null; return slackRowBoolean(row, camelKey, snakeKey); } function slackRowNullableString( row: Record, camelKey: string, snakeKey: string, ): string | null { const value = slackRowValue(row, camelKey, snakeKey); if (value === null || value === undefined) return null; if (typeof value !== "string") throw new Error(`Slack row malformed ${snakeKey}`); return value; } function slackRowNumber(row: Record, camelKey: string, snakeKey: string): number { const value = slackRowValue(row, camelKey, snakeKey); const parsed = typeof value === "number" ? value : Number(value); if (!Number.isSafeInteger(parsed)) throw new Error(`Slack row malformed ${snakeKey}`); return parsed; } function slackRowDate(row: Record, camelKey: string, snakeKey: string): Date { const value = slackRowValue(row, camelKey, snakeKey); const parsed = value instanceof Date ? value : new Date(String(value)); if (Number.isNaN(parsed.getTime())) throw new Error(`Slack row malformed ${snakeKey}`); return parsed; } function slackRowNullableDate( row: Record, camelKey: string, snakeKey: string, ): Date | null { const value = slackRowValue(row, camelKey, snakeKey); if (value === null || value === undefined) return null; return slackRowDate(row, camelKey, snakeKey); } export class SlackBotLifecycleSuccessAuditError extends Error { constructor() { super("Opengeni Slack bot lifecycle success audit failed"); this.name = "SlackBotLifecycleSuccessAuditError"; } } type SlackBotLifecycleSuccessAuditInput = { accountId: string; workspaceId: string; subjectId: string; credentialRole: string; credentialLabel: string; slackTeamId: string; }; export type PersistSlackBotInstallationInput = SlackBotLifecycleSuccessAuditInput & { requestedConnectionId?: string; requestedConnectionVersion?: number; credentialEncrypted: string; grantedScopes: string[]; verifiedInstallAt: Date; metadata: Record & { slackTeamId: string; slackTeamName: string; botId: string; botUserId: string; }; }; async function insertSlackBotLifecycleSuccessAuditInScope( db: Database, input: SlackBotLifecycleSuccessAuditInput & { action: "slack_bot.connected" | "slack_bot.reinstalled" | "slack_bot.disconnected"; connectionId: string; }, ): Promise { try { const [binding] = await db .select({ version: schema.slackInstallationBindings.version }) .from(schema.slackInstallationBindings) .where(eq(schema.slackInstallationBindings.connectionId, input.connectionId)) .limit(1); if (!binding) throw new Error("Slack lifecycle mutation omitted its installation binding"); await db.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: input.action, targetType: "connection", targetId: input.connectionId, metadata: { credentialRole: input.credentialRole, credentialLabel: input.credentialLabel, connectionId: input.connectionId, slackTeamId: input.slackTeamId, bindingVersion: binding.version, outcome: "succeeded", }, }, "metadata", "metadataCodecVersion", ), ); } catch { // Do not leak a provider/database payload through the callback. Throwing from // the RLS transaction is what rolls the paired connection mutation back. throw new SlackBotLifecycleSuccessAuditError(); } } export async function persistSlackBotInstallationWithSuccessAudit( db: Database, input: PersistSlackBotInstallationInput, ): Promise { return await withSlackBotLifecycleRls(db, input, async (scopedDb) => { const inspection = await inspectSlackInstallationBindingInScope(scopedDb, { slackTeamId: input.metadata.slackTeamId, botId: input.metadata.botId, botUserId: input.metadata.botUserId, }); if (inspection.outcome !== "available" && inspection.outcome !== "same_binding") { throw new SlackInstallationBindingConflictError(inspection.outcome); } let action: "slack_bot.connected" | "slack_bot.reinstalled"; let connection: ConnectionMetadataWithVerification | null; if (inspection.outcome === "same_binding") { if (!inspection.connectionId || !inspection.connectionVersion) { throw new Error("same Slack installation binding omitted its connection fence"); } if ( (input.requestedConnectionId && input.requestedConnectionId !== inspection.connectionId) || (input.requestedConnectionVersion !== undefined && input.requestedConnectionVersion !== inspection.connectionVersion) ) { throw new SlackInstallationBindingConflictError("stale_reinstall"); } action = "slack_bot.reinstalled"; connection = await updateConnectionInScope(scopedDb, { workspaceId: input.workspaceId, connectionId: inspection.connectionId, visibleToSubjectId: input.subjectId, expectedVersion: inspection.connectionVersion, subjectId: null, providerDomain: "slack.com", kind: "app_install", status: "active", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes, expiresAt: null, verifiedInstallAt: input.verifiedInstallAt, verifiedInstallVersion: inspection.connectionVersion + 1, metadata: input.metadata, updatedBySubjectId: input.subjectId, }); } else { if (input.requestedConnectionId || input.requestedConnectionVersion !== undefined) { throw new SlackInstallationBindingConflictError("stale_reinstall"); } action = "slack_bot.connected"; connection = await createConnectionInScope(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: null, providerDomain: "slack.com", kind: "app_install", credentialEncrypted: input.credentialEncrypted, grantedScopes: input.grantedScopes, expiresAt: null, verifiedInstallAt: input.verifiedInstallAt, verifiedInstallVersion: 1, metadata: input.metadata, createdBySubjectId: input.subjectId, }); } if (!connection) throw new SlackInstallationBindingConflictError("stale_reinstall"); await insertSlackBotLifecycleSuccessAuditInScope(scopedDb, { ...input, action, connectionId: connection.id, }); return connection; }); } async function assertWorkspaceAccountPairInScope( db: Database, accountId: string, workspaceId: string, ): Promise { const [workspace] = await db .select({ id: schema.workspaces.id }) .from(schema.workspaces) .where(and(eq(schema.workspaces.id, workspaceId), eq(schema.workspaces.accountId, accountId))) .limit(1); if (!workspace) { throw new Error("Workspace does not belong to the expected account"); } } async function withSlackBotLifecycleRls( db: Database, input: Pick, fn: (db: Database) => Promise, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); await assertWorkspaceAccountPairInScope(scopedDb, input.accountId, input.workspaceId); return await fn(scopedDb); }, ); } export async function createConnectionWithSlackBotSuccessAudit( db: Database, input: SlackBotLifecycleSuccessAuditInput & { connection: CreateConnectionInput; }, ): Promise { if ( input.connection.accountId !== input.accountId || input.connection.workspaceId !== input.workspaceId ) { throw new Error("Slack bot connection and lifecycle audit tenant must match"); } return await withSlackBotLifecycleRls(db, input, async (scopedDb) => { const connection = await createConnectionInScope(scopedDb, input.connection); await insertSlackBotLifecycleSuccessAuditInScope(scopedDb, { ...input, action: "slack_bot.connected", connectionId: connection.id, }); return connection; }); } export async function updateConnectionWithSlackBotSuccessAudit( db: Database, input: SlackBotLifecycleSuccessAuditInput & { connection: UpdateConnectionInput; }, ): Promise { if (input.connection.workspaceId !== input.workspaceId) { throw new Error("Slack bot connection and lifecycle audit workspace must match"); } return await withSlackBotLifecycleRls(db, input, async (scopedDb) => { const connection = await updateConnectionInScope(scopedDb, input.connection); if (!connection) return null; if (connection.accountId !== input.accountId) { throw new Error("Slack bot connection and lifecycle audit account must match"); } await insertSlackBotLifecycleSuccessAuditInScope(scopedDb, { ...input, action: "slack_bot.reinstalled", connectionId: connection.id, }); return connection; }); } export async function revokeConnectionWithSlackBotSuccessAudit( db: Database, input: SlackBotLifecycleSuccessAuditInput & { connectionId: string; expectedVersion: number; /** Also record the generic `connection.disconnected` row as this actor. */ audit?: DisconnectAuditActor | null; }, ): Promise { return await withSlackBotLifecycleRls(db, input, async (scopedDb) => { const connection = await revokeConnectionAuditedInScope( scopedDb, input.workspaceId, input.connectionId, input.subjectId, input.expectedVersion, input.audit, ); if (!connection) return null; if (connection.accountId !== input.accountId) { throw new Error("Slack bot connection and lifecycle audit account must match"); } await insertSlackBotLifecycleSuccessAuditInScope(scopedDb, { ...input, action: "slack_bot.disconnected", connectionId: connection.id, }); return connection; }); } export type SlackBotInstallCallbackFailureStage = | "permission_check" | "nonce_consume" | "provider_denial" | "code_exchange" | "credential_verification" | "permission_recheck" | "principal_validation" | "persistence"; export type SlackBotInstallCallbackFailureReason = | "permission_lost" | "state_replayed" | "provider_denied" | "missing_code" | "exchange_failed" | "scope_mismatch" | "identity_mismatch" | "credential_verification_failed" | "connection_conflict" | "principal_mismatch" | "persistence_failed" | "success_audit_failed"; export async function recordSlackBotInstallCallbackFailure( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; callbackDigest: string; installMode: "connect" | "reinstall"; stage: SlackBotInstallCallbackFailureStage; reason: SlackBotInstallCallbackFailureReason; }, ): Promise { if (!/^[a-f0-9]{64}$/.test(input.callbackDigest)) { throw new Error("Slack callback digest must be a lowercase SHA-256 value"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); await assertWorkspaceAccountPairInScope(scopedDb, input.accountId, input.workspaceId); await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`slack-callback-failure:${input.workspaceId}:${input.callbackDigest}`}, 0))`, ); const [existing] = await scopedDb .select({ id: schema.auditEvents.id }) .from(schema.auditEvents) .where( and( eq(schema.auditEvents.accountId, input.accountId), eq(schema.auditEvents.workspaceId, input.workspaceId), eq(schema.auditEvents.action, "slack_bot.install.callback.failed"), eq(schema.auditEvents.targetType, "slack_oauth_callback"), eq(schema.auditEvents.targetId, input.callbackDigest), ), ) .limit(1); if (existing) return false; await scopedDb.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "slack_bot.install.callback.failed", targetType: "slack_oauth_callback", targetId: input.callbackDigest, metadata: { outcome: "failed", installMode: input.installMode, stage: input.stage, reason: input.reason, }, }, "metadata", "metadataCodecVersion", ), ); return true; }, ); } export type ClaimSlackBotPostOperationResult = | { kind: "claimed" | "reconcile" | "in_progress" | "completed"; operation: SlackBotPostOperation; } | { kind: "conflict" | "connection_not_found" }; /** * Claims one durable Slack post identity. The insert occurs before any provider * call; retries retain the original client_msg_id and immutable request digest. * A live claim suppresses concurrent work. An expired provider_started claim is * conservatively converted to outcome_unknown and may only be reconciled. */ export async function claimSlackBotPostOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; targetKind: "channel" | "user"; targetId: string; requestDigest: string; claimHolderId: string; claimLeaseMs: number; }, ): Promise { const claimLeaseMs = Math.max(1, Math.min(Math.trunc(input.claimLeaseMs), 120_000)); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [connection] = await tx .select({ id: schema.connections.id }) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), ), ) .for("share") .limit(1); if (!connection) return { kind: "connection_not_found" } as const; const [created] = await tx .insert(schema.slackBotPostOperations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, operationId: input.operationId, clientMessageId: input.operationId, targetKind: input.targetKind, targetId: input.targetId, requestDigest: input.requestDigest, status: "pending", claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, claimMode: "send", attemptCount: 1, }) .onConflictDoNothing({ target: [ schema.slackBotPostOperations.workspaceId, schema.slackBotPostOperations.connectionId, schema.slackBotPostOperations.operationId, ], }) .returning(); if (created) { return { kind: "claimed", operation: mapSlackBotPostOperation(created), } as const; } const [existing] = await tx .select() .from(schema.slackBotPostOperations) .where( and( eq(schema.slackBotPostOperations.workspaceId, input.workspaceId), eq(schema.slackBotPostOperations.connectionId, input.connectionId), eq(schema.slackBotPostOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!existing) throw new Error("Slack post operation disappeared after conflict"); if ( existing.accountId !== input.accountId || existing.targetKind !== input.targetKind || existing.targetId !== input.targetId || existing.requestDigest !== input.requestDigest || existing.clientMessageId !== input.operationId ) { return { kind: "conflict" } as const; } if (existing.status === "completed") { return { kind: "completed", operation: mapSlackBotPostOperation(existing), } as const; } if ( existing.claimHolderId && existing.claimExpiresAt && existing.claimExpiresAt > new Date() ) { return { kind: "in_progress", operation: mapSlackBotPostOperation(existing), } as const; } const nextStatus = existing.status === "provider_started" ? "outcome_unknown" : existing.status; const claimMode = nextStatus === "outcome_unknown" ? "reconcile" : "send"; const [reclaimed] = await tx .update(schema.slackBotPostOperations) .set({ status: nextStatus, claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, claimMode, attemptCount: sql`${schema.slackBotPostOperations.attemptCount} + 1`, updatedAt: sql`now()`, }) .where(eq(schema.slackBotPostOperations.id, existing.id)) .returning(); if (!reclaimed) throw new Error("Slack post operation reclaim returned no row"); return { kind: claimMode === "reconcile" ? "reconcile" : "claimed", operation: mapSlackBotPostOperation(reclaimed), } as const; }), ); } export async function markSlackBotPostOperationProviderStarted( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.slackBotPostOperations) .set({ status: "provider_started", updatedAt: sql`now()` }) .where( and( eq(schema.slackBotPostOperations.workspaceId, input.workspaceId), eq(schema.slackBotPostOperations.connectionId, input.connectionId), eq(schema.slackBotPostOperations.operationId, input.operationId), eq(schema.slackBotPostOperations.status, "pending"), eq(schema.slackBotPostOperations.claimMode, "send"), eq(schema.slackBotPostOperations.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackBotPostOperations.id }); return rows.length === 1; }, ); } export async function releaseSlackBotPostOperationClaim( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; outcomeUnknown: boolean; failureCode: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.slackBotPostOperations) .set({ status: input.outcomeUnknown ? "outcome_unknown" : "pending", claimHolderId: null, claimExpiresAt: null, claimMode: null, lastFailureCode: input.failureCode.slice(0, 128), updatedAt: sql`now()`, }) .where( and( eq(schema.slackBotPostOperations.workspaceId, input.workspaceId), eq(schema.slackBotPostOperations.connectionId, input.connectionId), eq(schema.slackBotPostOperations.operationId, input.operationId), ne(schema.slackBotPostOperations.status, "completed"), eq(schema.slackBotPostOperations.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackBotPostOperations.id }); return rows.length === 1; }, ); } export type CompleteSlackBotPostOperationResult = | { kind: "completed"; operation: SlackBotPostOperation; newlyCompleted: boolean; } | { kind: "not_found" | "not_owned" }; /** Completion and the single success audit receipt commit atomically. */ export async function completeSlackBotPostOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; slackChannelId: string; slackMessageTimestamp: string; subjectId?: string | null; auditMetadata: Record; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [current] = await tx .select() .from(schema.slackBotPostOperations) .where( and( eq(schema.slackBotPostOperations.workspaceId, input.workspaceId), eq(schema.slackBotPostOperations.connectionId, input.connectionId), eq(schema.slackBotPostOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!current) return { kind: "not_found" } as const; if (current.status === "completed") { return { kind: "completed", operation: mapSlackBotPostOperation(current), newlyCompleted: false, } as const; } if (current.claimHolderId !== input.claimHolderId) { return { kind: "not_owned" } as const; } const [completed] = await tx .update(schema.slackBotPostOperations) .set({ status: "completed", claimHolderId: null, claimExpiresAt: null, claimMode: null, lastFailureCode: null, slackChannelId: input.slackChannelId, slackMessageTimestamp: input.slackMessageTimestamp, completedAt: sql`now()`, updatedAt: sql`now()`, }) .where(eq(schema.slackBotPostOperations.id, current.id)) .returning(); if (!completed) throw new Error("Slack post completion returned no row"); await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "slack_bot.message.post", targetType: "connection", targetId: input.connectionId, metadata: input.auditMetadata, }, "metadata", "metadataCodecVersion", ), ); return { kind: "completed", operation: mapSlackBotPostOperation(completed), newlyCompleted: true, } as const; }), ); } export async function getSlackBotPostOperation( db: Database, workspaceId: string, connectionId: string, operationId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackBotPostOperations) .where( and( eq(schema.slackBotPostOperations.workspaceId, workspaceId), eq(schema.slackBotPostOperations.connectionId, connectionId), eq(schema.slackBotPostOperations.operationId, operationId), ), ) .limit(1); return row ? mapSlackBotPostOperation(row) : null; }); } export type ClaimSlackBotUpdateOperationResult = | { kind: "claimed" | "in_progress" | "completed"; operation: SlackBotUpdateOperation; } | { kind: "conflict" | "connection_not_found" }; export async function claimSlackBotUpdateOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; slackChannelId: string; slackMessageTimestamp: string; requestDigest: string; claimHolderId: string; claimLeaseMs: number; }, ): Promise { const claimLeaseMs = Math.max(1, Math.min(Math.trunc(input.claimLeaseMs), 120_000)); return await withRlsContext( db, input, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [connection] = await tx .select({ id: schema.connections.id }) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), ), ) .for("share") .limit(1); if (!connection) return { kind: "connection_not_found" } as const; const [created] = await tx .insert(schema.slackBotUpdateOperations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, operationId: input.operationId, slackChannelId: input.slackChannelId, slackMessageTimestamp: input.slackMessageTimestamp, requestDigest: input.requestDigest, status: "provider_started", claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, attemptCount: 1, }) .onConflictDoNothing({ target: [ schema.slackBotUpdateOperations.workspaceId, schema.slackBotUpdateOperations.connectionId, schema.slackBotUpdateOperations.operationId, ], }) .returning(); if (created) return { kind: "claimed", operation: mapSlackBotUpdateOperation(created), }; const [existing] = await tx .select() .from(schema.slackBotUpdateOperations) .where( and( eq(schema.slackBotUpdateOperations.workspaceId, input.workspaceId), eq(schema.slackBotUpdateOperations.connectionId, input.connectionId), eq(schema.slackBotUpdateOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!existing) throw new Error("Slack update operation disappeared after conflict"); if ( existing.accountId !== input.accountId || existing.slackChannelId !== input.slackChannelId || existing.slackMessageTimestamp !== input.slackMessageTimestamp || existing.requestDigest !== input.requestDigest ) { return { kind: "conflict" } as const; } if (existing.status === "completed") { return { kind: "completed", operation: mapSlackBotUpdateOperation(existing), }; } const [reclaimed] = await tx .update(schema.slackBotUpdateOperations) .set({ claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, attemptCount: sql`${schema.slackBotUpdateOperations.attemptCount} + 1`, lastFailureCode: null, updatedAt: sql`now()`, }) .where( and( eq(schema.slackBotUpdateOperations.id, existing.id), or( isNull(schema.slackBotUpdateOperations.claimHolderId), lte(schema.slackBotUpdateOperations.claimExpiresAt, sql`now()`), ), ), ) .returning(); return reclaimed ? { kind: "claimed", operation: mapSlackBotUpdateOperation(reclaimed), } : { kind: "in_progress", operation: mapSlackBotUpdateOperation(existing), }; }), ); } export async function releaseSlackBotUpdateOperationClaim( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; failureCode: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .update(schema.slackBotUpdateOperations) .set({ claimHolderId: null, claimExpiresAt: null, lastFailureCode: input.failureCode.slice(0, 128), updatedAt: sql`now()`, }) .where( and( eq(schema.slackBotUpdateOperations.workspaceId, input.workspaceId), eq(schema.slackBotUpdateOperations.connectionId, input.connectionId), eq(schema.slackBotUpdateOperations.operationId, input.operationId), eq(schema.slackBotUpdateOperations.status, "provider_started"), eq(schema.slackBotUpdateOperations.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackBotUpdateOperations.id }); return rows.length === 1; }); } export async function completeSlackBotUpdateOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; subjectId?: string | null; auditMetadata: Record; }, ): Promise<"completed" | "not_found" | "not_owned"> { return await withRlsContext( db, input, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [current] = await tx .select() .from(schema.slackBotUpdateOperations) .where( and( eq(schema.slackBotUpdateOperations.workspaceId, input.workspaceId), eq(schema.slackBotUpdateOperations.connectionId, input.connectionId), eq(schema.slackBotUpdateOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!current) return "not_found" as const; if (current.status === "completed") return "completed" as const; if (current.claimHolderId !== input.claimHolderId) return "not_owned" as const; await tx .update(schema.slackBotUpdateOperations) .set({ status: "completed", claimHolderId: null, claimExpiresAt: null, lastFailureCode: null, completedAt: sql`now()`, updatedAt: sql`now()`, }) .where(eq(schema.slackBotUpdateOperations.id, current.id)); await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "slack_bot.message.update", targetType: "connection", targetId: input.connectionId, metadata: input.auditMetadata, }, "metadata", "metadataCodecVersion", ), ); return "completed" as const; }), ); } export type ClaimSlackBotDeleteOperationResult = | { kind: "claimed" | "reconcile" | "in_progress" | "completed"; operation: SlackBotDeleteOperation; } | { kind: "conflict" | "connection_not_found" }; export async function claimSlackBotDeleteOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; principalType: "subject" | "service"; principalId: string; toolName: "slack_bot_delete_message"; channelId: string; messageTimestamp: string; requestDigest: string; claimHolderId: string; claimLeaseMs: number; }, ): Promise { if (input.toolName !== "slack_bot_delete_message") { return { kind: "conflict" }; } const claimLeaseMs = Math.max(1, Math.min(Math.trunc(input.claimLeaseMs), 120_000)); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [connection] = await tx .select({ id: schema.connections.id }) .from(schema.connections) .where( and( eq(schema.connections.accountId, input.accountId), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId), ), ) .for("share") .limit(1); if (!connection) return { kind: "connection_not_found" } as const; const [created] = await tx .insert(schema.slackBotDeleteOperations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, operationId: input.operationId, principalType: input.principalType, principalId: input.principalId, toolName: input.toolName, channelId: input.channelId, messageTimestamp: input.messageTimestamp, requestDigest: input.requestDigest, status: "pending", claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, attemptCount: 1, }) .onConflictDoNothing({ target: [ schema.slackBotDeleteOperations.workspaceId, schema.slackBotDeleteOperations.operationId, ], }) .returning(); if (created) { return { kind: "claimed", operation: mapSlackBotDeleteOperation(created), } as const; } const [existing] = await tx .select() .from(schema.slackBotDeleteOperations) .where( and( eq(schema.slackBotDeleteOperations.workspaceId, input.workspaceId), eq(schema.slackBotDeleteOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!existing) throw new Error("Slack delete operation disappeared after conflict"); if ( existing.accountId !== input.accountId || existing.connectionId !== input.connectionId || existing.principalType !== input.principalType || existing.principalId !== input.principalId || existing.toolName !== input.toolName || existing.channelId !== input.channelId || existing.messageTimestamp !== input.messageTimestamp || existing.requestDigest !== input.requestDigest ) { return { kind: "conflict" } as const; } if (existing.status === "completed") { return { kind: "completed", operation: mapSlackBotDeleteOperation(existing), } as const; } if ( existing.claimHolderId && existing.claimExpiresAt && existing.claimExpiresAt > new Date() ) { return { kind: "in_progress", operation: mapSlackBotDeleteOperation(existing), } as const; } const nextStatus = existing.status === "provider_started" ? "outcome_unknown" : existing.status; const [reclaimed] = await tx .update(schema.slackBotDeleteOperations) .set({ status: nextStatus, claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimLeaseMs} * interval '1 millisecond')`, attemptCount: sql`${schema.slackBotDeleteOperations.attemptCount} + 1`, updatedAt: sql`now()`, }) .where(eq(schema.slackBotDeleteOperations.id, existing.id)) .returning(); if (!reclaimed) throw new Error("Slack delete operation reclaim returned no row"); return { kind: nextStatus === "outcome_unknown" ? "reconcile" : "claimed", operation: mapSlackBotDeleteOperation(reclaimed), } as const; }), ); } export async function markSlackBotDeleteOperationProviderStarted( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.slackBotDeleteOperations) .set({ status: "provider_started", updatedAt: sql`now()` }) .where( and( eq(schema.slackBotDeleteOperations.workspaceId, input.workspaceId), eq(schema.slackBotDeleteOperations.connectionId, input.connectionId), eq(schema.slackBotDeleteOperations.operationId, input.operationId), eq(schema.slackBotDeleteOperations.claimHolderId, input.claimHolderId), or( eq(schema.slackBotDeleteOperations.status, "pending"), eq(schema.slackBotDeleteOperations.status, "outcome_unknown"), ), ), ) .returning({ id: schema.slackBotDeleteOperations.id }); return rows.length === 1; }, ); } export async function releaseSlackBotDeleteOperationClaim( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; outcomeUnknown: boolean; failureCode: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.slackBotDeleteOperations) .set({ status: input.outcomeUnknown ? "outcome_unknown" : "pending", claimHolderId: null, claimExpiresAt: null, lastFailureCode: input.failureCode.slice(0, 128), updatedAt: sql`now()`, }) .where( and( eq(schema.slackBotDeleteOperations.workspaceId, input.workspaceId), eq(schema.slackBotDeleteOperations.connectionId, input.connectionId), eq(schema.slackBotDeleteOperations.operationId, input.operationId), ne(schema.slackBotDeleteOperations.status, "completed"), eq(schema.slackBotDeleteOperations.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.slackBotDeleteOperations.id }); return rows.length === 1; }, ); } export type CompleteSlackBotDeleteOperationResult = | { kind: "completed"; operation: SlackBotDeleteOperation; newlyCompleted: boolean; } | { kind: "not_found" | "not_owned" }; export async function completeSlackBotDeleteOperation( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; slackChannelId: string; slackMessageTimestamp: string; subjectId?: string | null; auditMetadata: Record; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [current] = await tx .select() .from(schema.slackBotDeleteOperations) .where( and( eq(schema.slackBotDeleteOperations.workspaceId, input.workspaceId), eq(schema.slackBotDeleteOperations.connectionId, input.connectionId), eq(schema.slackBotDeleteOperations.operationId, input.operationId), ), ) .for("update") .limit(1); if (!current) return { kind: "not_found" } as const; if (current.status === "completed") { return { kind: "completed", operation: mapSlackBotDeleteOperation(current), newlyCompleted: false, } as const; } if (current.claimHolderId !== input.claimHolderId) { return { kind: "not_owned" } as const; } const [completed] = await tx .update(schema.slackBotDeleteOperations) .set({ status: "completed", claimHolderId: null, claimExpiresAt: null, lastFailureCode: null, slackChannelId: input.slackChannelId, slackMessageTimestamp: input.slackMessageTimestamp, completedAt: sql`now()`, updatedAt: sql`now()`, }) .where(eq(schema.slackBotDeleteOperations.id, current.id)) .returning(); if (!completed) throw new Error("Slack delete completion returned no row"); await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "slack_bot.message.delete", targetType: "connection", targetId: input.connectionId, metadata: input.auditMetadata, }, "metadata", "metadataCodecVersion", ), ); return { kind: "completed", operation: mapSlackBotDeleteOperation(completed), newlyCompleted: true, } as const; }), ); } export async function getSlackBotDeleteOperation( db: Database, workspaceId: string, connectionId: string, operationId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.slackBotDeleteOperations) .where( and( eq(schema.slackBotDeleteOperations.workspaceId, workspaceId), eq(schema.slackBotDeleteOperations.connectionId, connectionId), eq(schema.slackBotDeleteOperations.operationId, operationId), ), ) .limit(1); return row ? mapSlackBotDeleteOperation(row) : null; }); } export async function loadConnectionCredentialForBroker( db: Database, settings: Settings, input: { workspaceId: string; connectionId?: string; providerDomain: string; kind?: ConnectionKind; subjectId?: string | null; allowSubjectOwned?: boolean; expectedAuthorityGeneration?: number; }, ): Promise { if (input.allowSubjectOwned && !input.subjectId) { return null; } const key = environmentsEncryptionKeyBytes(settings); if (!key) { throw new Error( "connection credential present but OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured", ); } const subjectPredicate = input.allowSubjectOwned ? connectionExactSubject(input.subjectId) : isNull(schema.connections.subjectId); const conditions: SQL[] = [ eq(schema.connections.workspaceId, input.workspaceId), subjectPredicate, ]; if (input.connectionId) { conditions.push(eq(schema.connections.id, input.connectionId)); } else { conditions.push( sql`lower(${schema.connections.providerDomain}) = lower(${input.providerDomain})`, ); if (input.kind) { conditions.push(eq(schema.connections.kind, input.kind)); } } if (input.expectedAuthorityGeneration !== undefined) { conditions.push(eq(schema.connections.authorityGeneration, input.expectedAuthorityGeneration)); } return await withConnectionSubjectRls( db, input.workspaceId, input.allowSubjectOwned ? input.subjectId : null, async (scopedDb) => { // Prefer active rows: a revoke bumps updatedAt, so recency alone would let a // freshly revoked connection shadow an active replacement for the provider. // UUID-free Personal Slack lookup additionally mirrors the UI/reconnect // canonical rule through createdAt and immutable UUID tie-breakers. Migration // 0132 can stamp legacy duplicates with the same updatedAt in one transaction. const personalSlackSubjectLookup = !input.connectionId && input.allowSubjectOwned === true && input.providerDomain === "slack.com" && input.kind === "oauth2"; const [row] = await scopedDb .select() .from(schema.connections) .where(and(...conditions)) .orderBy( ...(personalSlackSubjectLookup ? personalSlackCanonicalConnectionOrder() : [ desc(sql`(${schema.connections.status} = 'active')`), desc(schema.connections.updatedAt), desc(schema.connections.createdAt), desc(schema.connections.id), ]), ) .limit(1); if (!row) { return null; } let credential: unknown; try { credential = JSON.parse(decryptEnvironmentValue(key, row.credentialEncrypted)); } catch (error) { throw new Error( `connection credential could not be decrypted for ${row.id}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } if (!credential || typeof credential !== "object" || Array.isArray(credential)) { throw new Error(`connection credential bundle for ${row.id} is not a JSON object`); } return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, subjectId: row.subjectId, providerDomain: row.providerDomain, kind: row.kind as ConnectionKind, status: row.status as ConnectionStatus, credential: credential as Record, grantedScopes: row.grantedScopes, expiresAt: row.expiresAt, lastRefreshAt: row.lastRefreshAt, version: row.version, authorityGeneration: row.authorityGeneration, metadata: row.metadata, }; }, ); } export async function getWorkspaceProviderApiKeyConnectionMetadata( db: Database, workspaceId: string, providerKind: WorkspaceProviderApiKeyConnectionKind, ): Promise<{ connectionId: string; version: number } | null> { return workspaceProviderApiKeyConnectionMetadataFromConnections( await listConnectionsMetadata(db, workspaceId, null), providerKind, ); } /** Select readiness from an already authorized, newest-first metadata read. */ export function workspaceProviderApiKeyConnectionMetadataFromConnections( connections: readonly ConnectionMetadata[], providerKind: WorkspaceProviderApiKeyConnectionKind, ): { connectionId: string; version: number } | null { const spec = workspaceProviderApiKeyConnectionSpec(providerKind); const connection = connections.find( (candidate) => candidate.subjectId === null && candidate.providerDomain.toLowerCase() === spec.providerDomain && candidate.kind === "api_key" && candidate.status === "active" && candidate.metadata.credentialRole === spec.credentialRole, ); return connection ? { connectionId: connection.id, version: connection.version } : null; } /** Metadata-only capability revision input; never selects/decrypts the API key. */ export async function getWorkspaceVercelAiGatewayConnectionMetadata( db: Database, workspaceId: string, ): Promise<{ connectionId: string; version: number } | null> { return await getWorkspaceProviderApiKeyConnectionMetadata(db, workspaceId, "vercel_gateway"); } export async function getWorkspaceOpenRouterConnectionMetadata( db: Database, workspaceId: string, ): Promise<{ connectionId: string; version: number } | null> { return await getWorkspaceProviderApiKeyConnectionMetadata(db, workspaceId, "openrouter"); } export async function getWorkspaceOpperConnectionMetadata( db: Database, workspaceId: string, ): Promise<{ connectionId: string; version: number } | null> { return await getWorkspaceProviderApiKeyConnectionMetadata(db, workspaceId, "opper"); } export async function workspaceOpperConnectionActive( db: Database, workspaceId: string, ): Promise { return (await getWorkspaceOpperConnectionMetadata(db, workspaceId)) !== null; } export async function workspaceVercelAiGatewayConnectionActive( db: Database, workspaceId: string, ): Promise { return (await getWorkspaceVercelAiGatewayConnectionMetadata(db, workspaceId)) !== null; } export async function workspaceOpenRouterConnectionActive( db: Database, workspaceId: string, ): Promise { return (await getWorkspaceOpenRouterConnectionMetadata(db, workspaceId)) !== null; } export async function loadWorkspaceProviderApiKey( db: Database, settings: Settings, workspaceId: string, providerKind: WorkspaceProviderApiKeyConnectionKind, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[], ): Promise { if (providerKind === "claude_subscription" && !settings.claudeSubscriptionEnabled) return null; const spec = workspaceProviderApiKeyConnectionSpec(providerKind); const metadata = ( connectionMetadata ?? (await listConnectionsMetadata(db, workspaceId, null)) ).find( (connection) => connection.subjectId === null && connection.providerDomain.toLowerCase() === spec.providerDomain && connection.kind === "api_key" && connection.status === "active" && connection.metadata.credentialRole === spec.credentialRole, ); if (!metadata) { return null; } const connection = await loadConnectionCredentialForBroker(db, settings, { workspaceId, connectionId: metadata.id, providerDomain: spec.providerDomain, kind: "api_key", allowSubjectOwned: false, }); if ( !connection || connection.status !== "active" || connection.metadata.credentialRole !== spec.credentialRole ) { return null; } if (turnModelId) { await assertModelConnectionAllowsTurn(db, { workspaceId, subjectId: "worker:model-access", modelId: turnModelId, workspaceProviderConnectionId: connection.id, }); } const apiKey = connection.credential.apiKey; return typeof apiKey === "string" && apiKey.trim().length > 0 ? apiKey : null; } /** Resolve only the reviewed workspace-shared AI Gateway credential shape. */ export async function loadWorkspaceVercelAiGatewayApiKey( db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[], ): Promise { return await loadWorkspaceProviderApiKey( db, settings, workspaceId, "vercel_gateway", turnModelId?.startsWith("workspace-gateway/") ? turnModelId : null, connectionMetadata, ); } /** Resolve only the reviewed workspace-shared OpenRouter credential shape. */ export async function loadWorkspaceOpenRouterApiKey( db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[], ): Promise { return await loadWorkspaceProviderApiKey( db, settings, workspaceId, "openrouter", turnModelId?.startsWith("workspace-openrouter/") ? turnModelId : null, connectionMetadata, ); } /** Resolve only the reviewed workspace-shared Opper credential shape. */ export async function loadWorkspaceOpperApiKey( db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[], ): Promise { return await loadWorkspaceProviderApiKey( db, settings, workspaceId, "opper", turnModelId?.startsWith("workspace-opper/") ? turnModelId : null, connectionMetadata, ); } /** * Worker-only immutable credential lease for an asynchronous video operation. * The operation copies the already-encrypted credential envelope before its * accepted receipt commits, so a later workspace disconnect cannot strand a * paid provider job. Never expose this return value from an API route. */ export async function loadWorkspaceVercelAiGatewayCredentialLease( db: Database, settings: Settings, workspaceId: string, ): Promise<{ connectionId: string; version: number; credentialEncrypted: string; apiKey: string; } | null> { return await withConnectionSubjectRls(db, workspaceId, null, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.connections) .where( and( eq(schema.connections.workspaceId, workspaceId), isNull(schema.connections.subjectId), sql`lower(${schema.connections.providerDomain}) = lower(${VERCEL_AI_GATEWAY_CONNECTION_DOMAIN})`, eq(schema.connections.kind, "api_key"), eq(schema.connections.status, "active"), ), ) .orderBy(desc(schema.connections.updatedAt), desc(schema.connections.id)) .limit(1); if (!row || row.metadata.credentialRole !== VERCEL_AI_GATEWAY_CONNECTION_ROLE) return null; const key = environmentsEncryptionKeyBytes(settings); if (!key) { throw new Error( "workspace AI Gateway credential requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY", ); } let decoded: unknown; try { decoded = JSON.parse(decryptEnvironmentValue(key, row.credentialEncrypted)); } catch { // JSON parser errors can quote decrypted plaintext. Never attach them to // a worker error that may be serialized into Temporal history or logs. throw new Error("workspace AI Gateway credential could not be decrypted"); } const apiKey = decoded && typeof decoded === "object" && !Array.isArray(decoded) ? (decoded as Record).apiKey : null; if (typeof apiKey !== "string" || apiKey.trim().length === 0) return null; return { connectionId: row.id, version: row.version, credentialEncrypted: row.credentialEncrypted, apiKey, }; }); } export async function recordConnectionTokenRefresh( db: Database, input: { id: string; version: number; workspaceId: string; credentialEncrypted: string; expiresAt: Date | null; grantedScopes?: string[]; metadata?: Record; lastRefreshAt: Date; subjectId?: string | null; }, ): Promise { return await withConnectionSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => { const set = { credentialEncrypted: input.credentialEncrypted, expiresAt: input.expiresAt, lastRefreshAt: input.lastRefreshAt, status: "active", lastError: null, version: sql`${schema.connections.version} + 1`, updatedAt: new Date(), ...(input.grantedScopes !== undefined ? { grantedScopes: input.grantedScopes } : {}), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}), }; const updated = await scopedDb .update(schema.connections) .set(set) .where( and( eq(schema.connections.id, input.id), eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.version, input.version), connectionExactSubject(input.subjectId), // A refresh may only ever renew a live credential; revoked/errored rows // stay dead even if a status change somewhere forgot to bump version. eq(schema.connections.status, "active"), ), ) .returning({ id: schema.connections.id }); return updated.length > 0; }, ); } export async function setConnectionStatus( db: Database, workspaceId: string, status: ConnectionStatus, lastError: string | null, guard: { id: string; version: number; subjectId?: string | null }, ): Promise { return await withConnectionSubjectRls(db, workspaceId, guard.subjectId, async (scopedDb) => { const updated = await scopedDb .update(schema.connections) .set({ status, lastError, version: sql`${schema.connections.version} + 1`, verifiedInstallVersion: sql`case when ${schema.connections.verifiedInstallAt} is null then null else ${schema.connections.version} + 1 end`, updatedAt: new Date(), }) .where( and( eq(schema.connections.workspaceId, workspaceId), eq(schema.connections.id, guard.id), eq(schema.connections.version, guard.version), connectionExactSubject(guard.subjectId), ), ) .returning({ id: schema.connections.id }); return updated.length > 0; }); } export async function recordConnectionUsed( db: Database, workspaceId: string, connectionId: string, subjectId?: string | null, ): Promise { await withConnectionSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { await scopedDb .update(schema.connections) .set({ lastUsedAt: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.connections.workspaceId, workspaceId), eq(schema.connections.id, connectionId), connectionExactSubject(subjectId), ), ); }); } export async function loadIntegrationOAuthClient( db: Database, settings: Settings, issuer: string, ): Promise { const [row] = await db .select() .from(schema.integrationOauthClients) .where(eq(schema.integrationOauthClients.issuer, issuer)) .limit(1); if (!row) { return null; } let clientSecret: string | null = null; if (row.clientSecretEncrypted) { const key = environmentsEncryptionKeyBytes(settings); if (!key) { throw new Error( "OAuth client secret present but OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured", ); } clientSecret = decryptEnvironmentValue(key, row.clientSecretEncrypted); } return { id: row.id, issuer: row.issuer, authorizationServer: row.authorizationServer, clientId: row.clientId, clientSecret, tokenEndpointAuthMethod: row.tokenEndpointAuthMethod, metadata: row.metadata, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } export async function storeIntegrationOAuthClient( db: Database, input: StoreIntegrationOAuthClientInput, ): Promise { const [inserted] = await db .insert(schema.integrationOauthClients) .values({ issuer: input.issuer, authorizationServer: input.authorizationServer, clientId: input.clientId, clientSecretEncrypted: input.clientSecretEncrypted ?? null, tokenEndpointAuthMethod: input.tokenEndpointAuthMethod ?? "none", metadata: input.metadata ?? {}, }) .onConflictDoNothing({ target: schema.integrationOauthClients.issuer, }) .returning(); if (inserted) { return mapStoredIntegrationOAuthClient(inserted); } const [winner] = await db .select() .from(schema.integrationOauthClients) .where(eq(schema.integrationOauthClients.issuer, input.issuer)) .limit(1); if (!winner) { throw new Error( `OAuth client registration conflict winner not found for issuer ${input.issuer}`, ); } return mapStoredIntegrationOAuthClient(winner); } export async function replaceIntegrationOAuthClient( db: Database, input: ReplaceIntegrationOAuthClientInput, ): Promise { const [row] = await db .insert(schema.integrationOauthClients) .values({ issuer: input.issuer, authorizationServer: input.authorizationServer, clientId: input.clientId, clientSecretEncrypted: input.clientSecretEncrypted ?? null, tokenEndpointAuthMethod: input.tokenEndpointAuthMethod ?? "none", metadata: input.metadata ?? {}, }) .onConflictDoUpdate({ target: schema.integrationOauthClients.issuer, set: { authorizationServer: input.authorizationServer, clientId: input.clientId, clientSecretEncrypted: input.clientSecretEncrypted ?? null, tokenEndpointAuthMethod: input.tokenEndpointAuthMethod ?? "none", metadata: input.metadata ?? {}, updatedAt: new Date(), }, }) .returning(); if (!row) { throw new Error(`OAuth client registration replacement failed for issuer ${input.issuer}`); } return mapStoredIntegrationOAuthClient(row); } export async function replaceIntegrationOAuthClientIfCurrent( db: Database, input: ReplaceIntegrationOAuthClientIfCurrentInput, ): Promise { const [row] = await db .update(schema.integrationOauthClients) .set({ authorizationServer: input.authorizationServer, clientId: input.clientId, clientSecretEncrypted: input.clientSecretEncrypted ?? null, tokenEndpointAuthMethod: input.tokenEndpointAuthMethod ?? "none", metadata: input.metadata ?? {}, updatedAt: new Date(), }) .where( and( eq(schema.integrationOauthClients.issuer, input.issuer), eq(schema.integrationOauthClients.clientId, input.expectedClientId), ), ) .returning(); return row ? mapStoredIntegrationOAuthClient(row) : null; } function mapStoredIntegrationOAuthClient( row: typeof schema.integrationOauthClients.$inferSelect, ): StoredIntegrationOAuthClient { return { id: row.id, issuer: row.issuer, authorizationServer: row.authorizationServer, clientId: row.clientId, clientSecretEncrypted: row.clientSecretEncrypted, tokenEndpointAuthMethod: row.tokenEndpointAuthMethod, metadata: row.metadata, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } export async function consumeIntegrationOAuthStateNonce( db: Database, input: ConsumeOAuthStateNonceInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .delete(schema.integrationOauthStateNonces) .where( and( eq(schema.integrationOauthStateNonces.workspaceId, input.workspaceId), lt(schema.integrationOauthStateNonces.expiresAt, input.now), ), ); const inserted = await scopedDb .insert(schema.integrationOauthStateNonces) .values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, nonce: input.nonce, expiresAt: input.expiresAt, usedAt: input.now, }) .onConflictDoNothing({ target: schema.integrationOauthStateNonces.nonce, }) .returning({ nonce: schema.integrationOauthStateNonces.nonce }); return inserted.length > 0; }, ); } export async function createKnowledgeMemory( db: Database, input: CreateKnowledgeMemoryInput, ): Promise { const text = requireDbString(input.text, "knowledge memory text"); const scope = cleanDbString(input.scope) ?? "workspace"; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.knowledgeMemories) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, status: input.status ?? "proposed", kind: input.kind ?? "semantic", scope, text, textHash: hashMemoryText(text), sourceRefs: input.sourceRefs ?? [], confidence: confidenceToStorage(input.confidence ?? 0.5), metadata: input.metadata ?? {}, createdBySessionId: input.createdBySessionId ?? null, }, "text", "textCodecVersion", ), ) .returning(); if (!row) { throw new Error("Failed to create knowledge memory"); } return mapKnowledgeMemory(row); }, ); } export async function updateKnowledgeMemory( db: Database, workspaceId: string, memoryId: string, input: UpdateKnowledgeMemoryInput, embedder?: MemoryEmbedder, ): Promise { const reviewStatus = input.status === "approved" || input.status === "rejected"; const scope = input.scope !== undefined ? requireDbString(input.scope, "knowledge memory scope") : undefined; const reviewedBy = input.reviewedBy === null ? null : input.reviewedBy !== undefined ? requireDbString(input.reviewedBy, "knowledge memory reviewer") : undefined; // A text edit is a human audit action: it bypasses the dedup/cap gates (an // authorized curator's edit is intentional), preserves exact text, recomputes // text_hash, and re-embeds fail-soft so the row stays coherent. type MemoryTextUpdate = { text: string; textHash: string; embedding: number[] | null; embeddingModel: string | null; updateEmbedding: boolean; }; const embedForMemoryUpdate = async ( exactText: string, ): Promise<{ embedding: number[] | null; embeddingModel: string | null }> => { let embedding: number[] | null = null; let embeddingModel: string | null = null; if (embedder) { try { const [vector] = await embedder.embedMany([exactText]); if (vector && vector.length > 0) { embedding = vector; embeddingModel = embedder.model; } } catch { console.warn("workspace memory edit: embedding failed; storing keyword-only", { errorClass: "MemoryEmbeddingOperationError", errorCode: "memory_edit_embedding_failed", origin: "db", }); } } return { embedding, embeddingModel }; }; let textUpdate: MemoryTextUpdate | undefined; if (input.text !== undefined) { const exactText = memoryTextForStorage(input.text); if (normalizeMemoryText(exactText).length === 0) { throw new Error("Memory text is empty; nothing to save."); } if (isMemoryTextTooLong(exactText)) { throw new Error( `Memory text is too long (${exactText.length} chars; max ${MEMORY_TEXT_MAX_CHARS}).`, ); } const { embedding, embeddingModel } = await embedForMemoryUpdate(exactText); textUpdate = { text: exactText, textHash: hashMemoryText(exactText), embedding, embeddingModel, updateEmbedding: true, }; } return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [existing] = await scopedDb .select({ id: schema.knowledgeMemories.id, status: schema.knowledgeMemories.status, text: schema.knowledgeMemories.text, textCodecVersion: schema.knowledgeMemories.textCodecVersion, textHash: schema.knowledgeMemories.textHash, embedding: schema.knowledgeMemories.embedding, }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), eq(schema.knowledgeMemories.id, memoryId), ), ) .limit(1); if (!existing) { throw new Error(`Knowledge memory not found: ${memoryId}`); } const existingText = fromPostgresLosslessText(existing.text, existing.textCodecVersion); const nextStatus = (input.status ?? existing.status) as KnowledgeMemoryStatus; const wasVisible = agentVisibleMemoryStatuses.includes( existing.status as (typeof agentVisibleMemoryStatuses)[number], ); const willBeVisible = agentVisibleMemoryStatuses.includes( nextStatus as (typeof agentVisibleMemoryStatuses)[number], ); if (willBeVisible) { const [{ visibleCount } = { visibleCount: 0 }] = await scopedDb .select({ visibleCount: sql`count(*)::int`, }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), ne(schema.knowledgeMemories.id, memoryId), ), ); if (Number(visibleCount) >= MEMORY_VISIBLE_RECORD_CAP) { throw new Error( `Workspace's visible memory is full (${MEMORY_VISIBLE_RECORD_CAP} visible records). Correct or supersede stale memories before adding new ones.`, ); } } if (!wasVisible && willBeVisible && textUpdate === undefined) { const exactText = memoryTextForStorage(existingText); if (normalizeMemoryText(exactText).length === 0) { throw new Error("Memory text is empty; nothing to save."); } if (isMemoryTextTooLong(exactText)) { throw new Error( `Memory text is too long (${exactText.length} chars; max ${MEMORY_TEXT_MAX_CHARS}).`, ); } const textChanged = exactText !== existingText; const missingEmbedding = existing.embedding == null; const { embedding, embeddingModel } = textChanged || missingEmbedding ? await embedForMemoryUpdate(exactText) : { embedding: null, embeddingModel: null }; textUpdate = { text: exactText, textHash: hashMemoryText(exactText), embedding, embeddingModel, updateEmbedding: textChanged || missingEmbedding, }; } const nextTextHash = textUpdate?.textHash ?? existing.textHash; if (!wasVisible && willBeVisible && nextTextHash) { const duplicate = await findVisibleMemoryByTextHash( scopedDb, workspaceId, nextTextHash, memoryId, ); if (duplicate) { throw new Error(visibleTextHashConflictMessage(duplicate)); } } let row: typeof schema.knowledgeMemories.$inferSelect | undefined; try { const rows = await scopedDb.transaction( async (tx) => await tx .update(schema.knowledgeMemories) .set({ ...(input.status !== undefined ? { status: input.status } : {}), ...(input.kind !== undefined ? { kind: input.kind } : {}), ...(scope !== undefined ? { scope } : {}), ...(textUpdate !== undefined ? { text: textUpdate.text, textCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, textHash: textUpdate.textHash, ...(textUpdate.updateEmbedding ? { embedding: textUpdate.embedding, embeddingModel: textUpdate.embeddingModel, } : {}), } : {}), ...(input.sourceRefs !== undefined ? { sourceRefs: input.sourceRefs } : {}), ...(input.confidence !== undefined ? { confidence: confidenceToStorage(input.confidence) } : {}), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}), ...(input.pinned !== undefined ? { pinned: input.pinned } : {}), // Re-proposing clears review metadata; an explicit reviewedBy in the same // update still wins via the later spread. ...(input.status === "proposed" ? { reviewedBy: null, reviewedAt: null } : {}), ...(reviewedBy !== undefined ? { reviewedBy } : {}), ...(reviewStatus ? { reviewedAt: new Date() } : {}), updatedAt: new Date(), }) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), eq(schema.knowledgeMemories.id, memoryId), ), ) .returning(), ); row = rows[0]; } catch (error) { if (!isVisibleTextHashUniqueViolation(error) || !nextTextHash) { throw error; } const duplicate = await findVisibleMemoryByTextHash( scopedDb, workspaceId, nextTextHash, memoryId, ); throw new Error(visibleTextHashConflictMessage(duplicate), { cause: error, }); } if (!row) { throw new Error(`Knowledge memory not found: ${memoryId}`); } return mapKnowledgeMemory(row); }); } export async function getKnowledgeMemory( db: Database, workspaceId: string, memoryId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), eq(schema.knowledgeMemories.id, memoryId), ), ) .limit(1); return row ? mapKnowledgeMemory(row) : null; }); } export async function listKnowledgeMemories( db: Database, workspaceId: string, options: ListKnowledgeMemoryOptions = {}, ): Promise { const readScopes = memoryAgentReadScopes(options.agentScope); if (readScopes && readScopes.length === 0) return []; return await withWorkspaceRls(db, workspaceId, (scopedDb) => withMemoryScopeRlsContext(scopedDb, readScopes, async () => { const conditions: SQL[] = [eq(schema.knowledgeMemories.workspaceId, workspaceId)]; if (readScopes) conditions.push(memoryScopeVisibilityFilter(readScopes)); if (options.status) { conditions.push( Array.isArray(options.status) ? inArray(schema.knowledgeMemories.status, options.status) : eq(schema.knowledgeMemories.status, options.status), ); } if (options.kind) { conditions.push(eq(schema.knowledgeMemories.kind, options.kind)); } const scope = cleanDbString(options.scope); if (scope) { conditions.push(eq(schema.knowledgeMemories.scope, scope)); } const query = cleanDbString(options.query); if (query) { conditions.push( sql`to_tsvector('simple', ${schema.knowledgeMemories.text}) @@ plainto_tsquery('simple', ${query})`, ); } const limit = Math.min(Math.max(options.limit ?? 20, 1), 100); const rows = await scopedDb .select() .from(schema.knowledgeMemories) .where(and(...conditions)) .orderBy(desc(schema.knowledgeMemories.updatedAt)) .limit(limit); return rows.map(mapKnowledgeMemory); }), ); } // =========================================================================== // Workspace Memory V1 — agent-writable, hybrid-searchable memory over // knowledge_memories. saveWorkspaceMemory is the single write gate; every write // path (first-party tools, REST, future reflector) funnels through it. The // embedder is a minimal structural port so packages/db need not depend on // packages/documents; callers pass getDocumentServices().embedder. // =========================================================================== export type MemoryEmbedder = { model: string; embedMany: (texts: string[]) => Promise; }; export type WorkspaceMemoryOrigin = "agent" | "human"; export type SaveWorkspaceMemoryInput = { accountId: string; workspaceId: string; text: string; kind?: KnowledgeMemoryKind | undefined; confidence?: number | undefined; // 0-1 pinned?: boolean | undefined; replacesId?: string | null | undefined; // short or full id of the record this supersedes sessionId?: string | null | undefined; // provenance + event linkage origin?: WorkspaceMemoryOrigin | undefined; metadata?: Record | undefined; /** * Typed selector the record is written under (migration 0427). Omitted * means the shared workspace layer; `user` and `session` write one private * layer whose rows only that end-user label / root tree can read back. */ scope?: MemoryScopeSpec | undefined; }; export type SaveWorkspaceMemoryResult = { memory: KnowledgeMemory; // true → a matching record already existed; nothing new was inserted (NOOP). deduped: boolean; dedupeReason: "exact" | "near" | null; // the record that `replacesId` retired, if any. superseded: KnowledgeMemory | null; supersededId: string | null; // true when `replacesId` matched the same row and the row was updated in place // instead of being superseded by a new/existing row. updated: boolean; embedded: boolean; }; export type CorrectWorkspaceMemoryInput = { accountId: string; workspaceId: string; id: string; // short or full id reason?: string | undefined; replacementText?: string | undefined; sessionId?: string | null | undefined; origin?: WorkspaceMemoryOrigin | undefined; /** Agent read/write context; mutations must remain in its writable layer. */ agentScope?: MemoryAgentScope | undefined; }; export type CorrectWorkspaceMemoryResult = { action: "archived" | "superseded" | "updated"; // the record that was archived, superseded, or updated in place. memory: KnowledgeMemory; // the replacement record when replacementText was supplied, else null. replacement: KnowledgeMemory | null; }; export type WorkspaceMemorySearchMode = "hybrid" | "vector" | "keyword"; export type WorkspaceMemorySearchInput = { query: string; kind?: KnowledgeMemoryKind | undefined; limit?: number | undefined; mode?: WorkspaceMemorySearchMode | undefined; /** Agent-only containment. Human audit/search callers omit this. */ agentPromptMode?: WorkspaceMemoryPromptMode | undefined; /** * Agent-only typed read layers (migration 0427): the workspace layer plus * the session's own `user` or `session` layer. Human callers omit this and * keep today's workspace-only read. */ agentScope?: MemoryAgentScope | undefined; }; export type WorkspaceMemorySearchResult = { memory: KnowledgeMemory; score: number; matchType: WorkspaceMemorySearchMode; vectorScore: number | null; keywordScore: number | null; }; function memoryVectorLiteral(values: number[]): string { return `[${values.join(",")}]`; } const agentVisibleMemoryStatuses = [...AGENT_VISIBLE_MEMORY_STATUSES]; const visibleTextHashUniqueIndexNames = new Set([ "knowledge_memories_workspace_visible_text_hash_uq", "knowledge_memories_scope_visible_text_hash_uq", ]); type AgentWritableMemoryScope = Extract< MemoryScopeSpec, { type: "workspace" } | { type: "user" } | { type: "session" } >; /** Session memory scope only ever writes the three agent-owned selectors. */ function requireAgentWritableMemoryScope( scope: MemoryScopeSpec | undefined, ): AgentWritableMemoryScope { const normalized = normalizeMemoryScope(scope ?? { type: "workspace" }); if ( normalized.type !== "workspace" && normalized.type !== "user" && normalized.type !== "session" ) { throw new Error(`Workspace memory writes do not accept the ${normalized.type} scope`); } return normalized; } /** * Bind the typed selectors of one read/write to the transaction so the * FORCE-RLS `workspace_isolation` policy on knowledge_memories admits exactly * the workspace layer plus the named private layer. The subject GUC is the * opaque end-user memory subject (`end_user:v1:`), never a human; * the memory session GUC is the lineage root. */ async function withMemoryScopeRlsContext( scopedDb: Database, scopes: readonly MemoryScopeSpec[] | null, fn: () => Promise, ): Promise { if (!scopes) return await fn(); let subjectId = ""; let sessionId = ""; for (const scope of scopes) { if (scope.type === "user") subjectId = scope.subjectId; if (scope.type === "session") sessionId = scope.sessionId; } // The override is transaction-local and restored afterwards so a wrapping // caller (for example Slack publication in the same transaction) keeps its // own actor context rather than inheriting the opaque end-user subject. const [previous] = (await scopedDb.execute(sql`select current_setting('opengeni.subject_id', true) as subject_id, current_setting('opengeni.memory_session_id', true) as session_id`)) as unknown as Array<{ subject_id: string | null; session_id: string | null; }>; await scopedDb.execute(sql`select set_config('opengeni.subject_id', ${subjectId}, true), set_config('opengeni.memory_session_id', ${sessionId}, true)`); try { return await fn(); } finally { await scopedDb.execute(sql`select set_config('opengeni.subject_id', ${previous?.subject_id ?? ""}, true), set_config('opengeni.memory_session_id', ${previous?.session_id ?? ""}, true)`); } } /** Explicit typed-scope predicate matching the RLS layer (defense in depth). */ function memoryScopeVisibilityFilter(scopes: readonly MemoryScopeSpec[]): SQL { const clauses: SQL[] = []; for (const scope of scopes) { if (scope.type === "workspace") { clauses.push(eq(schema.knowledgeMemories.scopeType, "workspace")); } else if (scope.type === "user") { clauses.push( and( eq(schema.knowledgeMemories.scopeType, "user"), eq(schema.knowledgeMemories.scopeSubjectId, scope.subjectId), )!, ); } else if (scope.type === "session") { clauses.push( and( eq(schema.knowledgeMemories.scopeType, "session"), eq(schema.knowledgeMemories.scopeSessionId, scope.sessionId), )!, ); } } if (clauses.length === 0) return sql`false`; return clauses.length === 1 ? clauses[0]! : or(...clauses)!; } function memoryScopeColumns(scope: AgentWritableMemoryScope): { scope: string; scopeType: string; scopeSubjectId: string | null; scopeSessionId: string | null; } { return { scope: scope.type, scopeType: scope.type, scopeSubjectId: scope.type === "user" ? scope.subjectId : null, scopeSessionId: scope.type === "session" ? scope.sessionId : null, }; } /** The typed scope a stored record lives in, when it is one an agent may write. */ function agentWritableMemoryScopeOfRow( row: Pick< typeof schema.knowledgeMemories.$inferSelect, "scopeType" | "scopeSubjectId" | "scopeSessionId" >, ): AgentWritableMemoryScope | null { if (row.scopeType === "workspace") return { type: "workspace" }; if (row.scopeType === "user" && row.scopeSubjectId) { return { type: "user", subjectId: row.scopeSubjectId }; } if (row.scopeType === "session" && row.scopeSessionId) { return { type: "session", sessionId: row.scopeSessionId }; } return null; } /** Shared read access never grants a private agent shared write authority. */ function assertMemoryWriteScope( row: Parameters[0], scope: AgentWritableMemoryScope, ): void { const actual = agentWritableMemoryScopeOfRow(row); if (!actual || JSON.stringify(normalizeMemoryScope(actual)) !== JSON.stringify(scope)) { throw new Error("Memory mutations must stay in the session's writable scope."); } } function memoryAgentReadScopes(agentScope: MemoryAgentScope | undefined): MemoryScopeSpec[] | null { return agentScope ? memoryReadScopesForAgentScope(agentScope) : null; } function isVisibleTextHashUniqueViolation(error: unknown): boolean { const candidate = error as { code?: unknown; constraint?: unknown; constraint_name?: unknown; message?: unknown; cause?: unknown; } | null; if (!candidate || typeof candidate !== "object") { return false; } const constraint = candidate.constraint ?? candidate.constraint_name; if (candidate.code === "23505" && visibleTextHashUniqueIndexNames.has(String(constraint))) { return true; } const message = typeof candidate.message === "string" ? candidate.message : null; if ( message !== null && [...visibleTextHashUniqueIndexNames].some((name) => message.includes(name)) && (candidate.code === "23505" || message.includes("duplicate key value violates unique constraint")) ) { return true; } return isVisibleTextHashUniqueViolation(candidate.cause); } async function findVisibleMemoryByTextHash( scopedDb: Database, workspaceId: string, textHash: string, excludeId?: string, ): Promise { const filters = [ eq(schema.knowledgeMemories.workspaceId, workspaceId), eq(schema.knowledgeMemories.textHash, textHash), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), ]; if (excludeId) { filters.push(ne(schema.knowledgeMemories.id, excludeId)); } const [row] = await scopedDb .select() .from(schema.knowledgeMemories) .where(and(...filters)) .orderBy(desc(schema.knowledgeMemories.updatedAt)) .limit(1); return row ?? null; } function visibleTextHashConflictMessage( existing: Pick | { id: string } | null, ): string { const suffix = existing ? ` Existing memory id: ${existing.id}.` : ""; return `Memory text duplicates an existing visible memory.${suffix} Search memory and update, archive, or supersede the existing record instead.`; } function hasMetadataOrigin(metadata: Record): boolean { return Object.prototype.hasOwnProperty.call(metadata, "origin"); } function saveMemoryMetadata(input: SaveWorkspaceMemoryInput): Record { return { ...(input.metadata ?? {}), ...(input.origin ? { origin: input.origin } : {}), }; } function inPlaceSaveMemoryMetadata( existing: Record, input: SaveWorkspaceMemoryInput, ): Record | undefined { if (input.metadata === undefined && (!input.origin || hasMetadataOrigin(existing))) { return undefined; } const merged = { ...existing, ...(input.metadata ?? {}), }; if (hasMetadataOrigin(existing)) { merged.origin = existing.origin; } else if (input.origin) { merged.origin = input.origin; } return merged; } // Resolve a short prefix or full uuid to the full id within a workspace. Full // uuid lookup is status-agnostic so correction/archive paths can still surface a // clear terminal-row result; prefix lookup is restricted to non-terminal rows // because short ids are shown only for records an agent can legitimately target. // Returns null when nothing matches; throws on an ambiguous live prefix. async function resolveWorkspaceMemoryId( scopedDb: Database, workspaceId: string, rawId: string, ): Promise { const candidate = rawId.trim().toLowerCase(); if (!/^[0-9a-f-]{4,36}$/.test(candidate)) { return null; } if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(candidate)) { const [match] = await scopedDb .select({ id: schema.knowledgeMemories.id }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), eq(schema.knowledgeMemories.id, candidate), ), ) .limit(1); return match?.id ?? null; } const matches = await scopedDb .select({ id: schema.knowledgeMemories.id }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), sql`${schema.knowledgeMemories.id}::text like ${`${candidate}%`}`, ne(schema.knowledgeMemories.status, "archived"), ne(schema.knowledgeMemories.status, "superseded"), ne(schema.knowledgeMemories.status, "rejected"), ), ) .limit(2); if (matches.length === 0) { return null; } if (matches.length > 1) { throw new Error( `Ambiguous memory id "${rawId}": it matches multiple live memory records. Run memory_search and use the full id from the intended record.`, ); } return matches[0]!.id; } export async function saveWorkspaceMemory( db: Database, input: SaveWorkspaceMemoryInput, embedder?: MemoryEmbedder, ): Promise { const exactText = memoryTextForStorage(input.text); if (normalizeMemoryText(exactText).length === 0) { throw new Error("Memory text is empty; nothing to save."); } if (isMemoryTextTooLong(exactText)) { throw new Error( `Memory text is too long (${exactText.length} chars; max ${MEMORY_TEXT_MAX_CHARS}). Store one crisp fact per record.`, ); } const textHash = hashMemoryText(exactText); const kind: KnowledgeMemoryKind = input.kind ?? "semantic"; const writeScope = requireAgentWritableMemoryScope(input.scope); // A private write still sees the shared layer: an agent saving into its // user/session layer dedupes against workspace facts it can already read. const visibleScopes: MemoryScopeSpec[] = writeScope.type === "workspace" ? [writeScope] : [{ type: "workspace" }, writeScope]; const visibleScopeFilter = memoryScopeVisibilityFilter(visibleScopes); // Embed fail-soft, OUTSIDE the transaction: a provider error must never block a // write (the row stays keyword-searchable). Mirrors indexDocumentNow. let embedding: number[] | null = null; let embeddingModel: string | null = null; if (embedder) { try { const [vector] = await embedder.embedMany([exactText]); if (vector && vector.length > 0) { embedding = vector; embeddingModel = embedder.model; } } catch { console.warn("workspace memory save: embedding failed; saving keyword-only", { errorClass: "MemoryEmbeddingOperationError", errorCode: "memory_save_embedding_failed", origin: "db", }); } } return await withWorkspaceRls(db, input.workspaceId, (scopedDb) => withMemoryScopeRlsContext(scopedDb, visibleScopes, async () => { // Resolve the supersession target first so an invalid replaces_id fails before // we insert anything (cross-workspace ids are RLS-invisible → treated as not found). let replacesFullId: string | null = null; let replacesRow: typeof schema.knowledgeMemories.$inferSelect | null = null; if (input.replacesId) { replacesFullId = await resolveWorkspaceMemoryId( scopedDb, input.workspaceId, input.replacesId, ); if (!replacesFullId) { throw new Error( `replaces_id "${input.replacesId}" does not match a memory in this workspace.`, ); } const [row] = await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, replacesFullId), ), ) .limit(1) .for("update"); if (!row) { throw new Error( `replaces_id "${input.replacesId}" does not match a memory in this workspace.`, ); } if (input.origin === "agent" && row.status !== "active") { throw new Error( `Autonomous Memory can replace only active agent-writable records; memory "${row.id}" has status "${row.status}". Human-reviewed Knowledge must be changed through its review lifecycle.`, ); } assertMemoryWriteScope(row, writeScope); replacesRow = row; } const updateReplacesInPlace = async (): Promise => { if (!replacesFullId) { throw new Error("Cannot update a memory in place without replaces_id."); } // A caller can "replace" a row with text that exact/near-dedups only to // that same row. In that case there is no supersession target; keep the // row live and update its text/vector metadata so the call still has an // observable effect. const normalizedTextChanged = replacesRow ? hashMemoryText( fromPostgresLosslessText(replacesRow.text, replacesRow.textCodecVersion), ) !== textHash : true; const metadata = replacesRow ? inPlaceSaveMemoryMetadata(replacesRow.metadata, input) : undefined; const [updated] = await scopedDb .update(schema.knowledgeMemories) .set( withLosslessContentWriteVersion( { text: exactText, textHash, ...(normalizedTextChanged ? { // New text with no fresh vector must clear the old vector. Keeping a // stale vector would make vector search return this row for the old // text's meaning; keyword search still covers the new text. embedding, embeddingModel, } : {}), ...(input.kind !== undefined ? { kind } : {}), ...(input.confidence !== undefined ? { confidence: confidenceToStorage(input.confidence) } : {}), ...(input.pinned !== undefined ? { pinned: input.pinned } : {}), ...(metadata !== undefined ? { metadata } : {}), updatedAt: new Date(), }, "text", "textCodecVersion", ), ) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, replacesFullId), ), ) .returning(); if (!updated) { throw new Error( `replaces_id "${input.replacesId}" does not match a memory in this workspace.`, ); } return { memory: mapKnowledgeMemory(updated), deduped: false, dedupeReason: null, superseded: null, supersededId: null, updated: true, embedded: embedding !== null, }; }; const dedupeToExisting = async ( row: typeof schema.knowledgeMemories.$inferSelect, dedupeReason: "exact" | "near", ): Promise => { if (replacesFullId && row.id === replacesFullId) { return await updateReplacesInPlace(); } let superseded: KnowledgeMemory | null = null; if (replacesFullId) { const [old] = await scopedDb .update(schema.knowledgeMemories) .set({ status: "superseded", supersededById: row.id, validUntil: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, replacesFullId), ), ) .returning(); if (!old) { throw new Error( `replaces_id "${input.replacesId}" does not match a memory in this workspace.`, ); } superseded = mapKnowledgeMemory(old); } return { memory: mapKnowledgeMemory(row), deduped: true, dedupeReason, superseded, supersededId: superseded?.id ?? null, updated: false, embedded: embedding !== null, }; }; // Exact-dup gate: same normalized text among agent-visible rows → NOOP. const exactMatches = await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.textHash, textHash), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), visibleScopeFilter, ), ) .orderBy( replacesFullId ? sql`case when ${schema.knowledgeMemories.id} = ${replacesFullId} then 1 else 0 end` : schema.knowledgeMemories.updatedAt, ) .limit(replacesFullId ? 2 : 1); const exact = exactMatches.find((row) => row.id !== replacesFullId) ?? exactMatches[0]; if (exact) { return await dedupeToExisting(exact, "exact"); } // Near-dup gate: top-N cosine neighbours among agent-visible rows with a // vector from the SAME model; similarity ≥ threshold → NOOP. This check is // advisory: cosine similarity cannot be protected by a unique index, unlike // the exact text_hash gate below. if (embedding && embeddingModel) { const distance = sql`${schema.knowledgeMemories.embedding} <=> ${memoryVectorLiteral(embedding)}::vector`; const neighbours = await scopedDb .select({ id: schema.knowledgeMemories.id, distance, }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), eq(schema.knowledgeMemories.embeddingModel, embeddingModel), sql`${schema.knowledgeMemories.embedding} is not null`, visibleScopeFilter, ), ) .orderBy(distance) .limit(MEMORY_NEAR_DUP_NEIGHBORS); const duplicateNeighbours = neighbours.filter( (row) => 1 - Number(row.distance) >= MEMORY_NEAR_DUP_COSINE_THRESHOLD, ); const nearest = duplicateNeighbours.find((row) => row.id !== replacesFullId) ?? duplicateNeighbours[0]; if (nearest) { const [row] = await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, nearest.id), ), ) .limit(1); if (row) { return await dedupeToExisting(row, "near"); } } } // Per-workspace visible-record cap: fail actionably rather than silently drop. const [{ visibleCount } = { visibleCount: 0 }] = await scopedDb .select({ visibleCount: sql`count(*)::int`, }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), ), ); const replacesVisible = replacesRow ? agentVisibleMemoryStatuses.includes( replacesRow.status as (typeof agentVisibleMemoryStatuses)[number], ) : false; const effectiveVisibleCount = Number(visibleCount) - (replacesVisible ? 1 : 0); if (effectiveVisibleCount >= MEMORY_VISIBLE_RECORD_CAP) { throw new Error( `Workspace's visible memory is full (${MEMORY_VISIBLE_RECORD_CAP} visible records). Correct or supersede stale memories before adding new ones.`, ); } const sourceRefs: KnowledgeSourceRef[] = input.sessionId ? [{ kind: "session_event", id: input.sessionId, metadata: {} }] : []; let inserted: typeof schema.knowledgeMemories.$inferSelect | undefined; try { const rows = await scopedDb.transaction( async (tx) => await tx .insert(schema.knowledgeMemories) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, status: "active", kind, ...memoryScopeColumns(writeScope), text: exactText, textHash, sourceRefs, confidence: confidenceToStorage(input.confidence ?? 0.5), pinned: input.pinned ?? false, metadata: saveMemoryMetadata(input), createdBySessionId: input.sessionId ?? null, supersedesId: replacesFullId, ...(embedding ? { embedding, embeddingModel } : {}), }, "text", "textCodecVersion", ), ) .returning(), ); inserted = rows[0]; } catch (error) { if (!isVisibleTextHashUniqueViolation(error)) { throw error; } const winner = await findVisibleMemoryByTextHash(scopedDb, input.workspaceId, textHash); if (!winner) { throw error; } return await dedupeToExisting(winner, "exact"); } if (!inserted) { throw new Error("Failed to save workspace memory"); } let superseded: KnowledgeMemory | null = null; if (replacesFullId) { const [old] = await scopedDb .update(schema.knowledgeMemories) .set({ status: "superseded", supersededById: inserted.id, validUntil: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, replacesFullId), ), ) .returning(); superseded = old ? mapKnowledgeMemory(old) : null; } return { memory: mapKnowledgeMemory(inserted), deduped: false, dedupeReason: null, superseded, supersededId: superseded?.id ?? null, updated: false, embedded: embedding !== null, }; }), ); } export async function correctWorkspaceMemory( db: Database, input: CorrectWorkspaceMemoryInput, embedder?: MemoryEmbedder, ): Promise { const replacementText = input.replacementText; const readScopes = memoryAgentReadScopes(input.agentScope); if (readScopes && readScopes.length === 0) { throw new Error("Memory is disabled for this session."); } const writeScope = input.agentScope ? memoryWriteScopeForAgentScope(input.agentScope) : null; if (replacementText !== undefined) { // Correction WITH a replacement is a full supersede through the one write gate. const [old] = await withWorkspaceRls(db, input.workspaceId, (scopedDb) => withMemoryScopeRlsContext(scopedDb, readScopes, async () => { const fullId = await resolveWorkspaceMemoryId(scopedDb, input.workspaceId, input.id); if (!fullId) { return [] as (typeof schema.knowledgeMemories.$inferSelect)[]; } return await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, fullId), ), ) .limit(1) .for("update"); }), ); if (!old) { throw new Error(`Memory "${input.id}" not found in this workspace.`); } if (input.origin === "agent" && old.status !== "active") { throw new Error( `Autonomous Memory can correct only active agent-writable records; memory "${old.id}" has status "${old.status}". Human-reviewed Knowledge must be changed through its review lifecycle.`, ); } if (writeScope) assertMemoryWriteScope(old, requireAgentWritableMemoryScope(writeScope)); const result = await saveWorkspaceMemory( db, { accountId: input.accountId, workspaceId: input.workspaceId, text: replacementText, kind: old.kind as KnowledgeMemoryKind, pinned: old.pinned, replacesId: old.id, sessionId: input.sessionId ?? null, origin: input.origin, // Rechecked under the replacement target lock by the common save gate. scope: writeScope ?? agentWritableMemoryScopeOfRow(old) ?? { type: "workspace" }, }, embedder, ); if (result.superseded) { return { action: "superseded", memory: result.superseded, replacement: result.memory, }; } return { action: "updated", memory: result.memory, replacement: null, }; } // No replacement → archive the record. return await withWorkspaceRls(db, input.workspaceId, (scopedDb) => withMemoryScopeRlsContext(scopedDb, readScopes, async () => { const fullId = await resolveWorkspaceMemoryId(scopedDb, input.workspaceId, input.id); if (!fullId) { throw new Error(`Memory "${input.id}" not found in this workspace.`); } const [existing] = await scopedDb .select() .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, fullId), ), ) .limit(1) .for("update"); if (!existing) { throw new Error(`Memory "${input.id}" not found in this workspace.`); } if (input.origin === "agent" && existing.status !== "active") { throw new Error( `Autonomous Memory can archive only active agent-writable records; memory "${existing.id}" has status "${existing.status}". Human-reviewed Knowledge must be changed through its review lifecycle.`, ); } if (writeScope) assertMemoryWriteScope(existing, requireAgentWritableMemoryScope(writeScope)); const correctionReason = cleanDbString(input.reason); const [archived] = await scopedDb .update(schema.knowledgeMemories) .set({ status: "archived", validUntil: new Date(), updatedAt: new Date(), ...(correctionReason ? { metadata: { ...(existing.metadata ?? {}), correctionReason } } : {}), }) .where( and( eq(schema.knowledgeMemories.workspaceId, input.workspaceId), eq(schema.knowledgeMemories.id, fullId), ), ) .returning(); if (!archived) { throw new Error(`Memory "${input.id}" not found in this workspace.`); } return { action: "archived", memory: mapKnowledgeMemory(archived), replacement: null, }; }), ); } export async function searchWorkspaceMemories( db: Database, workspaceId: string, input: WorkspaceMemorySearchInput, embedder?: MemoryEmbedder, ): Promise { const query = requireDbString(input.query, "memory search query"); const mode: WorkspaceMemorySearchMode = input.mode ?? "hybrid"; const limit = Math.min( Math.max(input.limit ?? MEMORY_SEARCH_DEFAULT_LIMIT, 1), MEMORY_SEARCH_MAX_LIMIT, ); const candidateLimit = mode === "hybrid" ? Math.min(limit * 4, 100) : limit; const baseConditions: SQL[] = [ eq(schema.knowledgeMemories.workspaceId, workspaceId), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), ]; if (input.kind) { baseConditions.push(eq(schema.knowledgeMemories.kind, input.kind)); } const readScopes = memoryAgentReadScopes(input.agentScope); if (readScopes) { // Memory off: an agent-scoped search sees nothing rather than the // workspace layer its session was configured not to read. if (readScopes.length === 0) return []; baseConditions.push(memoryScopeVisibilityFilter(readScopes)); } return await withWorkspaceRls(db, workspaceId, (scopedDb) => withMemoryScopeRlsContext(scopedDb, readScopes, async () => { const scored = new Map(); if (mode === "vector" || mode === "hybrid") { try { if (!embedder) { throw new Error("no embedder configured for vector memory search"); } const [vector] = await embedder.embedMany([query]); if (!vector || vector.length === 0) { throw new Error("embedder returned no query vector"); } const distance = sql`${schema.knowledgeMemories.embedding} <=> ${memoryVectorLiteral(vector)}::vector`; const rows = await scopedDb .select({ id: schema.knowledgeMemories.id, distance }) .from(schema.knowledgeMemories) .where( and( ...baseConditions, eq(schema.knowledgeMemories.embeddingModel, embedder.model), sql`${schema.knowledgeMemories.embedding} is not null`, ), ) .orderBy(distance) .limit(candidateLimit); for (const row of rows) { const vectorScore = 1 / (1 + Number(row.distance)); scored.set(row.id, { vectorScore, keywordScore: scored.get(row.id)?.keywordScore ?? null, }); } } catch (error) { if (mode === "vector") { throw error; } console.warn( "workspace memory hybrid search vector component failed; falling back to keyword", { errorClass: "MemorySearchOperationError", errorCode: "memory_hybrid_vector_failed", origin: "db", }, ); } } if (mode === "keyword" || mode === "hybrid") { const rank = sql`ts_rank_cd(to_tsvector('simple', ${schema.knowledgeMemories.text}), plainto_tsquery('simple', ${query}))`; const rows = await scopedDb .select({ id: schema.knowledgeMemories.id, rank }) .from(schema.knowledgeMemories) .where( and( ...baseConditions, sql`to_tsvector('simple', ${schema.knowledgeMemories.text}) @@ plainto_tsquery('simple', ${query})`, ), ) .orderBy(desc(rank)) .limit(candidateLimit); for (const row of rows) { const rankValue = Number(row.rank); const keywordScore = Number.isFinite(rankValue) && rankValue > 0 ? rankValue / (rankValue + 1) : 0; const prev = scored.get(row.id); scored.set(row.id, { vectorScore: prev?.vectorScore ?? null, keywordScore, }); } } const ranked = [...scored.entries()] .map(([id, { vectorScore, keywordScore }]) => { const matchType: WorkspaceMemorySearchMode = vectorScore !== null && keywordScore !== null ? "hybrid" : vectorScore !== null ? "vector" : "keyword"; const vector = vectorScore ?? 0; const keyword = keywordScore ?? 0; const score = mode === "vector" ? vector : mode === "keyword" ? keyword : Math.min(1, 0.65 * vector + 0.35 * keyword + (matchType === "hybrid" ? 0.1 : 0)); return { id, score: Number(score.toFixed(6)), matchType, vectorScore, keywordScore, }; }) .sort( (left, right) => right.score - left.score || (right.vectorScore ?? 0) - (left.vectorScore ?? 0) || (right.keywordScore ?? 0) - (left.keywordScore ?? 0), ) .slice(0, limit); if (ranked.length === 0) { return []; } // Bump usage_count/last_used_at for the returned rows (NOT updated_at — search // must not reshuffle the working set's recency order). Returns the fresh rows. const ids = ranked.map((entry) => entry.id); const bumped = await scopedDb .update(schema.knowledgeMemories) .set({ usageCount: sql`${schema.knowledgeMemories.usageCount} + 1`, lastUsedAt: new Date(), }) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), inArray(schema.knowledgeMemories.id, ids), ), ) .returning(); const byId = new Map(bumped.map((row) => [row.id, row] as const)); const results: WorkspaceMemorySearchResult[] = []; for (const entry of ranked) { const row = byId.get(entry.id); if (!row) { continue; } results.push({ memory: mapKnowledgeMemory(row), score: entry.score, matchType: entry.matchType, vectorScore: entry.vectorScore, keywordScore: entry.keywordScore, }); } return results; }), ); } // Render the per-turn working-set block for a workspace. Returns null when the // workspace's memory setting is off (injection no-ops); the empty-state block // when memory is on but there are zero visible records; otherwise the populated // block. Pure rendering lives in memory-domain.ts. export async function resolveWorkspaceMemoryBlock( db: Database, workspaceId: string, ): Promise { const [workspace] = await db .select({ settings: schema.workspaces.settings }) .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if ( !workspace || !resolveWorkspaceMemoryEnabled(workspace.settings) || resolveWorkspaceMemoryPromptMode() === "retrieval_only" ) { return null; } const records = await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb .select({ id: schema.knowledgeMemories.id, kind: schema.knowledgeMemories.kind, text: schema.knowledgeMemories.text, textCodecVersion: schema.knowledgeMemories.textCodecVersion, pinned: schema.knowledgeMemories.pinned, }) .from(schema.knowledgeMemories) .where( and( eq(schema.knowledgeMemories.workspaceId, workspaceId), inArray(schema.knowledgeMemories.status, agentVisibleMemoryStatuses), ne(schema.knowledgeMemories.kind, "episodic"), ), ) .orderBy(desc(schema.knowledgeMemories.pinned), desc(schema.knowledgeMemories.updatedAt)) .limit(MEMORY_BLOCK_RECORD_LIMIT), ); if (records.length === 0) { return WORKSPACE_MEMORY_BLOCK_EMPTY; } const blockRecords: MemoryBlockRecord[] = records.map((row) => ({ id: row.id, kind: row.kind as KnowledgeMemoryKind, text: fromPostgresLosslessText(row.text, row.textCodecVersion), pinned: row.pinned, })); return renderWorkspaceMemoryBlock(blockRecords) ?? WORKSPACE_MEMORY_BLOCK_EMPTY; } export async function createSocialConnection( db: Database, input: CreateSocialConnectionInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); const [row] = await scopedDb .insert(schema.socialConnections) .values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, provider: input.provider, accountHandle: input.accountHandle, accountName: input.accountName ?? null, externalAccountId: input.externalAccountId ?? null, status: input.status, scopes: input.scopes ?? [], credentialRef: input.credentialRef ?? null, credentialEncrypted: input.credentialEncrypted ?? null, tokenMetadata: input.tokenMetadata ?? {}, metadata: input.metadata ?? {}, }) .returning(); if (!row) { throw new Error("Failed to create social connection"); } return mapSocialConnection(row); }, ); } /** * OAuth-callback persistence: reconnecting the same provider account replaces * the stored credential and revives the connection instead of failing on the * (workspace, provider, handle) unique index. */ export async function upsertSocialOAuthConnection( db: Database, input: UpsertSocialOAuthConnectionInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); if (input.expectedConnection) { const [updated] = await scopedDb .update(schema.socialConnections) .set({ accountHandle: input.accountHandle, accountName: input.accountName ?? null, status: "connected", scopes: input.scopes, credentialEncrypted: input.credentialEncrypted, tokenMetadata: input.tokenMetadata ?? {}, updatedAt: new Date(), }) .where( and( eq(schema.socialConnections.accountId, input.accountId), eq(schema.socialConnections.workspaceId, input.workspaceId), eq(schema.socialConnections.id, input.expectedConnection.id), eq(schema.socialConnections.version, input.expectedConnection.version), eq(schema.socialConnections.provider, input.provider), input.subjectId ? eq(schema.socialConnections.subjectId, input.subjectId) : isNull(schema.socialConnections.subjectId), input.externalAccountId ? eq(schema.socialConnections.externalAccountId, input.externalAccountId) : sql`false`, ), ) .returning(); if (!updated) throw new Error( "Social connection changed; authorize the same account again from current state", ); return mapSocialConnection(updated); } const [row] = await scopedDb .insert(schema.socialConnections) .values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, provider: input.provider, accountHandle: input.accountHandle, accountName: input.accountName ?? null, externalAccountId: input.externalAccountId ?? null, status: "connected", scopes: input.scopes, credentialEncrypted: input.credentialEncrypted, tokenMetadata: input.tokenMetadata ?? {}, }) .onConflictDoUpdate({ target: input.subjectId ? [ schema.socialConnections.workspaceId, schema.socialConnections.subjectId, schema.socialConnections.provider, ] : [ schema.socialConnections.workspaceId, schema.socialConnections.provider, schema.socialConnections.accountHandle, ], targetWhere: input.subjectId ? sql`subject_id is not null` : sql`subject_id is null`, set: { accountId: input.accountId, accountHandle: input.accountHandle, accountName: input.accountName ?? null, externalAccountId: input.externalAccountId ?? null, status: "connected", scopes: input.scopes, credentialEncrypted: input.credentialEncrypted, tokenMetadata: input.tokenMetadata ?? {}, updatedAt: new Date(), }, }) .returning(); if (!row) { throw new Error("Failed to upsert social connection"); } return mapSocialConnection(row); }, ); } /** * Host-side credential read for the social API client. Deliberately not part * of mapSocialConnection so the encrypted bundle never rides along on list or * MCP responses. */ export async function loadSocialConnectionCredential( db: Database, workspaceId: string, connectionId: string, subjectId?: string | null, ): Promise<{ connection: SocialConnection; credentialEncrypted: string | null; } | null> { return await withSocialConnectionSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.socialConnections) .where( and( eq(schema.socialConnections.workspaceId, workspaceId), eq(schema.socialConnections.id, connectionId), socialConnectionSubjectVisibility(subjectId), ), ) .limit(1); if (!row) { return null; } return { connection: mapSocialConnection(row), credentialEncrypted: row.credentialEncrypted, }; }); } export async function updateSocialConnectionCredential( db: Database, input: UpdateSocialConnectionCredentialInput, ): Promise { return await withSocialConnectionSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => { const audited = input.audit && input.status === "disabled" ? input.audit : null; const [prior] = audited ? await scopedDb .select({ status: schema.socialConnections.status }) .from(schema.socialConnections) .where( and( eq(schema.socialConnections.workspaceId, input.workspaceId), eq(schema.socialConnections.id, input.connectionId), socialConnectionSubjectVisibility(input.subjectId), ), ) .for("update") : []; const [row] = await scopedDb .update(schema.socialConnections) .set({ ...(input.credentialEncrypted !== undefined ? { credentialEncrypted: input.credentialEncrypted } : {}), ...(input.status !== undefined ? { status: input.status } : {}), ...(input.tokenMetadata !== undefined ? { tokenMetadata: input.tokenMetadata } : {}), updatedAt: new Date(), }) .where( and( eq(schema.socialConnections.workspaceId, input.workspaceId), eq(schema.socialConnections.id, input.connectionId), socialConnectionSubjectVisibility(input.subjectId), ), ) .returning(); if (!row) return null; if (audited && prior && prior.status !== "disabled") { await insertDisconnectAuditEventInScope(scopedDb, { accountId: row.accountId, workspaceId: row.workspaceId, action: CONNECTION_DISCONNECTED_AUDIT_ACTION, actor: audited, target: { type: "social_connection", id: row.id, provider: row.provider }, details: { ownership: row.subjectId ? "personal" : "workspace", accountHandle: row.accountHandle, }, }); } return mapSocialConnection(row); }, ); } // List/get never select credential_encrypted (same posture as the broker // `connections` helpers): the ciphertext must not ride into API-process memory // on every list, where one added debug log or row spread would expose it. const { credentialEncrypted: _socialCredentialColumn, ...socialConnectionPublicColumns } = getTableColumns(schema.socialConnections); export async function listSocialConnections( db: Database, workspaceId: string, limit = 100, subjectId?: string | null, ): Promise { return await withSocialConnectionSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const rows = await scopedDb .select(socialConnectionPublicColumns) .from(schema.socialConnections) .where( and( eq(schema.socialConnections.workspaceId, workspaceId), socialConnectionSubjectVisibility(subjectId), ), ) .orderBy(desc(schema.socialConnections.createdAt)) .limit(limit); return rows.map(mapSocialConnection); }); } export async function getSocialConnection( db: Database, workspaceId: string, connectionId: string, subjectId?: string | null, ): Promise { return await withSocialConnectionSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const [row] = await scopedDb .select(socialConnectionPublicColumns) .from(schema.socialConnections) .where( and( eq(schema.socialConnections.workspaceId, workspaceId), eq(schema.socialConnections.id, connectionId), socialConnectionSubjectVisibility(subjectId), ), ) .limit(1); return row ? mapSocialConnection(row) : null; }); } export async function requireSocialConnection( db: Database, workspaceId: string, connectionId: string, subjectId?: string | null, ): Promise { const connection = await getSocialConnection(db, workspaceId, connectionId, subjectId); if (!connection) { throw new Error(`Social connection not found: ${connectionId}`); } return connection; } export async function createSocialPost( db: Database, input: CreateSocialPostInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); const connection = await requireSocialConnection( scopedDb, input.workspaceId, input.connectionId, input.subjectId, ); const [row] = await scopedDb .insert(schema.socialPosts) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, provider: connection.provider, externalPostId: input.externalPostId ?? null, url: input.url ?? null, authorHandle: input.authorHandle ?? connection.accountHandle, text: input.text, publishedAt: input.publishedAt, metrics: input.metrics ?? {}, raw: input.raw ?? {}, }) .returning(); if (!row) { throw new Error("Failed to create social post"); } return mapSocialPost(row); }, ); } /** * Idempotent bulk ingest for provider sync: rows already present under the * (workspace, connection, external post id) unique index are skipped, so a * scheduled re-sync never duplicates or fails. */ export async function recordSyncedSocialPosts( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; subjectId?: string | null; posts: Array<{ externalPostId: string; url?: string | null; authorHandle?: string | null; text: string; publishedAt: Date; metrics?: Record; raw?: Record; }>; }, ): Promise<{ inserted: number; skipped: number }> { if (input.posts.length === 0) { return { inserted: 0, skipped: 0 }; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); const connection = await requireSocialConnection( scopedDb, input.workspaceId, input.connectionId, input.subjectId, ); const rows = await scopedDb .insert(schema.socialPosts) .values( input.posts.map((post) => ({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, provider: connection.provider, externalPostId: post.externalPostId, url: post.url ?? null, authorHandle: post.authorHandle ?? connection.accountHandle, text: post.text, publishedAt: post.publishedAt, metrics: post.metrics ?? {}, raw: post.raw ?? {}, })), ) .onConflictDoNothing({ target: [ schema.socialPosts.workspaceId, schema.socialPosts.connectionId, schema.socialPosts.externalPostId, ], }) .returning({ id: schema.socialPosts.id }); return { inserted: rows.length, skipped: input.posts.length - rows.length, }; }, ); } export async function listSocialPosts( db: Database, options: { workspaceId: string; subjectId?: string | null; connectionIds?: string[]; since?: Date; limit?: number; }, ): Promise { const conditions: SQL[] = [eq(schema.socialPosts.workspaceId, options.workspaceId)]; if (options.connectionIds?.length) { conditions.push(inArray(schema.socialPosts.connectionId, options.connectionIds)); } if (options.since) { conditions.push(gte(schema.socialPosts.publishedAt, options.since)); } const limit = options.limit ?? 100; return await withSocialConnectionSubjectRls( db, options.workspaceId, options.subjectId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.socialPosts) .where(and(...conditions)) .orderBy(desc(schema.socialPosts.publishedAt)) .limit(limit); return rows.map(mapSocialPost); }, ); } export async function createScheduledTask( db: Database, input: CreateScheduledTaskInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const frozenCreator = await frozenSessionCreatorForInsert(scopedDb, input); await setScheduledTaskAuthorityRlsContext(scopedDb, frozenCreator); await input.beforeCreateCommit?.(scopedDb); // Low-level callers without a frozen snapshot have no exact accepting // human here, so they resolve the organization or workspace pool. const sharedTaskPool = input.xaiProviderAccountAuthoritySnapshot === undefined || input.claudeProviderAccountAuthoritySnapshot === undefined ? await sharedPoolSubscriptionAuthoritySnapshotsInTransaction(scopedDb, input.workspaceId) : null; // v2 for every provider on the shared core (M3 PR 3b, EP-T15; M4 // X2b): frozen once, at creation, for the exact // accepting human under the acceptance rule; firings copy it and never // recompute it. Non-human creators freeze the empty value; nothing // before the cutover. const taskOwnerSubjectId = (input.action?.kind ?? "agent_turn") === "agent_turn" ? (frozenCreator.initiatingHumanSubjectId ?? (frozenCreator.initiator.kind === "subject" ? frozenCreator.initiator.subjectId : null)) : null; const creatorTurn = input.createdByActor ? ( await scopedDb .select({ authority: schema.sessionTurns.subscriptionAuthority }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.accountId, input.accountId), eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.createdByActor.sessionId), eq(schema.sessionTurns.id, input.createdByActor.turnId), ), ) .limit(1) )[0] : null; const [taskDestination] = input.createdByActor && taskOwnerSubjectId ? await rawRows<{ eligible: boolean }>( scopedDb, sql`select case when ${input.targetSessionId ?? null}::uuid is null then get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) = 'personal' else exists (select 1 from sessions destination where destination.account_id = ${input.accountId}::uuid and destination.workspace_id = ${input.workspaceId}::uuid and destination.id = ${input.targetSessionId ?? null}::uuid and destination.owner_subject_id = ${taskOwnerSubjectId} and (destination.visibility = 'user_private' or get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) = 'personal')) end as eligible`, ) : []; const taskSubscriptionAuthority = input.createdByActor ? subscriptionAuthorityV2OrEmpty(taskDestination?.eligible ? creatorTurn?.authority : null) : await coreSubscriptionAuthorityV2ForScheduledTaskInTransaction(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, reusableSessionId: input.targetSessionId ?? null, acceptingSubjectId: taskOwnerSubjectId, }); const [row] = await scopedDb .insert(schema.scheduledTasks) .values({ id: input.id, accountId: input.accountId, workspaceId: input.workspaceId, billingOrigin: input.billingOrigin ?? null, name: input.name, ownerSubjectId: (input.action?.kind ?? "agent_turn") === "agent_turn" ? (frozenCreator.initiatingHumanSubjectId ?? (frozenCreator.initiator.kind === "subject" ? frozenCreator.initiator.subjectId : null)) : null, status: input.status, visibility: input.visibility ?? "workspace_shared", schedule: input.schedule, temporalScheduleId: input.temporalScheduleId, runMode: input.runMode, overlapPolicy: input.overlapPolicy, action: input.action ?? { kind: "agent_turn" }, agentConfig: input.agentConfig, ...creatorColumns(frozenCreator), xaiProviderAccountAuthoritySnapshot: input.xaiProviderAccountAuthoritySnapshot ?? sharedTaskPool!.xai, claudeProviderAccountAuthoritySnapshot: input.claudeProviderAccountAuthoritySnapshot ?? sharedTaskPool!.claude, subscriptionAuthority: taskSubscriptionAuthority, creatorFirstPartyMcpTools: input.creatorPolicy?.firstPartyMcpTools ?? null, creatorFirstPartyMcpPermissions: input.creatorPolicy?.firstPartyMcpPermissions ? canonicalSecretPermissions(input.creatorPolicy.firstPartyMcpPermissions) : null, creatorSessionPolicy: scheduledTaskCreatorSessionPolicyForInsert(input.creatorPolicy), reusableSessionId: input.targetSessionId ?? null, // The column default is { mode: "all" }; omit it so rows written // before 0739 (and older-migration fixtures) keep working. ...(input.vaultPolicy !== undefined ? { vaultPolicy: input.vaultPolicy } : {}), rigId: input.rigId ?? null, metadata: input.metadata, ...(input.creatorLocked ? { creatorLocked: true } : {}), }) .returning(); if (!row) { throw new Error("Failed to create scheduled task"); } await scopedDb.execute(sql`select freeze_scheduled_task_personal_resources( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${row.authorityRevision}::bigint )`); await scopedDb.execute(sql`select record_scheduled_task_revision_authority( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${row.authorityRevision}::bigint )`); await copySubscriptionAuthorityCompatInTransaction(scopedDb, [ { kind: "scheduled_task", workspaceId: row.workspaceId, id: row.id }, { kind: "scheduled_task_revision", workspaceId: row.workspaceId, id: row.id, taskAuthorityRevision: row.authorityRevision, }, ]); await input.captureLinkAuthority?.(scopedDb, mapScheduledTask(row)); return mapScheduledTask(row); }, ); } /** * Trusted mutation seam: verify an exact agent attempt before deriving its * human. A creator-locked task matches only its own creator principal, and * never an agent attempt. */ export async function scheduledTaskMutationOwnerMatches( db: Database, input: { workspaceId: string; taskId: string; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; }, ): Promise { return withWorkspaceRls(db, input.workspaceId, async (tx) => { const actor = await frozenSessionCreatorForInsert(tx, input); const [task] = await tx .select({ owner: schema.scheduledTasks.ownerSubjectId, creatorLocked: schema.scheduledTasks.creatorLocked, creatorSubjectId: schema.scheduledTasks.createdBySubjectId, }) .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), ), ) .for("update") .limit(1); if (!task) return false; if (task.creatorLocked) { return !input.createdByActor && actor.initiator.subjectId === task.creatorSubjectId; } const subject = actor.initiatingHumanSubjectId ?? (actor.initiator.kind === "subject" ? actor.initiator.subjectId : null); return task.owner === null || task.owner === subject; }); } /** * The person a request reads schedules as: the human caller, or the human an * exact agent attempt acts for. Null for keys and services, which own no * Only me schedules. */ export async function scheduledTaskViewerSubject( db: Database, input: { workspaceId: string; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; }, ): Promise { return withWorkspaceRls(db, input.workspaceId, async (tx) => { const actor = await frozenSessionCreatorForInsert(tx, input); const subject = actor.initiatingHumanSubjectId ?? (actor.initiator.kind === "subject" ? actor.initiator.subjectId : null); return subject && !subject.startsWith("api_key:") ? subject : null; }); } /** * The one meeting a built-in meeting-summary chat may read and write * (recordings.ts), or null for every other chat. Only an exact live attempt * of an Only me summary reads as its owner, the meeting's owner whom * `createSession` proved; a workspace summary reads as no one, so it sees * only shared meetings. */ export async function meetingSummarySessionScope( db: Database, input: { workspaceId: string; sessionId: string; createdByActor?: AgentSessionCreationActor | null; }, ): Promise<{ recordingId: string; ownerSubjectId: string | null } | null> { return withWorkspaceRls(db, input.workspaceId, async (tx) => { const [session] = await tx .select({ createdByKind: schema.sessions.createdByKind, createdBySubjectId: schema.sessions.createdBySubjectId, policyRole: schema.sessions.policyRole, metadata: schema.sessions.metadata, visibility: schema.sessions.visibility, ownerSubjectId: schema.sessions.ownerSubjectId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session) return null; const recordingId = session.metadata[MEETING_SUMMARY_RECORDING_METADATA_KEY]; if ( session.createdByKind !== "service" || session.createdBySubjectId !== MEETING_SUMMARY_SUBJECT_ID || session.policyRole !== MEETING_SUMMARY_POLICY_ROLE || typeof recordingId !== "string" ) { return null; } const exactAttempt = input.createdByActor?.sessionId === input.sessionId; if (exactAttempt) await frozenSessionCreatorForInsert(tx, input); return { recordingId, ownerSubjectId: exactAttempt && session.visibility === "user_private" ? session.ownerSubjectId : null, }; }); } /** * Admin view of other people's Only me schedules: owner, cadence, status, last * run and the last 30 days of usage. Never the name, prompt, settings or runs. */ export async function listPrivateScheduledTaskSummaries( db: Database, input: { workspaceId: string; /** Leave out this person's own schedules; they see those in full. */ excludeOwnerSubjectId: string | null; /** Read just this schedule. */ taskId?: string; now?: Date; limit?: number; }, ): Promise { const since = new Date((input.now ?? new Date()).getTime() - 30 * 24 * 60 * 60 * 1000); const limit = Math.min(Math.max(input.limit ?? 200, 1), 500); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await rawRows<{ id: string; owner_subject_id: string; owner_name: string | null; status: string; schedule: unknown; created_at: Date | string; last_run_at: Date | string | null; runs: number | string; credit_micros: number | string; provider_micros: number | string; }>( scopedDb, // Their runs and usage are usually hidden by chat visibility; this // definer function returns only these aggregates. sql`select * from opengeni_private.private_scheduled_task_summaries( nullif(current_setting('opengeni.account_id', true), '')::uuid, ${input.workspaceId}::uuid, ${input.excludeOwnerSubjectId}::text, ${input.taskId ?? null}::uuid, ${since.toISOString()}::timestamptz, ${limit}::integer )`, ); const iso = (value: Date | string | null) => value === null ? null : new Date(value).toISOString(); return rows.map((row) => ({ id: row.id, ownerSubjectId: row.owner_subject_id, ownerName: row.owner_name, status: row.status as ScheduledTaskStatus, schedule: row.schedule as ScheduledTaskScheduleSpec, lastRunAt: iso(row.last_run_at), last30Days: { runs: Number(row.runs), creditUsd: Number(row.credit_micros) / 1_000_000, estimatedProviderUsd: Number(row.provider_micros) / 1_000_000, }, createdAt: iso(row.created_at)!, })); }); } /** * Pause someone else's Only me schedule as a workspace admin, even when it * posts into a chat the admin cannot see. Returns false when no such schedule * exists. Runs check the stored status, so the paused schedule stops firing. */ export async function pausePrivateScheduledTask( db: Database, input: { workspaceId: string; taskId: string; excludeOwnerSubjectId: string | null }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await rawRows<{ paused: boolean }>( scopedDb, sql`select opengeni_private.pause_private_scheduled_task( nullif(current_setting('opengeni.account_id', true), '')::uuid, ${input.workspaceId}::uuid, ${input.excludeOwnerSubjectId}::text, ${input.taskId}::uuid ) as paused`, ); return row?.paused === true; }); } /** The stored audience of a chat this request can already see, or null. */ export async function getVisibleSessionTenancyVisibility( db: Database, workspaceId: string, sessionId: string, ): Promise<"user_private" | "workspace_shared" | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ visibility: schema.sessions.visibility }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!row) return null; return row.visibility === "user_private" ? "user_private" : "workspace_shared"; }); } /** * A chat's audience and, for an Only me chat, its owner; null when the * caller cannot see the chat. */ export async function getVisibleSessionAudience( db: Database, workspaceId: string, sessionId: string, ): Promise<{ visibility: "user_private" | "workspace_shared"; ownerSubjectId: string | null; } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ visibility: schema.sessions.visibility, ownerSubjectId: schema.sessions.ownerSubjectId, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!row) return null; return row.visibility === "user_private" ? { visibility: "user_private", ownerSubjectId: row.ownerSubjectId ?? null } : { visibility: "workspace_shared", ownerSubjectId: null }; }); } export async function updateScheduledTask( db: Database, workspaceId: string, taskId: string, input: UpdateScheduledTaskInput, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [previousLinkRevision] = await scopedDb .select({ authorityRevision: schema.scheduledTasks.authorityRevision, executionDigest: schema.scheduledTasks.executionDigest, creatorFirstPartyMcpTools: schema.scheduledTasks.creatorFirstPartyMcpTools, }) .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), ), ) .for("update") .limit(1); if ( input.expectedExecutionDigest !== undefined && previousLinkRevision?.executionDigest !== input.expectedExecutionDigest ) { throw new ScheduledTaskHeadChangedError(); } if (input.creatorFirstPartyPolicy && !previousLinkRevision?.creatorFirstPartyMcpTools) { throw new Error("only an agent-created scheduled task has a creator tool policy to refresh"); } if ( input.refreshPersonalResourceAuthority && input.clonePersonalResourceAuthorityFromRevision !== undefined ) { throw new Error("scheduled task authority refresh and clone are mutually exclusive"); } if (input.refreshPersonalResourceAuthority) { const frozenUpdater = await frozenSessionCreatorForInsert(scopedDb, { workspaceId, ...(input.authorityUpdatedBy ? { createdBy: input.authorityUpdatedBy } : {}), ...(input.authorityUpdatedByContext ? { createdByContext: input.authorityUpdatedByContext } : {}), ...(input.authorityUpdatedByActor !== undefined ? { createdByActor: input.authorityUpdatedByActor } : {}), }); await setScheduledTaskAuthorityRlsContext(scopedDb, frozenUpdater); } await input.beforeUpdateCommit?.(scopedDb); const [row] = await scopedDb .update(schema.scheduledTasks) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.status !== undefined ? { status: input.status } : {}), ...(input.visibility !== undefined ? { visibility: input.visibility } : {}), ...(input.schedule !== undefined ? { schedule: input.schedule } : {}), ...(input.runMode !== undefined ? { runMode: input.runMode } : {}), ...(input.overlapPolicy !== undefined ? { overlapPolicy: input.overlapPolicy } : {}), ...(input.action !== undefined ? { action: input.action } : {}), ...(input.agentConfig !== undefined ? { agentConfig: input.agentConfig } : {}), ...(input.targetSessionId !== undefined ? { reusableSessionId: input.targetSessionId } : input.reusableSessionId !== undefined ? { reusableSessionId: input.reusableSessionId } : {}), ...(input.rigId !== undefined ? { rigId: input.rigId } : {}), ...(input.vaultPolicy !== undefined ? { vaultPolicy: input.vaultPolicy } : {}), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}), ...(input.creatorFirstPartyPolicy ? { creatorFirstPartyMcpTools: [...input.creatorFirstPartyPolicy.firstPartyMcpTools], creatorFirstPartyMcpPermissions: canonicalSecretPermissions( input.creatorFirstPartyPolicy.firstPartyMcpPermissions, ), } : {}), ...(input.refreshPersonalResourceAuthority || input.clonePersonalResourceAuthorityFromRevision !== undefined ? { authorityRevision: sql`${schema.scheduledTasks.authorityRevision} + 1`, } : {}), updatedAt: new Date(), }) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), isNull(schema.scheduledTasks.deletedAt), ), ) .returning(); if (!row) { throw new Error(`Scheduled task not found: ${taskId}`); } if (input.refreshPersonalResourceAuthority) { await scopedDb.execute(sql`select freeze_scheduled_task_personal_resources( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${row.authorityRevision}::bigint )`); await scopedDb.execute(sql`select record_scheduled_task_revision_authority( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${row.authorityRevision}::bigint )`); } else if (input.clonePersonalResourceAuthorityFromRevision !== undefined) { await scopedDb.execute(sql`select clone_scheduled_task_personal_resource_authority( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${input.clonePersonalResourceAuthorityFromRevision}::bigint, ${row.authorityRevision}::bigint )`); await scopedDb.execute(sql`select clone_scheduled_task_revision_authority( ${row.accountId}::uuid, ${row.workspaceId}::uuid, ${row.id}::uuid, ${input.clonePersonalResourceAuthorityFromRevision}::bigint, ${row.authorityRevision}::bigint )`); } if ( input.refreshPersonalResourceAuthority || input.clonePersonalResourceAuthorityFromRevision !== undefined ) { await copySubscriptionAuthorityCompatInTransaction(scopedDb, [ { kind: "scheduled_task_revision", workspaceId: row.workspaceId, id: row.id, taskAuthorityRevision: row.authorityRevision, }, ]); } const mapped = mapScheduledTask(row); if (input.captureLinkAuthority) await input.captureLinkAuthority(scopedDb, mapped); else if (previousLinkRevision) await cloneExternalLinkTaskAuthority( scopedDb, mapped, input.clonePersonalResourceAuthorityFromRevision ?? previousLinkRevision.authorityRevision, ); return mapped; }); } export async function getScheduledTask( db: Database, workspaceId: string, taskId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), isNull(schema.scheduledTasks.deletedAt), ), ) .limit(1); return row ? mapScheduledTask(row) : null; }); } /** Internal delete-recovery lookup; public list/get surfaces hide tombstones. */ export async function getScheduledTaskIncludingDeleted( db: Database, workspaceId: string, taskId: string, ): Promise<(ScheduledTask & { deletedAt: string | null }) | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), ), ) .limit(1); return row ? { ...mapScheduledTask(row), deletedAt: row.deletedAt?.toISOString() ?? null, } : null; }); } /** Task-first deletion lock; call only inside the surrounding lifecycle transaction. */ export async function getScheduledTaskIncludingDeletedForUpdate( db: Database, workspaceId: string, taskId: string, ): Promise<(ScheduledTask & { deletedAt: string | null }) | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), ), ) .for("update") .limit(1); return row ? { ...mapScheduledTask(row), deletedAt: row.deletedAt?.toISOString() ?? null, } : null; }); } /** * Lock the incident task definition inside the dispatch transaction. Account * authority belongs to the accepted occurrence, never the mutable task head. */ export async function requireScheduledTaskIncidentAuthorityInTransaction( tx: Database, input: { workspaceId: string; taskId: string }, ): Promise { const [row] = await tx .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), isNull(schema.scheduledTasks.deletedAt), ), ) .for("update") .limit(1); if (!row) throw new Error(`Scheduled task not found: ${input.taskId}`); return mapScheduledTask(row); } export async function getScheduledTaskXaiProviderAccountAuthoritySnapshot( db: Database, workspaceId: string, taskId: string, ): Promise { return getAcceptedSubscriptionTaskAuthority(db, "xai", workspaceId, taskId); } /** * The frozen creator boundary of a scheduled task. Read at fire time (and by * recovery of an already-admitted run, which is why a tombstoned task still * answers). The session policy column is written once at create and never * updated, so recovery re-reads it deterministically. The tools and * permissions change only through the owner's explicit access refresh, and an * admitted run never re-reads them: its accepted execution carries the * resolved tools and permissions. Null when the task has no row at all. */ export async function getScheduledTaskCreatorPolicy( db: Database, workspaceId: string, taskId: string, ): Promise { return (await listScheduledTaskCreatorPolicies(db, workspaceId, [taskId])).get(taskId) ?? null; } /** Batch form of {@link getScheduledTaskCreatorPolicy}; tasks without a row are absent. */ export async function listScheduledTaskCreatorPolicies( db: Database, workspaceId: string, taskIds: readonly string[], ): Promise> { if (taskIds.length === 0) return new Map(); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ id: schema.scheduledTasks.id, firstPartyMcpTools: schema.scheduledTasks.creatorFirstPartyMcpTools, firstPartyMcpPermissions: schema.scheduledTasks.creatorFirstPartyMcpPermissions, sessionPolicy: schema.scheduledTasks.creatorSessionPolicy, }) .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), inArray(schema.scheduledTasks.id, [...new Set(taskIds)]), ), ); return new Map(rows.map((row) => [row.id, scheduledTaskCreatorPolicyFromRow(row)])); }); } /** Additive JSON on the existing write-once creator column; no new storage seam. */ function scheduledTaskCreatorSessionPolicyForInsert( policy: ScheduledTaskCreatorPolicy | null | undefined, ): ScheduledTaskCreatorSessionPolicy | SQL | null { if (policy?.credentialRestriction === undefined) return policy?.sessionPolicy ?? null; if (policy.credentialRestriction !== "developer_setup") { throw new Error("Malformed scheduled task credential restriction"); } // The Drizzle column's original type describes the three legacy session // fields. Serialize the additive JSON explicitly, including restriction-only // snapshots without manufacturing a session policy or changing defaults. return sql`${JSON.stringify({ ...policy.sessionPolicy, credentialRestriction: policy.credentialRestriction, })}::jsonb`; } function scheduledTaskCreatorPolicyFromRow(row: { firstPartyMcpTools: FirstPartyMcpToolName[] | null; firstPartyMcpPermissions: Permission[] | null; sessionPolicy: { agentAccess?: string | null; scopeSubjectId?: string | null; memoryScope?: string | null; credentialRestriction?: unknown; } | null; }): ScheduledTaskCreatorPolicy { const hasRestriction = Boolean( row.sessionPolicy && Object.hasOwn(row.sessionPolicy, "credentialRestriction"), ); if (hasRestriction && row.sessionPolicy?.credentialRestriction !== "developer_setup") { throw new Error("Malformed scheduled task credential restriction"); } const restrictionOnly = hasRestriction && !["agentAccess", "scopeSubjectId", "memoryScope"].some((key) => Object.hasOwn(row.sessionPolicy!, key), ); return { firstPartyMcpTools: row.firstPartyMcpTools ? [...row.firstPartyMcpTools] : null, firstPartyMcpPermissions: row.firstPartyMcpPermissions ? [...row.firstPartyMcpPermissions] : null, ...(hasRestriction ? { credentialRestriction: "developer_setup" as const } : {}), sessionPolicy: row.sessionPolicy && !restrictionOnly ? { agentAccess: row.sessionPolicy.agentAccess ?? null, scopeSubjectId: row.sessionPolicy.scopeSubjectId ?? null, memoryScope: row.sessionPolicy.memoryScope === "session" ? "off" : (row.sessionPolicy.memoryScope ?? null), } : null, }; } export async function requireScheduledTask( db: Database, workspaceId: string, taskId: string, ): Promise { const task = await getScheduledTask(db, workspaceId, taskId); if (!task) { throw new Error(`Scheduled task not found: ${taskId}`); } return task; } export class ScheduledTaskTargetConflictError extends Error { constructor() { super("scheduled task target changed during dispatch"); this.name = "ScheduledTaskTargetConflictError"; } } /** * DB-only delivery fence used inside the system-update source transaction. * The task row is locked after the target session row, so a concurrent retarget * linearizes before or after the complete scheduled occurrence instead of * delivering one fire to a stale session snapshot. */ export async function requireScheduledTaskTargetInTransaction( tx: Database, input: { workspaceId: string; taskId: string; targetSessionId: string; }, ): Promise { const [row] = await tx .select({ runMode: schema.scheduledTasks.runMode, reusableSessionId: schema.scheduledTasks.reusableSessionId, }) .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), isNull(schema.scheduledTasks.deletedAt), ), ) .for("update") .limit(1); if ( !row || row.runMode !== "existing_session" || row.reusableSessionId !== input.targetSessionId ) { throw new ScheduledTaskTargetConflictError(); } } /** Authoritative current targets, batched after session visibility has been resolved. */ export async function scheduledSessionIds( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { return (await sessionScheduleTargets(db, workspaceId, sessionIds)).scheduled; } /** * Whether a schedule can still start a run on its own: it is active, and its * cadence has a run left after `now`. A paused schedule, a one-time schedule * whose time has passed (fired or missed), an interval past its end, and a * manual task never fire by themselves. Malformed specs are not upcoming. * * A one-time run stops being upcoming as soon as `runAt` passes, even while * 0761's 24-hour missed-run catch-up could still start it: the indicator shows * what is ahead, not a late catch-up. Nothing writes at `runAt`/`endAt`, so a * list read before that moment keeps the icon until its next refresh. */ export function scheduledTaskHasUpcomingRun( task: { status: string; schedule: unknown }, now: Date, ): boolean { if (task.status !== "active") return false; const spec = task.schedule && typeof task.schedule === "object" ? (task.schedule as Record) : null; const later = (value: unknown) => { const at = typeof value === "string" ? Date.parse(value) : Number.NaN; return Number.isFinite(at) && at > now.getTime(); }; switch (spec?.type) { case "once": return later(spec.runAt); case "interval": return spec.endAt === undefined || spec.endAt === null || later(spec.endAt); case "calendar": return true; default: return false; } } export type SessionScheduleTargets = { /** Sessions any current schedule targets, including paused and finished ones. */ scheduled: Set; /** Sessions an active schedule targets that can still start a run. */ upcoming: Set; /** * Sessions an active automation targets that an event can still start: it * has an active event trigger and, if it runs once, has not run yet. */ waitingForEvents: Set; /** * What the automations the reader can see are waiting for, per session that * one of them can still continue. Sessions without such an automation are * absent. Null when the reader was not given schedule access at all. */ waits: Map | null; }; const CALENDAR_DAYS = [ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", ] as const; const wallClockFormatters = new Map(); function wallClockFormatter(timeZone: string): Intl.DateTimeFormat | null { const cached = wallClockFormatters.get(timeZone); if (cached) return cached; try { const formatter = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", hourCycle: "h23", }); if (wallClockFormatters.size >= 256) wallClockFormatters.clear(); wallClockFormatters.set(timeZone, formatter); return formatter; } catch { return null; } } /** The wall clock in a time zone at an instant, as a UTC timestamp of the same fields. */ function wallClockAsUtc(formatter: Intl.DateTimeFormat, instantMs: number): number { const parts: Record = {}; for (const part of formatter.formatToParts(new Date(instantMs))) { if (part.type !== "literal") parts[part.type] = Number(part.value); } return Date.UTC(parts.year!, parts.month! - 1, parts.day!, parts.hour!, parts.minute!); } /** The instant a wall-clock minute happens in a time zone (the later side of a DST gap). */ function zonedWallClockToUtc(formatter: Intl.DateTimeFormat, wallClockMs: number): number { let guess = wallClockMs; for (let step = 0; step < 3; step += 1) { const drift = wallClockMs - wallClockAsUtc(formatter, guess); if (drift === 0) break; guess += drift; } return guess; } /** * A schedule's next run strictly after `now`, as the Temporal schedule it * becomes fires it: a one-time run at its instant, intervals aligned to * `startAt` (otherwise the Unix epoch) until `endAt`, and calendar runs at a * wall-clock time in the schedule's time zone. Null for a manual schedule, a * one-time run that has passed, an interval past its end, or a malformed spec. */ export function scheduledTaskNextRunAt(schedule: unknown, now: Date): Date | null { const spec = schedule && typeof schedule === "object" ? (schedule as Record) : null; const nowMs = now.getTime(); const instant = (value: unknown) => (typeof value === "string" ? Date.parse(value) : Number.NaN); switch (spec?.type) { case "once": { const at = instant(spec.runAt); return Number.isFinite(at) && at > nowMs ? new Date(at) : null; } case "interval": { const everyMs = Number(spec.everySeconds) * 1_000; if (!Number.isSafeInteger(everyMs) || everyMs <= 0) return null; const startMs = spec.startAt == null ? null : instant(spec.startAt); const endMs = spec.endAt == null ? null : instant(spec.endAt); if (Number.isNaN(startMs) || Number.isNaN(endMs)) return null; const phase = startMs === null ? 0 : ((startMs % everyMs) + everyMs) % everyMs; const from = Math.max(nowMs + 1, startMs ?? Number.NEGATIVE_INFINITY); const next = phase + Math.ceil((from - phase) / everyMs) * everyMs; return endMs !== null && next > endMs ? null : new Date(next); } case "calendar": { const hour = Number(spec.hour); const minute = Number(spec.minute); if (!Number.isInteger(hour) || !Number.isInteger(minute)) return null; const formatter = wallClockFormatter( typeof spec.timeZone === "string" && spec.timeZone ? spec.timeZone : "UTC", ); if (!formatter) return null; const days = Array.isArray(spec.daysOfWeek) && spec.daysOfWeek.length > 0 ? new Set(spec.daysOfWeek) : null; const today = new Date(wallClockAsUtc(formatter, nowMs)); for (let offset = 0; offset <= 7; offset += 1) { const day = Date.UTC( today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() + offset, ); if (days && !days.has(CALENDAR_DAYS[new Date(day).getUTCDay()]!)) continue; const run = zonedWallClockToUtc(formatter, day + (hour * 60 + minute) * 60_000); if (run > nowMs) return new Date(run); } return null; } default: return null; } } type AutomationWaitRow = { taskId: string; sessionId: string | null; status: string; schedule: unknown; createdAt: Date; visibility: string; ownerSubjectId: string | null; triggerStatus: string | null; triggerPosition: number | null; eventTypes: string[] | null; sourceId: string | null; sourceKind: string | null; sourceName: string | null; sourceVisibility: string | null; sourceOwnerSubjectId: string | null; eventsOnce: boolean | null; eventsCompletedAt: Date | null; hasEventSettings: string | null; }; type AutomationWaitEvent = NonNullable; /** Both lists of event types as one, in order; every event covers the rest. */ function mergedWaitEventTypes(left: readonly string[], right: readonly string[]): string[] { if (left.includes("*") || right.includes("*")) return ["*"]; return [...new Set([...left, ...right])]; } /** * What the automations the reader can see are waiting for, per session. A * trusted reader (undefined) sees every automation and source; null sees * shared ones; a subject also sees their own. */ function automationWaitSummaries( rows: readonly AutomationWaitRow[], now: Date, viewerSubjectId: string | null | undefined, ): Map { const visible = (visibility: string | null, owner: string | null, shared: string) => viewerSubjectId === undefined || visibility === shared || (viewerSubjectId !== null && owner === viewerSubjectId); const tasks = new Map(); for (const row of rows) { if (!row.sessionId || !visible(row.visibility, row.ownerSubjectId, "workspace_shared")) continue; const task = tasks.get(row.taskId) ?? { sessionId: row.sessionId, rows: [] }; task.rows.push(row); tasks.set(row.taskId, task); } const ordered = [...tasks.values()].sort( (left, right) => left.rows[0]!.createdAt.getTime() - right.rows[0]!.createdAt.getTime() || left.rows[0]!.taskId.localeCompare(right.rows[0]!.taskId), ); const waits = new Map(); // Each chat's events by source id ("" for the ones the reader can't see). const sourceEvents = new Map>(); for (const { sessionId, rows: taskRows } of ordered) { const task = taskRows[0]!; if (task.status !== "active" || (task.eventsOnce && task.eventsCompletedAt)) continue; const nextRun = scheduledTaskHasUpcomingRun(task, now) ? scheduledTaskNextRunAt(task.schedule, now) : null; const triggers = task.hasEventSettings ? taskRows .filter((row) => row.triggerStatus === "active") .sort((left, right) => left.triggerPosition! - right.triggerPosition!) : []; if (!nextRun && triggers.length === 0) continue; const wait = waits.get(sessionId) ?? { nextRunAt: null, event: null, events: [], automations: 0, }; wait.automations += 1; if (nextRun && (!wait.nextRunAt || nextRun.getTime() < Date.parse(wait.nextRunAt))) { wait.nextRunAt = nextRun.toISOString(); } const bySource = sourceEvents.get(sessionId) ?? new Map(); for (const trigger of triggers) { const source = trigger.sourceId && trigger.sourceKind && trigger.sourceName !== null && visible(trigger.sourceVisibility, trigger.sourceOwnerSubjectId, "workspace") ? { kind: trigger.sourceKind as EventSourceKind, name: trigger.sourceName } : null; const eventTypes = trigger.eventTypes ?? []; wait.event ??= { source, eventTypes: [...eventTypes] }; const key = source ? trigger.sourceId! : ""; const entry = bySource.get(key); if (entry) { entry.eventTypes = mergedWaitEventTypes(entry.eventTypes, eventTypes); } else { const added = { source, eventTypes: mergedWaitEventTypes([], eventTypes) }; bySource.set(key, added); wait.events!.push(added); } } sourceEvents.set(sessionId, bySource); waits.set(sessionId, wait); } return waits; } export async function sessionScheduleTargets( db: Database, workspaceId: string, sessionIds: string[], options: { now?: Date; /** * Who is reading, for the wait summaries. Omitted (trusted callers): every * automation and source is described. Given: it is asked only when an * Only me automation or a private source targets these sessions; null * then describes shared ones, a subject also their own. */ viewer?: () => Promise; } = {}, ): Promise { const now = options.now ?? new Date(); if (sessionIds.length === 0) return { scheduled: new Set(), upcoming: new Set(), waitingForEvents: new Set(), waits: new Map(), }; const rows = await withWorkspaceRls(db, workspaceId, async (scopedDb) => scopedDb .select({ taskId: schema.scheduledTasks.id, sessionId: schema.scheduledTasks.reusableSessionId, status: schema.scheduledTasks.status, schedule: schema.scheduledTasks.schedule, createdAt: schema.scheduledTasks.createdAt, visibility: schema.scheduledTasks.visibility, ownerSubjectId: schema.scheduledTasks.ownerSubjectId, triggerStatus: schema.eventTriggers.status, triggerPosition: schema.eventTriggers.position, eventTypes: schema.eventTriggers.eventTypes, sourceId: schema.eventSources.id, sourceKind: schema.eventSources.kind, sourceName: schema.eventSources.name, sourceVisibility: schema.eventSources.visibility, sourceOwnerSubjectId: schema.eventSources.ownerSubjectId, eventsOnce: schema.scheduledTaskEventSettings.once, eventsCompletedAt: schema.scheduledTaskEventSettings.completedAt, hasEventSettings: schema.scheduledTaskEventSettings.taskId, }) .from(schema.scheduledTasks) .leftJoin(schema.eventTriggers, eq(schema.eventTriggers.taskId, schema.scheduledTasks.id)) .leftJoin(schema.eventSources, eq(schema.eventSources.id, schema.eventTriggers.sourceId)) .leftJoin( schema.scheduledTaskEventSettings, eq(schema.scheduledTaskEventSettings.taskId, schema.scheduledTasks.id), ) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), isNull(schema.scheduledTasks.deletedAt), inArray(schema.scheduledTasks.runMode, ["existing_session", "reusable_session"]), anyOf(schema.scheduledTasks.reusableSessionId, sessionIds), ), ), ); const restricted = rows.some( (row) => row.visibility !== "workspace_shared" || (row.sourceVisibility !== null && row.sourceVisibility !== "workspace"), ); const viewerSubjectId = options.viewer ? (restricted ? await options.viewer() : null) : undefined; const targets: SessionScheduleTargets = { scheduled: new Set(), upcoming: new Set(), waitingForEvents: new Set(), waits: automationWaitSummaries(rows, now, viewerSubjectId), }; for (const row of rows) { if (!row.sessionId) continue; targets.scheduled.add(row.sessionId); if (scheduledTaskHasUpcomingRun(row, now)) targets.upcoming.add(row.sessionId); if (row.status === "active" && row.triggerStatus === "active" && !row.eventsCompletedAt) { targets.waitingForEvents.add(row.sessionId); } } return targets; } export async function listScheduledTasks( db: Database, workspaceId: string, limit = 100, offset = 0, sessionId?: string, /** * The person reading. Omitted (trusted internal callers only): every * schedule. Given: shared schedules plus this person's own Only me ones; * null reads shared schedules only. */ viewerSubjectId?: string | null, /** Only automations whose runs are chats with this agent (`agentConfig.agentId`). */ filters: { agentId?: string } = {}, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), isNull(schema.scheduledTasks.deletedAt), ...(filters.agentId ? [sql`${schema.scheduledTasks.agentConfig} ->> 'agentId' = ${filters.agentId}`] : []), ...(viewerSubjectId === undefined ? [] : [ viewerSubjectId === null ? eq(schema.scheduledTasks.visibility, "workspace_shared") : or( eq(schema.scheduledTasks.visibility, "workspace_shared"), eq(schema.scheduledTasks.ownerSubjectId, viewerSubjectId), ), ]), ...(sessionId ? [ eq(schema.scheduledTasks.reusableSessionId, sessionId), inArray(schema.scheduledTasks.runMode, ["existing_session", "reusable_session"]), ] : []), ), ) .orderBy(desc(schema.scheduledTasks.createdAt), desc(schema.scheduledTasks.id)) .limit(limit) .offset(offset); return rows.map(mapScheduledTask); }); } /** * Active agent-turn tasks with person-pinned connector accounts, owned by * `subjectId` (and, with `includeOwnerless`, tasks without an owner). Only * these can have a pinned account become unusable, so the owner's access * attention list checks each one's pins. A caller without a subject passes an * empty id, which owns nothing. */ export async function listActiveScheduledTasksWithPinnedAccounts( db: Database, workspaceId: string, input: { subjectId: string; includeOwnerless: boolean; limit: number }, ): Promise { const limit = Math.max(1, Math.min(500, Math.floor(input.limit))); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const owner = eq(schema.scheduledTasks.ownerSubjectId, input.subjectId); const rows = await scopedDb .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), isNull(schema.scheduledTasks.deletedAt), eq(schema.scheduledTasks.status, "active"), sql`${schema.scheduledTasks.action} ->> 'kind' = 'agent_turn'`, sql`(case when jsonb_typeof(${schema.scheduledTasks.agentConfig} -> 'pinnedAccounts') = 'array' then jsonb_array_length(${schema.scheduledTasks.agentConfig} -> 'pinnedAccounts') else 0 end) > 0`, input.includeOwnerless ? or(owner, isNull(schema.scheduledTasks.ownerSubjectId)) : owner, ), ) .orderBy(desc(schema.scheduledTasks.createdAt), desc(schema.scheduledTasks.id)) .limit(limit); return rows.map(mapScheduledTask); }); } export async function deleteScheduledTask( db: Database, workspaceId: string, taskId: string, ): Promise<{ cleanup: TemporalScheduleCleanupClaim | null; changed: boolean }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { return await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [task] = await tx .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), ), ) .for("update") .limit(1); if (!task) return { cleanup: null, changed: false }; const changed = task.deletedAt === null; if (!task.deletedAt) { await tx .update(schema.scheduledTasks) .set({ status: "paused", deletedAt: new Date(), reusableSessionId: null, updatedAt: new Date(), }) .where( and( eq(schema.scheduledTasks.workspaceId, workspaceId), eq(schema.scheduledTasks.id, taskId), isNull(schema.scheduledTasks.deletedAt), ), ); } const claimId = randomUUID(); const [cleanup] = await tx .insert(schema.temporalScheduleCleanupOutbox) .values({ accountId: task.accountId, workspaceId: task.workspaceId, temporalScheduleId: task.temporalScheduleId, scheduledTaskId: null, connectorCleanupSubjectId: null, connectorCleanupSnapshot: null, connectorCleanupCompletedAt: null, claimId, claimUntil: sql`now() + interval '15 seconds'`, attemptCount: 1, }) .onConflictDoNothing({ target: schema.temporalScheduleCleanupOutbox.temporalScheduleId, }) .returning({ id: schema.temporalScheduleCleanupOutbox.id, accountId: schema.temporalScheduleCleanupOutbox.accountId, workspaceId: schema.temporalScheduleCleanupOutbox.workspaceId, temporalScheduleId: schema.temporalScheduleCleanupOutbox.temporalScheduleId, scheduledTaskId: schema.temporalScheduleCleanupOutbox.scheduledTaskId, connectorCleanupSubjectId: schema.temporalScheduleCleanupOutbox.connectorCleanupSubjectId, connectorCleanupSnapshot: schema.temporalScheduleCleanupOutbox.connectorCleanupSnapshot, connectorCleanupCompletedAt: schema.temporalScheduleCleanupOutbox.connectorCleanupCompletedAt, attemptCount: schema.temporalScheduleCleanupOutbox.attemptCount, }); return { cleanup: cleanup ? { ...cleanup, claimId } : null, changed, }; }); }); } /** * An archived chat can never continue, so its one-time automations are * retired when its undo window ends: run-once event automations and one-time * scheduled runs, whether still ahead or already run. They belong to the chat * (a "wake me when" from that chat or one of its sub-chats). Repeating * automations are not retired; they keep Archive from starting at all. Any * Temporal schedule is removed by the cleanup pump from the durable outbox * row each deletion writes. Returns the retired automation ids. */ export async function retireArchivedChatWaits( db: Database, input: { workspaceId: string; rootSessionId: string }, ): Promise { const task = schema.scheduledTasks; const settings = schema.scheduledTaskEventSettings; const rows = await withWorkspaceRls(db, input.workspaceId, async (scoped) => scoped .select({ id: task.id }) .from(task) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, task.workspaceId), eq(schema.sessions.id, task.reusableSessionId), ), ) .leftJoin(settings, eq(settings.taskId, task.id)) .where( and( eq(task.workspaceId, input.workspaceId), isNull(task.deletedAt), eq(task.runMode, "existing_session"), eq(schema.sessions.rootSessionId, input.rootSessionId), or( eq(settings.once, true), and(isNull(settings.taskId), sql`${task.schedule} ->> 'type' = 'once'`), ), ), ) .orderBy(task.id), ); const retired: string[] = []; for (const row of rows) { const deletion = await deleteScheduledTask(db, input.workspaceId, row.id); if (!deletion.changed) continue; await wakeScheduledTaskEventSubscriptions(db, input.workspaceId, row.id); retired.push(row.id); } return retired; } /** A terminal refusal is evidence, not accepted execution or permission to retry. */ export async function recordScheduledTaskAdmissionFailure( db: Database, input: { workspaceId: string; taskId: string; taskAuthorityRevision: number; taskExecutionDigest: string; triggerType: ScheduledTaskTriggerType; producerKey: string; scheduledAt?: Date | null; diagnostic: ConnectionAccountSelectionDiagnostic; }, ): Promise { const diagnostic = ConnectionAccountSelectionDiagnostic.parse(input.diagnostic); if (!input.producerKey.trim()) throw new Error("scheduled refusal requires producer identity"); return await withWorkspaceRls(db, input.workspaceId, async (tx) => { // Same task lock as accepted admission; both outcomes share the existing // producer unique key. A committed winner is immutable even after repair. const [task] = await tx .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), ), ) .for("update") .limit(1); if (!task) throw new Error("Scheduled task not found"); const readPrior = async () => { const [prior] = await tx .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.producerKey, input.producerKey), ), ) .limit(1); if (prior && (prior.taskId !== input.taskId || prior.triggerType !== input.triggerType)) { throw new Error("scheduled task run producer identity changed"); } return prior; }; const prior = await readPrior(); if (prior) return mapScheduledTaskRun(prior); if ( task.status !== "active" || task.deletedAt || task.authorityRevision !== input.taskAuthorityRevision || task.executionDigest !== input.taskExecutionDigest ) { throw new Error("scheduled task changed before refusal recording"); } const now = new Date(); const [inserted] = await tx .insert(schema.scheduledTaskRuns) .values({ accountId: task.accountId, workspaceId: input.workspaceId, taskId: task.id, taskAuthorityRevision: input.taskAuthorityRevision, taskExecutionDigest: input.taskExecutionDigest, triggerType: input.triggerType, producerKey: input.producerKey, scheduledAt: input.scheduledAt ?? null, firedAt: now, completedAt: now, actionKind: "agent_turn", status: "failed", error: "connection_account_unavailable", admissionDiagnostic: diagnostic, }) .onConflictDoNothing({ target: [schema.scheduledTaskRuns.workspaceId, schema.scheduledTaskRuns.producerKey], where: sql`${schema.scheduledTaskRuns.producerKey} is not null`, }) .returning(); const result = inserted ?? (await readPrior()); if (!result) throw new Error("scheduled refusal receipt missing"); return mapScheduledTaskRun(result); }); } /** Reasons a scheduled occurrence is refused before accepting execution. */ export type ScheduledTaskAdmissionRefusalReason = | "scheduled_authority_unavailable" | "machine_target_unavailable" | "machine_enrollment_inactive" | "rig_version_unavailable" | "scheduled_model_unavailable" | "insufficient_credits" | "allowance_exhausted" | "monthly_model_cost_limit" | "monthly_agent_run_limit" | "session_usage_limit"; /** * Record a refused occurrence as an immutable run receipt under its producer * identity (migration 0539). A transient refusal is `skipped`, a terminal one * `failed`; neither carries accepted execution. An existing receipt for the * producer wins, so redelivery never duplicates a run: the caller replays it. */ export async function recordScheduledTaskAdmissionRefusal( db: Database, input: { workspaceId: string; taskId: string; taskAuthorityRevision: number; taskExecutionDigest: string; triggerType: ScheduledTaskTriggerType; producerKey: string; scheduledAt?: Date | null; reason: ScheduledTaskAdmissionRefusalReason; retryable: boolean; }, ): Promise { if (!input.producerKey.trim()) throw new Error("scheduled refusal requires producer identity"); const refusal = ScheduledTaskAdmissionRefusal.parse({ version: 1, reason: input.reason, retryable: input.retryable, }); return await withWorkspaceRls(db, input.workspaceId, async (tx) => { const [task] = await tx .select() .from(schema.scheduledTasks) .where( and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), ), ) .for("update") .limit(1); if (!task) throw new Error("Scheduled task not found"); const readPrior = async () => { const [prior] = await tx .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.producerKey, input.producerKey), ), ) .limit(1); if (prior && (prior.taskId !== input.taskId || prior.triggerType !== input.triggerType)) { throw new Error("scheduled task run producer identity changed"); } return prior; }; const prior = await readPrior(); if (prior) return mapScheduledTaskRun(prior); if ( task.status !== "active" || task.deletedAt || task.authorityRevision !== input.taskAuthorityRevision || task.executionDigest !== input.taskExecutionDigest ) { throw new Error("scheduled task changed before refusal recording"); } const now = new Date(); const [inserted] = await tx .insert(schema.scheduledTaskRuns) .values({ accountId: task.accountId, workspaceId: input.workspaceId, taskId: task.id, taskAuthorityRevision: input.taskAuthorityRevision, taskExecutionDigest: input.taskExecutionDigest, triggerType: input.triggerType, producerKey: input.producerKey, scheduledAt: input.scheduledAt ?? null, firedAt: now, completedAt: now, actionKind: "agent_turn", status: refusal.retryable ? "skipped" : "failed", error: refusal.reason, admissionRefusal: refusal, }) .onConflictDoNothing({ target: [schema.scheduledTaskRuns.workspaceId, schema.scheduledTaskRuns.producerKey], where: sql`${schema.scheduledTaskRuns.producerKey} is not null`, }) .returning(); const result = inserted ?? (await readPrior()); if (!result) throw new Error("scheduled refusal receipt missing"); return mapScheduledTaskRun(result); }); } export async function createScheduledTaskRun( db: Database, input: { runId?: string; workspaceId: string; taskId: string; /** Exact task snapshot read by the dispatching worker. */ taskAuthorityRevision?: number | null; /** Exact task snapshot read by the dispatching worker. */ taskExecutionDigest?: string | null; triggerType: ScheduledTaskTriggerType; /** Stable Temporal workflow/activity producer identity for replay repair. */ producerKey?: string | null; scheduledAt?: Date | null; firedAt?: Date; acceptedExecutionSnapshot?: ScheduledTaskRunAcceptedExecutionType | null; /** * Trusted database-only admission seam for a fresh agent occurrence. * Throwing rolls back the run insert; exact producer replay skips it. */ beforeFreshAgentRunCommit?: (tx: Database) => Promise; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { if ((input.taskAuthorityRevision == null) !== (input.taskExecutionDigest == null)) { throw new Error("scheduled task run execution binding is incomplete"); } let guardedAcceptedExecution: ScheduledTaskRunAcceptedExecutionType | null = null; let replayedProducerRow: typeof schema.scheduledTaskRuns.$inferSelect | undefined; if (input.beforeFreshAgentRunCommit) { if (!input.producerKey || !input.acceptedExecutionSnapshot) { throw new Error( "scheduled fresh agent run commit guard requires a producer-bound accepted execution", ); } guardedAcceptedExecution = ScheduledTaskRunAcceptedExecution.parse( input.acceptedExecutionSnapshot, ); const readProducerReplay = async () => { const [row] = await scopedDb .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.producerKey, input.producerKey!), ), ) .limit(1); return row; }; replayedProducerRow = await readProducerReplay(); // Fresh custom-model admission must precede the task row lock. Material // task updates take the same advisory lock before updating that row, and // acquiring them in the opposite order can deadlock behind a queued // exclusive custom-model mutation. An exact durable producer replay // still skips the live-model check so retirement cannot invalidate work // that was already accepted. if (!replayedProducerRow) { try { await input.beforeFreshAgentRunCommit(scopedDb); } catch (error) { // An overlapping producer can commit after the unlocked pre-read // while this retry waits behind a queued retirement. Re-read before // surfacing the mutable-model denial so the committed winner remains // replayable instead of becoming a false terminal rejection. replayedProducerRow = await readProducerReplay(); if (!replayedProducerRow) throw error; } } } const taskFilter = and( eq(schema.scheduledTasks.workspaceId, input.workspaceId), eq(schema.scheduledTasks.id, input.taskId), isNull(schema.scheduledTasks.deletedAt), ); const [taskRow] = input.beforeFreshAgentRunCommit ? await scopedDb.select().from(schema.scheduledTasks).where(taskFilter).for("update").limit(1) : await scopedDb.select().from(schema.scheduledTasks).where(taskFilter).limit(1); if (!taskRow) { throw new Error(`Scheduled task not found: ${input.taskId}`); } const actionKind = ((taskRow.action as ScheduledTaskAction | null)?.kind ?? "agent_turn") satisfies ScheduledTaskActionKind; const acceptedExecutionSnapshot = actionKind === "agent_turn" ? (guardedAcceptedExecution ?? ScheduledTaskRunAcceptedExecution.parse(input.acceptedExecutionSnapshot)) : null; if (input.beforeFreshAgentRunCommit && actionKind !== "agent_turn") { throw new Error( "scheduled fresh agent run commit guard requires a producer-bound accepted execution", ); } if ( acceptedExecutionSnapshot && (acceptedExecutionSnapshot.task.id !== input.taskId || acceptedExecutionSnapshot.task.workspaceId !== input.workspaceId || acceptedExecutionSnapshot.task.accountId !== taskRow.accountId || acceptedExecutionSnapshot.task.authorityRevision !== input.taskAuthorityRevision || acceptedExecutionSnapshot.task.executionDigest !== input.taskExecutionDigest) ) { throw new Error("scheduled task accepted execution binding changed"); } if (replayedProducerRow) { if ( replayedProducerRow.actionKind !== "agent_turn" || replayedProducerRow.taskId !== input.taskId || replayedProducerRow.triggerType !== input.triggerType ) { throw new Error("scheduled task run producer identity changed"); } if ( replayedProducerRow.taskAuthorityRevision !== input.taskAuthorityRevision || replayedProducerRow.taskExecutionDigest !== input.taskExecutionDigest ) { throw new Error("scheduled task run execution binding changed"); } if ( stableJson(replayedProducerRow.acceptedExecutionSnapshot) !== stableJson(acceptedExecutionSnapshot) ) { throw new Error("scheduled task run accepted execution changed"); } } const values = { ...(input.runId ? { id: input.runId } : {}), accountId: taskRow.accountId, workspaceId: taskRow.workspaceId, taskId: input.taskId, taskAuthorityRevision: input.taskAuthorityRevision ?? null, taskExecutionDigest: input.taskExecutionDigest ?? null, triggerType: input.triggerType, producerKey: input.producerKey ?? null, scheduledAt: input.scheduledAt ?? null, firedAt: input.firedAt ?? new Date(), status: "queued" as const, actionKind, acceptedExecutionSnapshot, acceptedExecutionDigest: acceptedExecutionSnapshot ? sql`encode(digest(convert_to(${JSON.stringify( acceptedExecutionSnapshot, )}::jsonb::text, 'UTF8'), 'sha256'), 'hex')` : null, }; let inserted = replayedProducerRow; if (!inserted) { if (actionKind === "agent_turn" && input.producerKey && acceptedExecutionSnapshot) { const [created] = await rawRows<{ id: string }>( scopedDb, sql`select create_scheduled_agent_run_with_admission( ${input.runId ?? randomUUID()}::uuid, ${taskRow.accountId}::uuid, ${taskRow.workspaceId}::uuid, ${input.taskId}::uuid, ${input.taskAuthorityRevision}::bigint, ${input.taskExecutionDigest}::text, ${input.triggerType}::text, ${input.producerKey}::text, ${input.scheduledAt?.toISOString() ?? null}::timestamptz, ${(input.firedAt ?? new Date()).toISOString()}::timestamptz, ${JSON.stringify(acceptedExecutionSnapshot)}::jsonb ) as id`, ); if (created) { [inserted] = await scopedDb .select() .from(schema.scheduledTaskRuns) .where(eq(schema.scheduledTaskRuns.id, created.id)) .limit(1); } } else { [inserted] = input.producerKey ? await scopedDb .insert(schema.scheduledTaskRuns) .values(values) .onConflictDoNothing({ target: [ schema.scheduledTaskRuns.workspaceId, schema.scheduledTaskRuns.producerKey, ], where: sql`${schema.scheduledTaskRuns.producerKey} is not null`, }) .returning() : await scopedDb.insert(schema.scheduledTaskRuns).values(values).returning(); } } const [row] = inserted ? [inserted] : await scopedDb .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.producerKey, input.producerKey!), ), ) .limit(1); if (!row) { throw new Error("Failed to create scheduled task run"); } if ( input.taskAuthorityRevision != null && (row.taskAuthorityRevision !== input.taskAuthorityRevision || row.taskExecutionDigest !== input.taskExecutionDigest) ) { throw new Error("scheduled task run execution binding changed"); } if (row.taskId !== input.taskId || row.triggerType !== input.triggerType) { throw new Error("scheduled task run producer identity changed"); } if ( acceptedExecutionSnapshot && stableJson(row.acceptedExecutionSnapshot) !== stableJson(acceptedExecutionSnapshot) ) { throw new Error("scheduled task run accepted execution changed"); } return mapScheduledTaskRun(row); }); } export async function getScheduledTaskRunAcceptedExecution( db: Database, input: { workspaceId: string; runId: string }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ snapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, digest: schema.scheduledTaskRuns.acceptedExecutionDigest, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.id, input.runId), ), ) .limit(1); if (!row?.snapshot || !row.digest) return null; return ScheduledTaskRunAcceptedExecution.parse(row.snapshot); }); } export async function getScheduledTaskRunByProducerKey( db: Database, input: { workspaceId: string; taskId: string; triggerType: ScheduledTaskTriggerType; producerKey: string; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.producerKey, input.producerKey), ), ) .limit(1); if (!row) return null; if (row.taskId !== input.taskId || row.triggerType !== input.triggerType) { throw new Error("scheduled task run producer identity changed"); } return mapScheduledTaskRun(row); }); } export type ScheduledTaskRunPersonalResourceAuthority = { taskId: string; taskAuthorityRevision: number; executionDigest: string; initiatingHumanSubjectId: string; resources: Array<{ resourceKind: "variable_set" | "rig"; resourceId: string; resourceVersionId: string; selectionSources: string[]; authorityId: string; authorityGeneration: number; grantId: string; grantGeneration: number; grantMode: "once" | "session" | "always"; }>; }; export async function getScheduledTaskRunPersonalResourceAuthority( db: Database, input: { accountId: string; workspaceId: string; runId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await rawRows<{ taskId: string; taskAuthorityRevision: number; executionDigest: string; initiatingHumanSubjectId: string; resourceKind: "variable_set" | "rig"; resourceId: string; resourceVersionId: string; selectionSources: string[]; authorityId: string; authorityGeneration: number; grantId: string; grantGeneration: number; grantMode: "once" | "session" | "always"; }>( scopedDb, sql`select task_id as "taskId", task_authority_revision::int as "taskAuthorityRevision", execution_digest as "executionDigest", initiating_human_subject_id as "initiatingHumanSubjectId", resource_kind as "resourceKind", resource_id as "resourceId", resource_version_id as "resourceVersionId", selection_sources as "selectionSources", authority_id as "authorityId", authority_generation::int as "authorityGeneration", grant_id as "grantId", grant_generation::int as "grantGeneration", grant_mode as "grantMode" from scheduled_task_run_personal_resource_authority( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid )`, ); const first = rows[0]; if (!first) return null; return { taskId: first.taskId, taskAuthorityRevision: Number(first.taskAuthorityRevision), executionDigest: first.executionDigest, initiatingHumanSubjectId: first.initiatingHumanSubjectId, resources: rows.map((row) => ({ resourceKind: row.resourceKind, resourceId: row.resourceId, resourceVersionId: row.resourceVersionId, selectionSources: row.selectionSources, authorityId: row.authorityId, authorityGeneration: Number(row.authorityGeneration), grantId: row.grantId, grantGeneration: Number(row.grantGeneration), grantMode: row.grantMode, })), }; }, ); } export async function materializeScheduledTaskReusableSessionFromRun( db: Database, input: { accountId: string; workspaceId: string; taskId: string; runId: string; sessionId: string; sourceTaskAuthorityRevision: number; sourceExecutionDigest: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await rawRows<{ authorityRevision: number }>( scopedDb, sql`select materialize_scheduled_task_reusable_session_from_run( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.taskId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid, ${input.sourceTaskAuthorityRevision}::bigint, ${input.sourceExecutionDigest}::text )::int as "authorityRevision"`, ); if (!row) { throw new Error("scheduled reusable-session materialization returned no revision"); } // A new head revision cloned from the source one (skipped when none was inserted). await copySubscriptionAuthorityCompatInTransaction(scopedDb, [ { kind: "scheduled_task_revision", workspaceId: input.workspaceId, id: input.taskId, taskAuthorityRevision: Number(row.authorityRevision), }, ]); const materializedTask = await getScheduledTask(scopedDb, input.workspaceId, input.taskId); if (!materializedTask || materializedTask.authorityRevision !== Number(row.authorityRevision)) throw new Error("scheduled materialization revision changed"); await cloneExternalLinkTaskAuthority( scopedDb, materializedTask, input.sourceTaskAuthorityRevision, ); return Number(row.authorityRevision); }, ); } export async function bindScheduledTaskRunSessionInTransaction( tx: Database, input: { accountId: string; workspaceId: string; runId: string; sessionId: string; }, ): Promise { await withRlsContext( tx, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await rawRows( scopedDb, sql`select bind_scheduled_task_run_session( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid )`, ); }, ); } async function scheduledTaskRunCausalHumanInTransaction( tx: Database, input: { accountId: string; workspaceId: string; runId: string }, ): Promise { const [row] = await rawRows<{ initiatingHumanSubjectId: string }>( tx, sql`select initiating_human_subject_id as "initiatingHumanSubjectId" from scheduled_task_run_personal_resource_authority( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid ) limit 1`, ); const [connectionRow] = await rawRows<{ initiatingHumanSubjectId: string }>( tx, sql`select scheduled_task_run_connection_authority_subject( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid ) as "initiatingHumanSubjectId"`, ); if ( row?.initiatingHumanSubjectId && connectionRow?.initiatingHumanSubjectId && row.initiatingHumanSubjectId !== connectionRow.initiatingHumanSubjectId ) { throw new Error("scheduled authority classes have different causal humans"); } const [acceptedRow] = await tx .select({ acceptedExecutionSnapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.id, input.runId), eq(schema.scheduledTaskRuns.accountId, input.accountId), eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), ), ) .limit(1); const acceptedCausalSubject = acceptedRow?.acceptedExecutionSnapshot ? ScheduledTaskRunAcceptedExecution.parse(acceptedRow.acceptedExecutionSnapshot) .causalHumanSubjectId : null; const authoritySubject = row?.initiatingHumanSubjectId ?? connectionRow?.initiatingHumanSubjectId ?? null; if (authoritySubject && acceptedCausalSubject && authoritySubject !== acceptedCausalSubject) { throw new Error("scheduled accepted causal human differs from authority subject"); } return authoritySubject ?? acceptedCausalSubject ?? null; } export async function getScheduledTaskPersonalResourceAuthoritySubject( db: Database, input: { accountId: string; workspaceId: string; taskId: string; taskAuthorityRevision: number; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await rawRows<{ subjectId: string | null }>( scopedDb, sql`select scheduled_task_personal_resource_authority_subject( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.taskId}::uuid, ${input.taskAuthorityRevision}::bigint ) as "subjectId"`, ); return row?.subjectId ?? null; }, ); } export async function getScheduledTaskRevisionAuthoritySubject( db: Database, input: { accountId: string; workspaceId: string; taskId: string; taskAuthorityRevision: number; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await rawRows<{ subjectId: string | null }>( scopedDb, sql`select scheduled_task_revision_authority_subject( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.taskId}::uuid, ${input.taskAuthorityRevision}::bigint ) as "subjectId"`, ); return row?.subjectId ?? null; }, ); } export { getScheduledTaskRevisionAuthority } from "./scheduled-task-revision-authority"; /** Failure settlement must not rewrite a source already committed as dispatched. */ export async function markScheduledTaskRunFailedIfQueued( db: Database, workspaceId: string, runId: string, error: string, ): Promise { await withWorkspaceRls(db, workspaceId, async (scopedDb) => { await scopedDb.execute(sql`select transition_scheduled_agent_run( current_setting('opengeni.account_id')::uuid, ${workspaceId}::uuid, ${runId}::uuid, null::uuid, null::uuid, 'failed'::text, ${error}::text )`); }); } export type FailScheduledGeneratedSessionRouteResult = | { action: "failed"; events: SessionEvent[]; sessionReclaimed: boolean; error: string; } | { action: "terminal"; events: []; sessionReclaimed: false; status: "failed" | "skipped"; error: string | null; } | { action: "advanced"; events: []; sessionReclaimed: false; status: "dispatched" | "succeeded"; }; /** * Fail a queued scheduled run after its selected Connected Machine could not be * established. If the exact scheduler-created session has not acquired any * turn, fail that otherwise-orphaned session in the same transaction. A user * cancellation wins for the session row, but the machine failure still owns * the run settlement in this one durable boundary. * * The external liveness probe and sandbox CAS must happen before this DB-only * seam. This transaction serializes the resulting failure with initialization, * cancellation, and a concurrent dispatcher under the canonical * control -> workspace -> session -> scheduled-run lock order. */ export async function failScheduledGeneratedSessionRoute( db: Database, input: { accountId: string; workspaceId: string; taskId: string; runId: string; sessionId: string; error: string; }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const locks = await lockSessionEventWriteRows(scopedDb, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.workspace || !session || session.accountId !== input.accountId) { throw new SessionControlInvariantError( `Scheduled generated session ${input.sessionId} is unavailable`, ); } const [run] = await scopedDb .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.accountId, input.accountId), eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.id, input.runId), eq(schema.scheduledTaskRuns.taskId, input.taskId), eq(schema.scheduledTaskRuns.actionKind, "agent_turn"), ), ) .for("update") .limit(1); if (!run || run.sessionId !== input.sessionId) { throw new SessionControlInvariantError( `Scheduled run ${input.runId} is not bound to generated session ${input.sessionId}`, ); } if (run.status === "failed" || run.status === "skipped") { return { action: "terminal", events: [], sessionReclaimed: false, status: run.status, error: run.error, }; } if (run.status === "dispatched" || run.status === "succeeded") { return { action: "advanced", events: [], sessionReclaimed: false, status: run.status, }; } if (run.status !== "queued") { throw new SessionControlInvariantError( `Scheduled run ${input.runId} has unsupported status ${run.status}`, ); } const [existingTurn] = await scopedDb .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), ), ) .limit(1); const [existingSystemUpdate] = await scopedDb .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), ), ) .limit(1); const schedulerCreatedForRun = session.createdByKind === "service" && session.createdBySubjectId === "scheduler" && session.createdByContext?.scheduledTaskId === input.taskId && session.createdByContext?.scheduledTaskRunId === input.runId && session.metadata?.scheduledTaskId === input.taskId && session.metadata?.scheduledTaskRunId === input.runId; const reclaimSession = schedulerCreatedForRun && (session.status === "queued" || session.status === "idle") && session.activeTurnId === null && existingTurn === undefined && existingSystemUpdate === undefined && (await sessionQueueIsEmptyInTransaction(scopedDb, input.workspaceId, input.sessionId)); let events: SessionEvent[] = []; if (reclaimSession) { const now = new Date(); const [inserted] = await scopedDb .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.status.changed" as const, payload: { status: "failed", code: input.error }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!inserted) { throw new SessionControlInvariantError( `Scheduled generated session ${input.sessionId} failure event was not inserted`, ); } await scopedDb .update(schema.sessions) .set({ status: "failed", activeTurnId: null, compactRequested: false, compactRequestTrigger: null, lastSequence: inserted.sequence, queueVersion: session.queueVersion + 1, updatedAt: now, }) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); events = [mapEvent(inserted)]; } await scopedDb.execute(sql`select transition_scheduled_agent_run( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid, null::uuid, 'failed'::text, ${input.error}::text )`); return { action: "failed", events, sessionReclaimed: reclaimSession, error: input.error, }; }, ); } export async function markScheduledTaskRunSkippedIfQueued( db: Database, input: { workspaceId: string; runId: string; /** Null when the run was skipped before it got a chat. */ sessionId: string | null; error: string; }, ): Promise { await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { await scopedDb.execute(sql`select transition_scheduled_agent_run( current_setting('opengeni.account_id')::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid, null::uuid, 'skipped'::text, ${input.error}::text )`); }); } /** * Whether a workspace Pause holds every new chat in the workspace. A chat * created now could not run, so scheduled work checks this before creating one. */ export async function isWorkspaceAgentActivityPaused( db: Database, workspaceId: string, ): Promise { return withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ state: schema.workspaceInferenceControls.workspaceState }) .from(schema.workspaceInferenceControls) .where(eq(schema.workspaceInferenceControls.workspaceId, workspaceId)); return row?.state === "paused"; }); } /** * Whether the chat of a task's latest earlier run is still working: it has an * active turn, or work queued or waiting in it. A `skip` task that starts a * new chat per run skips an occurrence while this holds. A chat that is idle, * failed, cancelled, gone or only shows an empty queued projection does not * hold it. */ export async function scheduledTaskPreviousRunSessionBusy( db: Database, input: { workspaceId: string; taskId: string; runId: string }, ): Promise { return withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [previous] = await scopedDb .select({ sessionId: schema.sessions.id, status: schema.sessions.status, activeTurnId: schema.sessions.activeTurnId, }) .from(schema.scheduledTaskRuns) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.scheduledTaskRuns.workspaceId), eq(schema.sessions.id, schema.scheduledTaskRuns.sessionId), ), ) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.taskId, input.taskId), ne(schema.scheduledTaskRuns.id, input.runId), isNotNull(schema.scheduledTaskRuns.sessionId), ), ) .orderBy(desc(schema.scheduledTaskRuns.createdAt)) .limit(1); if (!previous) return false; if (previous.activeTurnId !== null) return true; if ( previous.status === "idle" || previous.status === "failed" || previous.status === "cancelled" ) { return false; } if (previous.status !== "queued") return true; return !(await sessionQueueIsEmptyInTransaction( scopedDb, input.workspaceId, previous.sessionId, )); }); } /** Claim-time stale-authority settlement; no model/tool/sandbox work has started. */ export async function markScheduledTaskRunAuthorityRejectedInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; runId: string; error?: string; }, ): Promise { await tx.execute(sql`select transition_scheduled_agent_run( current_setting('opengeni.account_id')::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid, null::uuid, 'failed'::text, ${input.error ?? "incident_responder_under_capable"}::text )`); } function scheduledRunPreclaimDenial( run: | Pick< typeof schema.scheduledTaskRuns.$inferSelect, "status" | "error" | "acceptedExecutionSnapshot" > | undefined, ): string | null { if (!run?.acceptedExecutionSnapshot) return "scheduled_authority_snapshot_missing"; if (run.status === "dispatched") return null; return run.status === "skipped" && (run.error === "scheduled_task_paused_before_claim" || run.error === "scheduled_task_deleted_before_claim") ? "scheduled_task_inactive_before_claim" : "scheduled_run_terminal_before_claim"; } async function validateScheduledTargetExecutionAtClaim( tx: Database, input: { accountId: string; workspaceId: string; session: typeof schema.sessions.$inferSelect; runId: string; }, ): Promise { const [run] = await tx .select({ status: schema.scheduledTaskRuns.status, error: schema.scheduledTaskRuns.error, acceptedExecutionSnapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.id, input.runId), eq(schema.scheduledTaskRuns.accountId, input.accountId), eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.sessionId, input.session.id), ), ) .limit(1) .for("update"); const preclaimDenial = scheduledRunPreclaimDenial(run); if (preclaimDenial) return preclaimDenial; const [liveAuthority] = await rawRows<{ denial: string | null }>( tx, sql`select validate_scheduled_agent_run_live_authority( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid ) as denial`, ); if (liveAuthority?.denial) return liveAuthority.denial; const accepted = ScheduledTaskRunAcceptedExecution.parse(run!.acceptedExecutionSnapshot); const target = accepted.targetSessionExecution; if (!target) return null; const mcpServers = await tx .select({ id: schema.sessionMcpServers.serverId }) .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, input.workspaceId), eq(schema.sessionMcpServers.sessionId, input.session.id), ), ) .orderBy(asc(schema.sessionMcpServers.serverId)); return target.sessionId !== input.session.id || (target.visibility !== input.session.visibility && !(target.visibility === "user_private" && input.session.visibility === "workspace_shared")) || target.authorityEpoch < input.session.executionAuthorityEpoch || target.authorityEpoch > input.session.authorityEpoch || stableJson(target.firstPartyMcpTools) !== stableJson(input.session.firstPartyMcpTools) || stableJson(target.firstPartyMcpPermissions) !== stableJson(input.session.firstPartyMcpPermissions ?? null) || stableJson(target.toolPolicy) !== stableJson(input.session.toolPolicy) || stableJson(target.mcpServerIds) !== stableJson(mcpServers.map((server) => server.id)) || target.toolPolicyVersion !== input.session.toolPolicyVersion || target.rigId !== (input.session.rigId ?? null) || target.rigVersionId !== (input.session.rigVersionId ?? null) || target.maxNestedAgentDepthOverride !== (input.session.maxNestedAgentDepthOverride ?? null) || target.effectiveMaxNestedAgentDepth !== input.session.effectiveMaxNestedAgentDepth ? "scheduled_target_execution_changed" : null; } export async function updateScheduledTaskRun( db: Database, workspaceId: string, runId: string, input: Partial<{ status: ScheduledTaskRunStatus; sessionId: string | null; triggerEventId: string | null; actionKind: ScheduledTaskActionKind; knowledgeSyncRunId: string | null; knowledgeSummary: Record | null; completedAt: Date | null; error: string | null; }>, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .update(schema.scheduledTaskRuns) .set({ ...(input.status !== undefined ? { status: input.status } : {}), ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}), ...(input.triggerEventId !== undefined ? { triggerEventId: input.triggerEventId } : {}), ...(input.actionKind !== undefined ? { actionKind: input.actionKind } : {}), ...(input.knowledgeSyncRunId !== undefined ? { knowledgeSyncRunId: input.knowledgeSyncRunId } : {}), ...(input.knowledgeSummary !== undefined ? { knowledgeSummary: input.knowledgeSummary } : {}), ...(input.completedAt !== undefined ? { completedAt: input.completedAt } : {}), ...(input.error !== undefined ? { error: input.error } : {}), updatedAt: new Date(), }) .where( and( eq(schema.scheduledTaskRuns.workspaceId, workspaceId), eq(schema.scheduledTaskRuns.id, runId), ), ) .returning(); if (!row) { throw new Error(`Scheduled task run not found: ${runId}`); } return mapScheduledTaskRun(row); }); } /** DB-only source mutation callback for durable scheduled delivery. */ export async function settleScheduledTaskRunInTransaction( tx: Database, input: { workspaceId: string; runId: string; sessionId: string; triggerEventId: string | null; status: "dispatched" | "skipped"; error?: string | null; }, ): Promise { await tx.execute(sql`select transition_scheduled_agent_run( current_setting('opengeni.account_id')::uuid, ${input.workspaceId}::uuid, ${input.runId}::uuid, ${input.sessionId}::uuid, ${input.triggerEventId}::uuid, ${input.status}::text, ${input.error ?? null}::text )`); } export async function listScheduledTaskRuns( db: Database, workspaceId: string, taskId: string, limit = 100, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, workspaceId), eq(schema.scheduledTaskRuns.taskId, taskId), ), ) .orderBy(desc(schema.scheduledTaskRuns.createdAt)) .limit(limit); const runs = rows.map(mapScheduledTaskRun); // A dispatched run whose own turn waits on a person is visible as such // instead of looking merely "dispatched" until someone answers. const waits = await scheduledRunHumanWaitsInRlsContext(scopedDb, workspaceId, { runIds: runs.filter((run) => run.status === "dispatched").map((run) => run.id), }); const byRun = new Map(waits.map((wait) => [wait.runId, wait])); return runs.map((run) => { const wait = byRun.get(run.id); return wait ? { ...run, awaitingHuman: { since: wait.since, expiresAt: wait.expiresAt } } : run; }); }); } // --------------------------------------------------------------------------- // Rigs (migration 0047). Workspace-scoped, versioned sandbox machine definitions. // Versions are append-only + content-immutable: NO function below ever UPDATEs a // content column of rig_versions — only activateRigVersion flips the `active` // boolean. Every function runs through withWorkspaceRls / withRlsContext. // --------------------------------------------------------------------------- // Thrown when a rig_change status transition is illegal (merged/rejected are // terminal). The domain/route layer maps this to a 409. export class RigChangeTransitionError extends Error { constructor( public readonly changeId: string, public readonly fromStatus: string, public readonly toStatus: string, ) { super( `Sandbox Environment change ${changeId} is ${fromStatus} (terminal); cannot transition to ${toStatus}`, ); this.name = "RigChangeTransitionError"; } } export class RigActiveVersionChangedError extends Error { constructor( public readonly rigId: string, public readonly expectedVersionId: string, public readonly actualVersionId: string | null, ) { super( `Sandbox Environment ${rigId} moved since verification: expected active ${expectedVersionId}, current active ${actualVersionId ?? "none"}`, ); this.name = "RigActiveVersionChangedError"; } } export class RigChangeAlreadyVerifyingError extends Error { constructor(public readonly changeId: string) { super(`Sandbox Environment change ${changeId} is already verifying`); this.name = "RigChangeAlreadyVerifyingError"; } } export class RigImageOverrideUnsupportedError extends Error { constructor() { super( "Sandbox environment image overrides are unsupported; sandbox environments use the deployment platform sandbox image", ); this.name = "RigImageOverrideUnsupportedError"; } } export type RigVersionContentInput = { /** @deprecated Rig versions always use the deployment platform sandbox image. */ image?: string | null; setupScript?: string | null; checks?: RigCheck[]; credentialHooks?: string[]; changelog?: string | null; createdBy?: string | null; }; function assertRigUsesPlatformImage(input: RigVersionContentInput | undefined): void { if (input?.image != null) { throw new RigImageOverrideUnsupportedError(); } } function mapRigVersion(row: typeof schema.rigVersions.$inferSelect): RigVersion { return { id: row.id, rigId: row.rigId, version: row.version, image: row.image, setupScript: row.setupScript, checks: row.checks, credentialHooks: row.credentialHooks, changelog: row.changelog, providerImages: row.providerImages, createdBy: row.createdBy, active: row.active, createdAt: row.createdAt.toISOString(), }; } function unknownRigHealth(activeVersion: RigVersion | null): RigVerificationHealth | null { return activeVersion ? { checkHealth: "unknown", lastVerifiedAt: null } : null; } /** Where an organization machine or rig works (migration 1190); null for * workspace and personal ones, whose reach is their owner's. */ function organizationComputeReach(row: { authorityScope: string; workspaceId: string; allowedWorkspaceIds: string[] | null; allowPersonalWorkspaces: boolean; allowManagedWorkspaces: boolean; }): OrganizationComputeReach | null { if (row.authorityScope !== "organization") return null; return { homeWorkspaceId: row.workspaceId, allowedWorkspaceIds: row.allowedWorkspaceIds ?? null, allowPersonalWorkspaces: row.allowPersonalWorkspaces, allowManagedWorkspaces: row.allowManagedWorkspaces, }; } function mapRig( row: typeof schema.rigs.$inferSelect, activeVersion: RigVersion | null, versionCount: number, activeVersionHealth: RigVerificationHealth | null = unknownRigHealth(activeVersion), ): Rig { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, scope: row.authorityScope as Rig["scope"], generation: Number(row.generation), status: row.status as Rig["status"], name: row.name, description: row.description, createdBy: row.createdBy, activeVersion, activeVersionHealth, versionCount, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), reach: organizationComputeReach(row), }; } function mapRigChange(row: typeof schema.rigChanges.$inferSelect): RigChange { const payload = fromPostgresLosslessJson(row.payload, row.payloadCodecVersion); const verification = fromPostgresLosslessJson(row.verification, row.verificationCodecVersion); return { id: row.id, rigId: row.rigId, baseVersionId: row.baseVersionId, kind: row.kind as RigChangeKind, payload: RigChangeContract.shape.payload.parse(payload), status: row.status as RigChangeStatus, proposedBy: row.proposedBy, verification: (verification ?? null) as RigChange["verification"], resultVersionId: row.resultVersionId, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } // Load a rig's active version + total version count within an existing RLS scope. async function loadRigActiveAndCount( scopedDb: Database, workspaceId: string, rigId: string, ): Promise<{ activeVersion: RigVersion | null; versionCount: number }> { const [activeRow] = await scopedDb .select() .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.active, true), ), ) .limit(1); const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int` }) .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ); return { activeVersion: activeRow ? mapRigVersion(activeRow) : null, versionCount: Number(count), }; } type RigHealthCandidate = { versionId: string; checkHealth: "passing" | "failing"; verifiedAt: string; }; function latestRigHealth(candidates: RigHealthCandidate[]): RigVerificationHealth { let latest: RigHealthCandidate | null = null; for (const candidate of candidates) { if (!latest || Date.parse(candidate.verifiedAt) >= Date.parse(latest.verifiedAt)) { latest = candidate; } } return latest ? { checkHealth: latest.checkHealth, lastVerifiedAt: latest.verifiedAt } : { checkHealth: "unknown", lastVerifiedAt: null }; } function verificationTimestamp( verification: Record | null | undefined, fallback: Date, ): string { return typeof verification?.finishedAt === "string" ? verification.finishedAt : fallback.toISOString(); } async function loadRigHealthByActiveVersion( scopedDb: Database, workspaceId: string, activeVersions: RigVersion[], ): Promise> { const versionIds = activeVersions.map((version) => version.id); const healthByVersion: Map = new Map( versionIds.map((versionId) => [versionId, { checkHealth: "unknown", lastVerifiedAt: null }]), ); if (versionIds.length === 0) { return healthByVersion; } const candidatesByVersion = new Map(); const pushCandidate = (candidate: RigHealthCandidate) => { candidatesByVersion.set(candidate.versionId, [ ...(candidatesByVersion.get(candidate.versionId) ?? []), candidate, ]); }; const changes = await scopedDb .select({ resultVersionId: schema.rigChanges.resultVersionId, verification: schema.rigChanges.verification, verificationCodecVersion: schema.rigChanges.verificationCodecVersion, updatedAt: schema.rigChanges.updatedAt, }) .from(schema.rigChanges) .where( and( eq(schema.rigChanges.workspaceId, workspaceId), inArray(schema.rigChanges.resultVersionId, versionIds), ), ); for (const change of changes) { if (!change.resultVersionId) { continue; } const verification = fromPostgresLosslessJson( change.verification, change.verificationCodecVersion, ) as Record | null; if (verification?.passed === true) { pushCandidate({ versionId: change.resultVersionId, checkHealth: "passing", verifiedAt: verificationTimestamp(verification, change.updatedAt), }); } else if (verification?.passed === false) { pushCandidate({ versionId: change.resultVersionId, checkHealth: "failing", verifiedAt: verificationTimestamp(verification, change.updatedAt), }); } } const auditRows = await scopedDb .select({ action: schema.auditEvents.action, metadata: schema.auditEvents.metadata, metadataCodecVersion: schema.auditEvents.metadataCodecVersion, occurredAt: schema.auditEvents.occurredAt, }) .from(schema.auditEvents) .where( and( eq(schema.auditEvents.workspaceId, workspaceId), eq(schema.auditEvents.targetType, "rig"), inArray(schema.auditEvents.action, ["rig.verification.passed", "rig.verification.failed"]), inArray(sql`${schema.auditEvents.metadata}->>'versionId'`, versionIds), ), ); for (const row of auditRows) { const metadata = fromPostgresLosslessJson(row.metadata, row.metadataCodecVersion) ?? {}; const versionId = typeof metadata.versionId === "string" ? metadata.versionId : null; if (!versionId || !healthByVersion.has(versionId)) { continue; } const passed = typeof metadata.passed === "boolean" ? metadata.passed : row.action === "rig.verification.passed"; pushCandidate({ versionId, checkHealth: passed ? "passing" : "failing", verifiedAt: row.occurredAt.toISOString(), }); } for (const versionId of versionIds) { healthByVersion.set(versionId, latestRigHealth(candidatesByVersion.get(versionId) ?? [])); } return healthByVersion; } // Creates the rig row AND its version 1 (active) in one transaction: a failure // leaves nothing behind. version-1 content comes from `initialVersion`. export async function createRig( db: Database, input: { accountId: string; workspaceId: string; scope?: Rig["scope"]; subjectId?: string; allowOrganization?: boolean; name: string; description?: string | null; createdBy?: string | null; initialVersion?: RigVersionContentInput; }, ): Promise { assertRigUsesPlatformImage(input.initialVersion); if (input.scope !== undefined || input.subjectId !== undefined) { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.subjectId) await setSubjectRlsContext(scopedDb, input.subjectId); const content = input.initialVersion ?? {}; const [row] = await rawRows<{ value: Rig }>( scopedDb, sql`select create_scoped_rig( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.scope ?? "workspace"}, ${input.name}, ${input.description ?? null}, ${input.createdBy ?? null}, ${JSON.stringify({ image: null, setupScript: content.setupScript ?? null, checks: content.checks ?? [], credentialHooks: content.credentialHooks ?? [], changelog: content.changelog ?? null, createdBy: content.createdBy ?? input.createdBy ?? null, })}::jsonb, ${input.allowOrganization === true} ) as value`, ); if (!row) throw new Error("Failed to create scoped sandbox environment"); return row.value; }, ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [rigRow] = await scopedDb .insert(schema.rigs) .values({ accountId: input.accountId, workspaceId: input.workspaceId, name: input.name, description: input.description ?? null, createdBy: input.createdBy ?? null, }) .returning(); if (!rigRow) { throw new Error("Failed to create sandbox environment"); } const content = input.initialVersion ?? {}; const [versionRow] = await scopedDb .insert(schema.rigVersions) .values({ accountId: input.accountId, workspaceId: input.workspaceId, rigId: rigRow.id, version: 1, image: null, setupScript: content.setupScript ?? null, checks: content.checks ?? [], credentialHooks: content.credentialHooks ?? [], changelog: content.changelog ?? null, providerImages: {}, createdBy: content.createdBy ?? input.createdBy ?? null, active: true, }) .returning(); if (!versionRow) { throw new Error("Failed to create initial sandbox environment version"); } return mapRig(rigRow, mapRigVersion(versionRow), 1); }, ); } export type RigAccessContext = { accountId: string; workspaceId: string; subjectId: string; }; export async function listRigs(db: Database, access: string | RigAccessContext): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const rows = await rawRows<{ value: Rig }>( scopedDb, sql`select value from list_scoped_rigs( ${access.accountId}::uuid, ${access.workspaceId}::uuid, null, null, null ) value`, ); return rows.map((row) => row.value); }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.rigs) .where(eq(schema.rigs.workspaceId, workspaceId)) .orderBy(asc(schema.rigs.createdAt)); if (rows.length === 0) { return []; } const activeRows = await scopedDb .select() .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.active, true)), ); const activeByRig = new Map(activeRows.map((row) => [row.rigId, mapRigVersion(row)])); const healthByVersion = await loadRigHealthByActiveVersion(scopedDb, workspaceId, [ ...activeByRig.values(), ]); const countRows = await scopedDb .select({ rigId: schema.rigVersions.rigId, count: sql`count(*)::int`, }) .from(schema.rigVersions) .where(eq(schema.rigVersions.workspaceId, workspaceId)) .groupBy(schema.rigVersions.rigId); const countByRig = new Map(countRows.map((row) => [row.rigId, Number(row.count)])); return rows.map((row) => { const activeVersion = activeByRig.get(row.id) ?? null; return mapRig( row, activeVersion, countByRig.get(row.id) ?? 0, activeVersion ? (healthByVersion.get(activeVersion.id) ?? unknownRigHealth(activeVersion)) : null, ); }); }); } export async function getRig( db: Database, access: string | RigAccessContext, rigId: string, ): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: Rig }>( scopedDb, sql`select value from list_scoped_rigs( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${rigId}::uuid, null, null ) value`, ); return row?.value ?? null; }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .limit(1); if (!row) { return null; } const { activeVersion, versionCount } = await loadRigActiveAndCount( scopedDb, workspaceId, rigId, ); const healthByVersion = await loadRigHealthByActiveVersion( scopedDb, workspaceId, activeVersion ? [activeVersion] : [], ); return mapRig( row, activeVersion, versionCount, activeVersion ? (healthByVersion.get(activeVersion.id) ?? unknownRigHealth(activeVersion)) : null, ); }); } export async function getRigByName( db: Database, access: string | RigAccessContext, name: string, scope?: Rig["scope"], ): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: Rig }>( scopedDb, sql`select value from list_scoped_rigs( ${access.accountId}::uuid, ${access.workspaceId}::uuid, null, ${name}, ${scope ?? null} ) value`, ); return row?.value ?? null; }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.name, name))) .limit(1); if (!row) { return null; } const { activeVersion, versionCount } = await loadRigActiveAndCount( scopedDb, workspaceId, row.id, ); const healthByVersion = await loadRigHealthByActiveVersion( scopedDb, workspaceId, activeVersion ? [activeVersion] : [], ); return mapRig( row, activeVersion, versionCount, activeVersion ? (healthByVersion.get(activeVersion.id) ?? unknownRigHealth(activeVersion)) : null, ); }); } // name/description only — never touches versions (content immutability). export async function updateRig( db: Database, workspaceId: string, rigId: string, input: { name?: string; description?: string | null; }, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .update(schema.rigs) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.description !== undefined ? { description: input.description } : {}), updatedAt: new Date(), }) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .returning(); if (!row) { throw new Error(`Sandbox Environment not found: ${rigId}`); } const { activeVersion, versionCount } = await loadRigActiveAndCount( scopedDb, workspaceId, rigId, ); const healthByVersion = await loadRigHealthByActiveVersion( scopedDb, workspaceId, activeVersion ? [activeVersion] : [], ); return mapRig( row, activeVersion, versionCount, activeVersion ? (healthByVersion.get(activeVersion.id) ?? unknownRigHealth(activeVersion)) : null, ); }); } export async function deleteRig( db: Database, workspaceId: string, rigId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .delete(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .returning({ id: schema.rigs.id }); return rows.length > 0; }); } export async function deleteRigIfNoActiveSessions( db: Database, workspaceId: string, rigId: string, ): Promise<{ deleted: boolean; activeSessionCount: number }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [rig] = await scopedDb .select({ id: schema.rigs.id }) .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .for("update") .limit(1); if (!rig) { return { deleted: false, activeSessionCount: 0 }; } const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int` }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.rigId, rigId), sql`${schema.sessions.status} not in ('failed', 'cancelled')`, ), ); const activeSessionCount = Number(count); if (activeSessionCount > 0) { return { deleted: false, activeSessionCount }; } const rows = await scopedDb .delete(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .returning({ id: schema.rigs.id }); return { deleted: rows.length > 0, activeSessionCount }; }); } export async function updateScopedRig( db: Database, access: RigAccessContext, rigId: string, input: { name?: string; description?: string | null; allowOrganization?: boolean; }, ): Promise { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: Rig | null }>( scopedDb, sql`select mutate_scoped_rig( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${rigId}::uuid, 'update', ${input.name ?? null}, ${input.name !== undefined}, ${input.description ?? null}, ${input.description !== undefined}, ${input.allowOrganization === true} ) as value`, ); if (!row?.value) throw new Error(`Sandbox Environment not found: ${rigId}`); return row.value; }); } export async function revokeScopedRig( db: Database, access: RigAccessContext, rigId: string, options: { allowOrganization?: boolean } = {}, ): Promise { await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); await scopedDb.execute(sql`select mutate_scoped_rig( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${rigId}::uuid, 'revoke', null, false, null, false, ${options.allowOrganization === true} )`); }); } /** Input for changing where an organization machine or rig works. The caller * has checked that the subject is an organization owner or admin. */ export type OrganizationComputeReachInput = { accountId: string; /** The workspace the machine was connected from or the rig was made in. */ homeWorkspaceId: string; allowedWorkspaceIds: string[] | null; allowPersonalWorkspaces: boolean; /** Every workspace the product manages (1512); omitted keeps the current setting. */ allowManagedWorkspaces?: boolean | undefined; subjectId: string; }; export type OrganizationComputeReachUpdate = | { status: "updated"; reach: OrganizationComputeReach } | { status: "not_found" } | { status: "unknown_workspaces"; workspaceIds: string[] }; /** The listed ids, without duplicates or the home workspace (which always has * it), checked against the organization's shared workspaces. */ async function normalizeOrganizationComputeReach( db: Database, input: OrganizationComputeReachInput, ): Promise< { ok: true; allowedWorkspaceIds: string[] | null } | { ok: false; workspaceIds: string[] } > { if (input.allowedWorkspaceIds === null) return { ok: true, allowedWorkspaceIds: null }; const listed = [...new Set(input.allowedWorkspaceIds)].filter( (workspaceId) => workspaceId !== input.homeWorkspaceId, ); if (listed.length === 0) return { ok: true, allowedWorkspaceIds: [] }; const shared = await withRlsContext( db, { accountId: input.accountId, workspaceId: null }, async (scopedDb) => await rawRows<{ workspace_id: string }>( scopedDb, sql`select workspace_id from list_organization_workspace_ids(${input.accountId}::uuid)`, ), ); const sharedIds = new Set(shared.map((row) => row.workspace_id)); const unknown = listed.filter((workspaceId) => !sharedIds.has(workspaceId)); if (unknown.length > 0) return { ok: false, workspaceIds: unknown }; return { ok: true, allowedWorkspaceIds: listed.sort() }; } /** Change where an organization rig works. Its home workspace always has it; * chats and schedules in a workspace it no longer works in fail at their next * attempt instead of using it. */ export async function updateOrganizationRigReach( db: Database, rigId: string, input: OrganizationComputeReachInput, ): Promise { const normalized = await normalizeOrganizationComputeReach(db, input); if (!normalized.ok) return { status: "unknown_workspaces", workspaceIds: normalized.workspaceIds }; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.homeWorkspaceId }, async (scopedDb) => { const where = and( eq(schema.rigs.accountId, input.accountId), eq(schema.rigs.workspaceId, input.homeWorkspaceId), eq(schema.rigs.id, rigId), eq(schema.rigs.authorityScope, "organization"), eq(schema.rigs.status, "active"), ); const [before] = await scopedDb .select({ allowedWorkspaceIds: schema.rigs.allowedWorkspaceIds, allowPersonalWorkspaces: schema.rigs.allowPersonalWorkspaces, allowManagedWorkspaces: schema.rigs.allowManagedWorkspaces, }) .from(schema.rigs) .where(where) .for("update") .limit(1); if (!before) return { status: "not_found" }; const [row] = await scopedDb .update(schema.rigs) .set({ allowedWorkspaceIds: normalized.allowedWorkspaceIds, allowPersonalWorkspaces: input.allowPersonalWorkspaces, ...(input.allowManagedWorkspaces !== undefined ? { allowManagedWorkspaces: input.allowManagedWorkspaces } : {}), updatedAt: new Date(), }) .where(where) .returning(); if (!row) return { status: "not_found" }; await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.homeWorkspaceId, subjectId: input.subjectId, action: "rig.reach.changed", targetType: "rig", targetId: rigId, metadata: { from: before, to: { allowedWorkspaceIds: row.allowedWorkspaceIds, allowPersonalWorkspaces: row.allowPersonalWorkspaces, allowManagedWorkspaces: row.allowManagedWorkspaces, }, }, }); return { status: "updated", reach: { homeWorkspaceId: row.workspaceId, allowedWorkspaceIds: row.allowedWorkspaceIds ?? null, allowPersonalWorkspaces: row.allowPersonalWorkspaces, allowManagedWorkspaces: row.allowManagedWorkspaces, }, }; }, ); } /** An organization machine or rig, wherever it works: its name and reach only. */ export type OrganizationComputeSummaryRow = { id: string; name: string; /** Machines: the machine's sandbox, which their pages open by. */ sandboxId?: string | null; reach: OrganizationComputeReach; }; /** * Every active organization machine or rig in the account, wherever it works * (migration 1224), for the people who decide where they work; the caller * checks organization administration (the owner or an admin) and refuses * agent runs. */ export async function listOrganizationCompute( db: Database, access: RigAccessContext, kind: "machine" | "rig", ): Promise { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const rows = await rawRows<{ value: { id: string; name?: string; sandboxId?: string | null; sandboxName?: string | null; os?: string | null; reach: OrganizationComputeReach; }; }>( scopedDb, sql`select value from opengeni_private.list_organization_compute_v1( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${kind} ) value`, ); return rows.map(({ value }) => kind === "machine" ? { id: value.id, // As the machine list names it. name: value.sandboxName ?? `${value.os} machine`, sandboxId: value.sandboxId ?? null, reach: value.reach, } : { id: value.id, name: value.name ?? "", reach: value.reach }, ); }); } // --- Channels --------------------------------------------------------------- // Workspace-shared rail organization for root sessions. Pure metadata: filing // a session into a channel never affects execution, authority, or history. export class ChannelNameConflictError extends Error { constructor(name: string) { super(`channel name is already in use: ${name}`); this.name = "ChannelNameConflictError"; } } export class ChannelNotFoundError extends Error { constructor(channelId: string) { super(`unknown channelId: ${channelId}`); this.name = "ChannelNotFoundError"; } } /** * An Only me project holds only its owner's own Only me chats and Sites * (1161), so nothing in it is ever visible to anyone else. */ export class ChannelAudienceMismatchError extends Error { constructor(kind: "chat" | "app") { super(`An Only me project holds only your own Only me ${kind}s.`); this.name = "ChannelAudienceMismatchError"; } } function isChannelNameUniqueViolation(error: unknown): boolean { const constraint = safeDatabaseErrorFacts(error).constraint; return ( nestedPostgresSqlState(error) === "23505" && (constraint === "channels_workspace_name_idx" || constraint === "channels_owner_name_idx") ); } /** Whether an item fits a project: anything fits a shared one. */ function fitsProject( project: { visibility: string; ownerSubjectId: string | null }, item: { visibility: string; ownerSubjectId: string | null }, ): boolean { return ( project.visibility !== "user_private" || (item.visibility === "user_private" && item.ownerSubjectId !== null && item.ownerSubjectId === project.ownerSubjectId) ); } /** * A write raced a concurrent channel delete: the sessions.channel_id FK * rejected the row after the workspace-scoped existence check passed. Mapped * to the same typed not-found error the pre-check throws, so callers keep * one 422 path instead of a driver-level 500. */ function isSessionChannelFkViolation(error: unknown): boolean { return ( nestedPostgresSqlState(error) === "23503" && safeDatabaseErrorFacts(error).constraint === "sessions_channel_id_fkey" ); } function translateSessionCreateError(error: unknown): never { const connectionFailure = sessionCreateConnectionSelectionFailure(error); if (connectionFailure) throw connectionFailure; throw error; } function mapChannel(row: typeof schema.channels.$inferSelect): Channel { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, name: row.name, description: row.description ?? null, avatar: storedSessionAvatar(row.avatar), pinned: row.pinned, sortOrder: row.sortOrder, visibility: row.visibility === "user_private" ? "private" : "workspace", createdBy: row.createdBy ?? null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } export async function createChannel( db: Database, input: { accountId: string; workspaceId: string; name: string; description?: string | null; avatar?: SessionAvatar | null; createdBy?: string | null; /** * Who sees it; Only me needs its owner. Omitted, shared with the * workspace, as every project was before audiences. */ audience?: { visibility: "user_private" | "workspace_shared"; ownerSubjectId: string | null }; }, ): Promise { const visibility = input.audience?.visibility ?? "workspace_shared"; const ownerSubjectId = input.audience?.ownerSubjectId ?? null; if (visibility === "user_private" && !ownerSubjectId) throw new TypeError("An Only me project needs an owner"); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { try { const nextSortOrder = ( await scopedDb .select({ nextSortOrder: sql`coalesce(max(${schema.channels.sortOrder}), -1) + 1`, }) .from(schema.channels) .where(eq(schema.channels.workspaceId, input.workspaceId)) )[0]?.nextSortOrder ?? 0; const [row] = await scopedDb .insert(schema.channels) .values({ accountId: input.accountId, workspaceId: input.workspaceId, name: input.name, description: input.description ?? null, avatar: input.avatar ?? null, sortOrder: nextSortOrder, visibility, ownerSubjectId, createdBy: input.createdBy ?? null, }) .returning(); if (!row) { throw new Error("Failed to create channel"); } return mapChannel(row); } catch (error) { if (isChannelNameUniqueViolation(error)) { throw new ChannelNameConflictError(input.name); } throw error; } }, ); } export async function listChannels(db: Database, workspaceId: string): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.channels) .where(eq(schema.channels.workspaceId, workspaceId)) .orderBy( desc(schema.channels.pinned), asc(schema.channels.sortOrder), asc(schema.channels.id), ); return rows.map(mapChannel); }); } export async function getChannel( db: Database, workspaceId: string, channelId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.channels) .where(and(eq(schema.channels.workspaceId, workspaceId), eq(schema.channels.id, channelId))) .limit(1); return row ? mapChannel(row) : null; }); } export async function updateChannel( db: Database, workspaceId: string, channelId: string, input: { name?: string | undefined; description?: string | null | undefined; avatar?: SessionAvatar | null | undefined; pinned?: boolean | undefined; /** Shares an Only me project with the workspace; never narrows. */ visibility?: "workspace_shared" | undefined; }, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { // Sharing keeps the name, which then has to be free among shared projects. const conflictName = input.name ?? (input.visibility === undefined ? "" : (( await scopedDb .select({ name: schema.channels.name }) .from(schema.channels) .where( and( eq(schema.channels.workspaceId, workspaceId), eq(schema.channels.id, channelId), ), ) .limit(1) )[0]?.name ?? "")); try { const [row] = await scopedDb .update(schema.channels) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.description !== undefined ? { description: input.description } : {}), ...(input.avatar !== undefined ? { avatar: input.avatar } : {}), ...(input.pinned !== undefined ? { pinned: input.pinned } : {}), ...(input.visibility !== undefined ? { visibility: input.visibility } : {}), updatedAt: new Date(), }) .where(and(eq(schema.channels.workspaceId, workspaceId), eq(schema.channels.id, channelId))) .returning(); return row ? mapChannel(row) : null; } catch (error) { if (isChannelNameUniqueViolation(error)) { throw new ChannelNameConflictError(conflictName); } throw error; } }); } export async function deleteChannel( db: Database, workspaceId: string, channelId: string, ): Promise { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { // Detaching sessions changes project-filter membership. Enroll matching // rows in the activity commit gate while preserving their recency sort so // an already-open filtered cursor remains a frozen membership snapshot. await scopedDb .update(schema.sessions) .set({ channelId: null, updatedAt: sql`${schema.sessions.updatedAt}` }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.channelId, channelId)), ); const rows = await scopedDb .delete(schema.channels) .where(and(eq(schema.channels.workspaceId, workspaceId), eq(schema.channels.id, channelId))) .returning({ id: schema.channels.id }); return rows.length > 0; }); } /** * Replaces the complete project order in one workspace-scoped transaction. * Callers must supply every current project exactly once so a stale drag can * never silently discard a concurrently created project. */ export async function reorderChannels( db: Database, workspaceId: string, channelIds: readonly string[], ): Promise { return await withWorkspaceRls( db, workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { const existing = await tx .select({ id: schema.channels.id }) .from(schema.channels) .where(eq(schema.channels.workspaceId, workspaceId)) .orderBy(asc(schema.channels.sortOrder), asc(schema.channels.id)) .for("update"); const existingIds = new Set(existing.map((channel) => channel.id)); if ( existing.length !== channelIds.length || new Set(channelIds).size !== channelIds.length || channelIds.some((channelId) => !existingIds.has(channelId)) ) { return null; } const updatedAt = new Date(); for (const [sortOrder, channelId] of channelIds.entries()) { await tx .update(schema.channels) .set({ sortOrder, updatedAt }) .where( and(eq(schema.channels.workspaceId, workspaceId), eq(schema.channels.id, channelId)), ); } const rows = await tx .select() .from(schema.channels) .where(eq(schema.channels.workspaceId, workspaceId)) .orderBy( desc(schema.channels.pinned), asc(schema.channels.sortOrder), asc(schema.channels.id), ); return rows.map(mapChannel); }), ); } // Re-files one session (rail organization only). Resolves the target channel // workspace-scoped so a foreign channel id can never be attached; null moves // the session back to the unfiled inbox. Filing advances the activity revision // used to freeze filtered cursor membership, while preserving updatedAt so it // never reorders the rail's recency buckets. export async function setSessionChannel( db: Database, input: { workspaceId: string; sessionId: string; channelId: string | null }, ): Promise { // Session-row writers require the activity-gated handle (migration 0214's // commit gate); filing is organizational but it is still a sessions UPDATE. return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => { if (input.channelId !== null) { const [channel] = await scopedDb .select({ id: schema.channels.id, visibility: schema.channels.visibility, ownerSubjectId: schema.channels.ownerSubjectId, }) .from(schema.channels) .where( and( eq(schema.channels.workspaceId, input.workspaceId), eq(schema.channels.id, input.channelId), ), ) .limit(1); if (!channel) { throw new ChannelNotFoundError(input.channelId); } if (channel.visibility === "user_private") { const [session] = await scopedDb .select({ visibility: schema.sessions.visibility, ownerSubjectId: schema.sessions.ownerSubjectId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session) return false; if ( !fitsProject(channel, { visibility: session.visibility, ownerSubjectId: session.ownerSubjectId ?? null, }) ) throw new ChannelAudienceMismatchError("chat"); } } try { const rows = await scopedDb .update(schema.sessions) // Naming updatedAt in the SET list enrolls this row in the commit gate; // the self-assignment deliberately preserves the activity sort time. .set({ channelId: input.channelId, updatedAt: sql`${schema.sessions.updatedAt}` }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .returning({ id: schema.sessions.id }); return rows.length > 0; } catch (error) { // The channel passed the existence check above but was deleted before // the UPDATE committed. if (input.channelId !== null && isSessionChannelFkViolation(error)) { throw new ChannelNotFoundError(input.channelId); } throw error; } }); } /** Bound on the conversations one Site row move re-files. */ export const SITE_PROJECT_MOVE_LIMIT = 500; /** * The conversations a Site row in one project stands for, as this person sees * them: the Site's top-level conversations filed in that project (null is * Default), archived or pinned ones included, so none stays behind. Up to * SITE_PROJECT_MOVE_LIMIT + 1 ids, so a caller can refuse an oversized move. */ export async function listSiteProjectConversationIds( db: Database, input: { workspaceId: string; subjectId: string; siteId: string; channelId: string | null }, ): Promise { return await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (scoped) => { const rows = await scoped .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.siteId, input.siteId), isNotNull(schema.sessions.siteAccessRootId), isNull(schema.sessions.parentSessionId), input.channelId === null ? isNull(schema.sessions.channelId) : eq(schema.sessions.channelId, input.channelId), ), ) .orderBy(schema.sessions.id) .limit(SITE_PROJECT_MOVE_LIMIT + 1); return rows.map((row) => row.id); }); } /** * Moves a Site's sidebar row from one project to another (null is Default), * like moving a chat. The row is the Site itself when that project is its * home as this person sees it (the project someone moved it to, else the * creating chat's): then the Site moves for everyone, and its new * conversations are filed there. The row's conversations move with it; the * caller passes the ids it authorized, and only those still filed in the * source project move. Only a Site in this person's audience can move; a row * left behind by a Site that is no longer theirs to see still moves its * conversations, as a chat owner can always move their own chat. Nothing * about the Site, its publication or audience changes. */ export async function moveSiteToProject( db: Database, input: { workspaceId: string; subjectId: string; siteId: string; fromChannelId: string | null; channelId: string | null; sessionIds: readonly string[]; }, ): Promise<{ siteMoved: boolean; movedSessionIds: string[] }> { return await withWorkspaceSubjectSessionActivityRls( db, input.workspaceId, input.subjectId, async (scoped) => { // One move of a Site at a time, so concurrent moves cannot leave the Site // in one project and its conversations in another. await scoped.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`site-project:${input.workspaceId}:${input.siteId}`}, 0))`, ); const [site] = await rawRows<{ accountId: string; homeChannelId: string | null; inAudience: boolean; visibility: string; ownerSubjectId: string | null; }>( scoped, sql` select artifact.account_id as "accountId", (case when placement.site_id is not null then placement.channel_id else creator.channel_id end)::text as "homeChannelId", (artifact.visibility = 'workspace_shared' or artifact.owner_subject_id = ${input.subjectId}) as "inAudience", artifact.visibility as "visibility", artifact.owner_subject_id as "ownerSubjectId" from ${schema.workspaceArtifacts} artifact left join ${schema.siteProjectPlacements} placement on placement.workspace_id = artifact.workspace_id and placement.site_id = artifact.id left join ${schema.workspaceArtifactVersions} version on version.workspace_id = artifact.workspace_id and version.artifact_id = artifact.id and version.revision = 1 left join ${schema.sessions} source on source.workspace_id = artifact.workspace_id and source.id = version.source_session_id left join ${schema.sessions} creator on creator.workspace_id = artifact.workspace_id and creator.id = source.root_session_id and creator.site_access_root_id is null where artifact.workspace_id = ${input.workspaceId} and artifact.id = ${input.siteId} limit 1`, ); if (!site || (!site.inAudience && input.sessionIds.length === 0)) throw new WorkspaceArtifactNotFoundError("App not found"); if (input.fromChannelId === input.channelId) return { siteMoved: false, movedSessionIds: [] }; if (input.channelId !== null) { const [channel] = await scoped .select({ id: schema.channels.id, visibility: schema.channels.visibility, ownerSubjectId: schema.channels.ownerSubjectId, }) .from(schema.channels) .where( and( eq(schema.channels.workspaceId, input.workspaceId), eq(schema.channels.id, input.channelId), ), ) .limit(1); if (!channel) throw new ChannelNotFoundError(input.channelId); // An Only me project takes only its owner's Only me Site, and the // conversations that move with a row must fit it too. if (channel.visibility === "user_private") { if (!fitsProject(channel, site)) throw new ChannelAudienceMismatchError("app"); const misfits = input.sessionIds.length === 0 ? [] : await scoped .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), inArray(schema.sessions.id, [...input.sessionIds]), or( ne(schema.sessions.visibility, "user_private"), isNull(schema.sessions.ownerSubjectId), ne(schema.sessions.ownerSubjectId, channel.ownerSubjectId ?? ""), ), ), ) .limit(1); if (misfits.length > 0) throw new ChannelAudienceMismatchError("chat"); } } const siteMoved = site.inAudience && site.homeChannelId === input.fromChannelId; try { if (siteMoved) { await scoped .insert(schema.siteProjectPlacements) .values({ accountId: site.accountId, workspaceId: input.workspaceId, siteId: input.siteId, channelId: input.channelId, placedBySubjectId: input.subjectId, }) .onConflictDoUpdate({ target: [ schema.siteProjectPlacements.workspaceId, schema.siteProjectPlacements.siteId, ], set: { channelId: input.channelId, placedBySubjectId: input.subjectId, updatedAt: sql`now()`, }, }); } const moved = input.sessionIds.length === 0 ? [] : await scoped .update(schema.sessions) // As for a chat move: the self-assignment keeps the activity time. .set({ channelId: input.channelId, updatedAt: sql`${schema.sessions.updatedAt}` }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), inArray(schema.sessions.id, [...input.sessionIds]), eq(schema.sessions.siteId, input.siteId), isNotNull(schema.sessions.siteAccessRootId), isNull(schema.sessions.parentSessionId), input.fromChannelId === null ? isNull(schema.sessions.channelId) : eq(schema.sessions.channelId, input.fromChannelId), ), ) .returning({ id: schema.sessions.id }); return { siteMoved, movedSessionIds: moved.map((row) => row.id).sort() }; } catch (error) { // The project passed the check above but was deleted before the write. if ( input.channelId !== null && nestedPostgresSqlState(error) === "23503" && /channel/u.test(safeDatabaseErrorFacts(error).constraint ?? "") ) { throw new ChannelNotFoundError(input.channelId); } throw error; } }, ); } export async function countRigs( db: Database, access: string | RigAccessContext, scope: Rig["scope"] = "workspace", ): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ count: number }>( scopedDb, sql`select count_scoped_rigs( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${scope} ) as count`, ); return Number(row?.count ?? 0); }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int` }) .from(schema.rigs) .where(eq(schema.rigs.workspaceId, workspaceId)); return Number(count); }); } export async function countSessionsUsingRig( db: Database, workspaceId: string, rigId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int` }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.rigId, rigId))); return Number(count); }); } // Mints the next version for a rig (promote/rollback-mint paths, M4). Row-locks // the rig so concurrent mints get strictly-monotonic version numbers. When // `activate` is set, atomically deactivates the current active version first. export async function createRigVersion( db: Database, workspaceId: string, rigId: string, input: RigVersionContentInput, options: { activate?: boolean } = {}, ): Promise { assertRigUsesPlatformImage(input); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [rig] = await scopedDb .select({ id: schema.rigs.id, accountId: schema.rigs.accountId }) .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .for("update") .limit(1); if (!rig) { throw new Error(`Sandbox Environment not found: ${rigId}`); } const [{ max } = { max: 0 }] = await scopedDb .select({ max: sql`coalesce(max(${schema.rigVersions.version}), 0)::int`, }) .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ); const nextVersion = Number(max) + 1; if (options.activate) { await scopedDb .update(schema.rigVersions) .set({ active: false }) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.active, true), ), ); } const [row] = await scopedDb .insert(schema.rigVersions) .values({ accountId: rig.accountId, workspaceId, rigId, version: nextVersion, image: null, setupScript: input.setupScript ?? null, checks: input.checks ?? [], credentialHooks: input.credentialHooks ?? [], changelog: input.changelog ?? null, providerImages: {}, createdBy: input.createdBy ?? null, active: options.activate ?? false, }) .returning(); if (!row) { throw new Error("Failed to create sandbox environment version"); } await scopedDb .update(schema.rigs) .set({ updatedAt: new Date() }) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))); return mapRigVersion(row); }); } export async function createRigVersionForChangePromotion( db: Database, workspaceId: string, rigId: string, changeId: string, input: RigVersionContentInput & { expectedActiveVersionId: string; providerImages?: RigProviderImages; }, ): Promise<{ version: RigVersion; change: RigChange }> { assertRigUsesPlatformImage(input); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [rig] = await scopedDb .select({ id: schema.rigs.id, accountId: schema.rigs.accountId }) .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .for("update") .limit(1); if (!rig) { throw new Error(`Sandbox Environment not found: ${rigId}`); } const [currentChange] = await scopedDb .select() .from(schema.rigChanges) .where( and( eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.rigId, rigId), eq(schema.rigChanges.id, changeId), ), ) .for("update") .limit(1); if (!currentChange) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } if (currentChange.status === "merged" || currentChange.status === "rejected") { throw new RigChangeTransitionError(changeId, currentChange.status, "merged"); } if (currentChange.baseVersionId !== input.expectedActiveVersionId) { throw new RigActiveVersionChangedError( rigId, input.expectedActiveVersionId, currentChange.baseVersionId, ); } const [active] = await scopedDb .select({ id: schema.rigVersions.id }) .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.active, true), ), ) .limit(1); if (active?.id !== input.expectedActiveVersionId) { throw new RigActiveVersionChangedError( rigId, input.expectedActiveVersionId, active?.id ?? null, ); } const [{ max } = { max: 0 }] = await scopedDb .select({ max: sql`coalesce(max(${schema.rigVersions.version}), 0)::int`, }) .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ); const nextVersion = Number(max) + 1; const providerImages = await retainRigProviderImageArtifacts( scopedDb, workspaceId, input.providerImages ?? {}, ); await scopedDb .update(schema.rigVersions) .set({ active: false }) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.active, true), ), ); const [versionRow] = await scopedDb .insert(schema.rigVersions) .values({ accountId: rig.accountId, workspaceId, rigId, version: nextVersion, image: null, setupScript: input.setupScript ?? null, checks: input.checks ?? [], credentialHooks: input.credentialHooks ?? [], changelog: input.changelog ?? null, providerImages, createdBy: input.createdBy ?? null, active: true, }) .returning(); if (!versionRow) { throw new Error("Failed to create sandbox environment version"); } const [changeRow] = await scopedDb .update(schema.rigChanges) .set({ status: "merged", resultVersionId: versionRow.id, updatedAt: new Date(), }) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .returning(); if (!changeRow) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } await scopedDb .update(schema.rigs) .set({ updatedAt: new Date() }) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))); return { version: mapRigVersion(versionRow), change: mapRigChange(changeRow), }; }); } export async function listRigVersions( db: Database, workspaceId: string, rigId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ) .orderBy(desc(schema.rigVersions.version)); return rows.map(mapRigVersion); }); } export type RigVersionMonitoringSummary = { id: string; rigId: string; version: number; active: boolean; image: string | null; imageOriginalChars: number | null; setupScriptBytes: number; checkCount: number; credentialHookCount: number; changelog: string | null; changelogOriginalChars: number | null; createdBy: string | null; createdAt: string; }; /** Compact-by-query historical rig versions for the model-facing MCP surface. */ export async function listRigVersionMonitoringSummaries( db: Database, workspaceId: string, rigId: string, limit = 20, ): Promise<{ versions: RigVersionMonitoringSummary[]; hasMore: boolean; total: number; }> { const boundedLimit = Math.max(1, Math.min(100, Math.floor(limit))); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ id: schema.rigVersions.id, rigId: schema.rigVersions.rigId, version: schema.rigVersions.version, active: schema.rigVersions.active, image: sql`left(${schema.rigVersions.image}, 512)`, imageOriginalChars: sql`char_length(${schema.rigVersions.image})::int`, setupScriptBytes: sql`octet_length(coalesce(${schema.rigVersions.setupScript}, ''))::int`, checkCount: sql`jsonb_array_length(${schema.rigVersions.checks})::int`, credentialHookCount: sql`jsonb_array_length(${schema.rigVersions.credentialHooks})::int`, changelog: sql`left(${schema.rigVersions.changelog}, 600)`, changelogOriginalChars: sql< number | null >`char_length(${schema.rigVersions.changelog})::int`, createdBy: sql`left(${schema.rigVersions.createdBy}, 200)`, createdAt: schema.rigVersions.createdAt, }) .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ) .orderBy(desc(schema.rigVersions.version), desc(schema.rigVersions.id)) .limit(boundedLimit + 1); const [{ total } = { total: 0 }] = await scopedDb .select({ total: sql`count(*)::int` }) .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId)), ); return { versions: rows.slice(0, boundedLimit).map((row) => ({ ...row, setupScriptBytes: Number(row.setupScriptBytes), checkCount: Number(row.checkCount), credentialHookCount: Number(row.credentialHookCount), imageOriginalChars: row.imageOriginalChars === null ? null : Number(row.imageOriginalChars), changelogOriginalChars: row.changelogOriginalChars === null ? null : Number(row.changelogOriginalChars), createdAt: row.createdAt.toISOString(), })), hasMore: rows.length > boundedLimit, total: Number(total), }; }); } export async function getRigVersion( db: Database, workspaceId: string, rigId: string, versionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.id, versionId), ), ) .limit(1); return row ? mapRigVersion(row) : null; }); } /** Credential-free exact retained Rig metadata under the target workspace's * scoped organization/user authority. Unlike the physical-workspace helpers, * this remains valid for a personal-origin Rig granted into another workspace. */ export async function getScheduledScopedRigVersionMetadata( db: Database, access: RigAccessContext, rigId: string, versionId: string, ): Promise<{ name: string; version: RigVersion; health: RigVerificationHealth; } | null> { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: { name: string; version: RigVersion; health: RigVerificationHealth; } | null; }>( scopedDb, sql`select scheduled_scoped_rig_version_metadata( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${access.subjectId}, ${rigId}::uuid, ${versionId}::uuid ) as value`, ); return row?.value ?? null; }); } export async function materializeRigVersionForAttempt( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; }, ): Promise<{ rigName: string; version: RigVersion } | null> { return await withRlsContext(db, input, async (scopedDb) => { if (input.subjectId) { await setSubjectRlsContext(scopedDb, input.subjectId); await scopedDb.execute(sql`select set_config( 'opengeni.initiating_human_subject_id', ${input.subjectId}, true )`); } const [row] = await rawRows<{ value: { rigName: string; version: RigVersion } | null; }>( scopedDb, sql`select materialize_scoped_rig_version_for_attempt( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer ) as value`, ); return row?.value ?? null; }); } /** Metadata-only health for one exact frozen rig version. Never reads setup, * variable values, credential material, or the currently active version. */ export async function getRigVersionHealth( db: Database, workspaceId: string, rigId: string, versionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.id, versionId), ), ) .limit(1); if (!row) return null; const version = mapRigVersion(row); const healthByVersion = await loadRigHealthByActiveVersion(scopedDb, workspaceId, [version]); return healthByVersion.get(version.id) ?? unknownRigHealth(version); }); } export async function getRigVersionById( db: Database, workspaceId: string, versionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigVersions) .where( and(eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.id, versionId)), ) .limit(1); return row ? mapRigVersion(row) : null; }); } export type RigProviderImageBuildClaim = | { status: "claimed"; image: RigProviderImage; /** The record this claim replaced, if any: a provider image it named is * no longer referenced once the new build is published. */ replaced: RigProviderImage | null; } | { status: "ready" | "in_progress" | "unsupported" | "conflict"; image: RigProviderImage; }; async function retainRigProviderImageArtifacts( db: Database, workspaceId: string, images: RigProviderImages, ): Promise { const retained: RigProviderImages = {}; for (const [backend, image] of Object.entries(images) as Array< [SandboxBackend, RigProviderImage] >) { if (image.status !== "ready" || backend !== "modal") { retained[backend] = image; continue; } if (!image.artifactId || !image.imageId || !image.providerBindingKeyHash) continue; const [artifact] = await db .select({ id: schema.sandboxCheckpointArtifacts.id, providerBindingKey: schema.sandboxCheckpointArtifacts.providerBindingKey, }) .from(schema.sandboxCheckpointArtifacts) .where( and( eq(schema.sandboxCheckpointArtifacts.id, image.artifactId), eq(schema.sandboxCheckpointArtifacts.workspaceId, workspaceId), eq(schema.sandboxCheckpointArtifacts.providerBackend, "modal"), eq(schema.sandboxCheckpointArtifacts.objectKind, "modal_filesystem_snapshot"), eq(schema.sandboxCheckpointArtifacts.objectId, image.imageId), inArray(schema.sandboxCheckpointArtifacts.state, ["candidate", "current"]), ), ) .for("update") .limit(1); const bindingHash = artifact ? `sha256:${createHash("sha256").update(artifact.providerBindingKey, "utf8").digest("hex")}` : null; if (!artifact || bindingHash !== image.providerBindingKeyHash) continue; // Checkpoint states `current` and `previous` are reserved for exact lease // references by the ledger's deferred integrity trigger. Rig ownership is // the transactionally published providerImages.artifactId reference, so a // rig-owned artifact remains a candidate and the global GC function skips // it while that ready reference exists. retained[backend] = image; } return retained; } /** * Claim the one provider-image build slot for an existing immutable rig * version. The setup hash fences definition drift. Deployment base-image and * provider-image protocol rotations may replace operational metadata for the * same setup; late finalizers remain fenced by the build request id. */ export async function claimRigVersionProviderImageBuild( db: Database, input: { workspaceId: string; versionId: string; image: RigProviderImage; staleAfterMs: number; /** Retry a same-content unsupported record only after runtime support exists. */ retryUnsupported?: boolean; }, ): Promise { const candidate = RigProviderImageContract.parse(input.image); if (candidate.status !== "building") { throw new Error("Sandbox Environment provider image build claims require status=building"); } return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, input.workspaceId), eq(schema.rigVersions.id, input.versionId), ), ) .for("update") .limit(1); if (!row) throw new Error(`Sandbox Environment version not found: ${input.versionId}`); const existing = row.providerImages[candidate.backend]; if (existing) { const sameContent = existing.contentHash === candidate.contentHash && existing.setupHash === candidate.setupHash && existing.sourceImage === candidate.sourceImage; const sameSetup = existing.setupHash === candidate.setupHash; if (existing.status === "ready") { if (sameContent) { const retained = await retainRigProviderImageArtifacts(scopedDb, input.workspaceId, { [existing.backend]: existing, }); if (retained[existing.backend] && existing.coldBootValidation?.version === 1) { return { status: "ready", image: existing }; } } } if (existing.status === "unsupported" && sameContent && !input.retryUnsupported) { return { status: "unsupported", image: existing }; } if (!sameContent && !sameSetup) { return { status: "conflict", image: existing }; } if (sameContent && existing.status === "building") { const startedAtMs = Date.parse(existing.startedAt); if ( Number.isFinite(startedAtMs) && Date.now() - startedAtMs < Math.max(1, input.staleAfterMs) ) { return { status: "in_progress", image: existing }; } } } // Failed or stale retries retain the provider idempotency key only when it // belongs to the current build protocol. A protocol upgrade deliberately // mints a new key so an older immutable image cannot masquerade as a newly // validated build of the same logical definition. const claimed = RigProviderImageContract.parse({ ...candidate, ...(existing?.buildRequestId === candidate.buildRequestId ? { buildRequestId: existing.buildRequestId } : {}), }); const providerImages: RigProviderImages = { ...row.providerImages, [claimed.backend]: claimed, }; await scopedDb .update(schema.rigVersions) .set({ providerImages }) .where( and( eq(schema.rigVersions.workspaceId, input.workspaceId), eq(schema.rigVersions.id, input.versionId), ), ); return { status: "claimed", image: claimed, replaced: existing ?? null }; }); } /** Finalize only the exact claimed build request; late callbacks are fenced. * A build that takes over an abandoned claim of the same content keeps the * deterministic build request id, so the claim's start time tells the two * builds apart: the stopped build cannot publish over the one that replaced * it. */ export async function finalizeRigVersionProviderImageBuild( db: Database, input: { workspaceId: string; versionId: string; image: RigProviderImage; }, ): Promise { const finalized = RigProviderImageContract.parse(input.image); if (finalized.status === "building") { throw new Error("Sandbox Environment provider image finalization requires a terminal status"); } return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, input.workspaceId), eq(schema.rigVersions.id, input.versionId), ), ) .for("update") .limit(1); if (!row) throw new Error(`Sandbox Environment version not found: ${input.versionId}`); const current = row.providerImages[finalized.backend]; if ( current?.status !== "building" || current.buildRequestId !== finalized.buildRequestId || current.startedAt !== finalized.startedAt || current.contentHash !== finalized.contentHash || current.setupHash !== finalized.setupHash ) { return ( current?.status === finalized.status && current.buildRequestId === finalized.buildRequestId && current.startedAt === finalized.startedAt && current.contentHash === finalized.contentHash ); } if (finalized.status === "ready") { const retained = await retainRigProviderImageArtifacts(scopedDb, input.workspaceId, { [finalized.backend]: finalized, }); if (!retained[finalized.backend]) return false; } const providerImages: RigProviderImages = { ...row.providerImages, [finalized.backend]: finalized, }; await scopedDb .update(schema.rigVersions) .set({ providerImages }) .where( and( eq(schema.rigVersions.workspaceId, input.workspaceId), eq(schema.rigVersions.id, input.versionId), ), ); return true; }); } // M3 runtime: the rig's display name only (for the turn's doctrine block + setup // events/errors), without the extra active-version + count reads getRig does. export async function getRigName( db: Database, workspaceId: string, rigId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ name: schema.rigs.name }) .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .limit(1); return row?.name ?? null; }); } // Flips which version is active (rollback / promote-activate). Row-locks the rig // to serialize concurrent activations, deactivates the current active, activates // the target. Only touches the `active` flag — never content. export async function activateRigVersion( db: Database, workspaceId: string, rigId: string, versionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [rig] = await scopedDb .select({ id: schema.rigs.id }) .from(schema.rigs) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))) .for("update") .limit(1); if (!rig) { throw new Error(`Sandbox Environment not found: ${rigId}`); } const [target] = await scopedDb .select({ id: schema.rigVersions.id }) .from(schema.rigVersions) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.id, versionId), ), ) .limit(1); if (!target) { throw new Error(`Sandbox Environment version not found: ${versionId}`); } await scopedDb .update(schema.rigVersions) .set({ active: false }) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.active, true), ), ); const [row] = await scopedDb .update(schema.rigVersions) .set({ active: true }) .where( and( eq(schema.rigVersions.workspaceId, workspaceId), eq(schema.rigVersions.rigId, rigId), eq(schema.rigVersions.id, versionId), ), ) .returning(); if (!row) { throw new Error(`Sandbox Environment version not found: ${versionId}`); } await scopedDb .update(schema.rigs) .set({ updatedAt: new Date() }) .where(and(eq(schema.rigs.workspaceId, workspaceId), eq(schema.rigs.id, rigId))); return mapRigVersion(row); }); } export async function createRigChange( db: Database, input: { accountId: string; workspaceId: string; rigId: string; baseVersionId?: string | null; kind: RigChangeKind; payload: Record; proposedBy?: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.rigChanges) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, rigId: input.rigId, baseVersionId: input.baseVersionId ?? null, kind: input.kind, payload: input.payload, status: "proposed", proposedBy: input.proposedBy ?? null, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!row) { throw new Error("Failed to create sandbox environment change"); } return mapRigChange(row); }, ); } export async function listRigChanges( db: Database, workspaceId: string, rigId: string, limit = 100, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.rigId, rigId)), ) .orderBy(desc(schema.rigChanges.createdAt)) .limit(limit); return rows.map(mapRigChange); }); } export type RigChangeMonitoringSummary = { id: string; rigId: string; baseVersionId: string | null; kind: RigChangeKind; status: RigChangeStatus; proposedBy: string | null; resultVersionId: string | null; commandPreview: string | null; commandOriginalChars: number | null; payloadBytes: number; verificationBytes: number; verificationLogBytes: number; verificationStartedAt: string | null; verificationFinishedAt: string | null; verificationPassed: boolean | null; createdAt: string; updatedAt: string; }; /** Compact-by-query recent rig changes for the model-facing MCP surface. */ export async function listRigChangeMonitoringSummaries( db: Database, workspaceId: string, rigId: string, limit = 20, ): Promise<{ changes: RigChangeMonitoringSummary[]; hasMore: boolean; total: number; }> { const boundedLimit = Math.max(1, Math.min(100, Math.floor(limit))); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ id: schema.rigChanges.id, rigId: schema.rigChanges.rigId, baseVersionId: schema.rigChanges.baseVersionId, kind: schema.rigChanges.kind, status: schema.rigChanges.status, proposedBy: sql`left(${schema.rigChanges.proposedBy}, 200)`, resultVersionId: schema.rigChanges.resultVersionId, commandPreview: sql`left(${schema.rigChanges.payload}->>'command', 600)`, commandOriginalChars: sql< number | null >`char_length(${schema.rigChanges.payload}->>'command')::int`, payloadBytes: sql`octet_length(${schema.rigChanges.payload}::text)::int`, verificationBytes: sql`octet_length(coalesce(${schema.rigChanges.verification}::text, 'null'))::int`, verificationLogBytes: sql`octet_length(coalesce(${schema.rigChanges.verification}->>'log', ''))::int`, verificationStartedAt: sql< string | null >`left(${schema.rigChanges.verification}->>'startedAt', 64)`, verificationFinishedAt: sql< string | null >`left(${schema.rigChanges.verification}->>'finishedAt', 64)`, verificationPassed: sql`case when ${schema.rigChanges.verification}->>'passed' = 'true' then true when ${schema.rigChanges.verification}->>'passed' = 'false' then false else null end`, createdAt: schema.rigChanges.createdAt, updatedAt: schema.rigChanges.updatedAt, }) .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.rigId, rigId)), ) .orderBy(desc(schema.rigChanges.createdAt), desc(schema.rigChanges.id)) .limit(boundedLimit + 1); const [{ total } = { total: 0 }] = await scopedDb .select({ total: sql`count(*)::int` }) .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.rigId, rigId)), ); return { changes: rows.slice(0, boundedLimit).map((row) => ({ ...row, kind: row.kind as RigChangeKind, status: row.status as RigChangeStatus, commandOriginalChars: row.commandOriginalChars === null ? null : Number(row.commandOriginalChars), payloadBytes: Number(row.payloadBytes), verificationBytes: Number(row.verificationBytes), verificationLogBytes: Number(row.verificationLogBytes), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), })), hasMore: rows.length > boundedLimit, total: Number(total), }; }); } export async function getRigChange( db: Database, workspaceId: string, changeId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .limit(1); return row ? mapRigChange(row) : null; }); } // Advances a change's lifecycle. merged/rejected are terminal (any attempted // transition throws RigChangeTransitionError). A supplied verification payload is // shallow-merged onto the existing one so a status bump can enrich it (M4). export async function updateRigChangeStatus( db: Database, workspaceId: string, changeId: string, input: { status: RigChangeStatus; verification?: Record | null; resultVersionId?: string | null; }, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [current] = await scopedDb .select() .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .for("update") .limit(1); if (!current) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } const terminal = current.status === "merged" || current.status === "rejected"; if (terminal) { throw new RigChangeTransitionError(changeId, current.status, input.status); } const currentVerification = fromPostgresLosslessJson( current.verification, current.verificationCodecVersion, ); const mergedVerification = input.verification ? { ...((currentVerification as Record | null) ?? {}), ...input.verification, } : undefined; const [row] = await scopedDb .update(schema.rigChanges) .set({ status: input.status, ...(mergedVerification !== undefined ? { verification: mergedVerification, verificationCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, } : {}), ...(input.resultVersionId !== undefined ? { resultVersionId: input.resultVersionId } : {}), updatedAt: new Date(), }) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .returning(); if (!row) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } return mapRigChange(row); }); } export async function beginRigChangeVerificationAttempt( db: Database, workspaceId: string, changeId: string, input: { startedAt: string; allowAlreadyVerifying?: boolean; }, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [current] = await scopedDb .select() .from(schema.rigChanges) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .for("update") .limit(1); if (!current) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } if (current.status === "verifying") { if (input.allowAlreadyVerifying) { return mapRigChange(current); } throw new RigChangeAlreadyVerifyingError(changeId); } if (current.status === "merged") { throw new RigChangeTransitionError(changeId, current.status, "verifying"); } const previousVerification = (fromPostgresLosslessJson(current.verification, current.verificationCodecVersion) as Record< string, unknown > | null) ?? {}; const previousAttempt = typeof previousVerification.attempt === "number" ? previousVerification.attempt : 0; const [row] = await scopedDb .update(schema.rigChanges) .set( withLosslessContentWriteVersion( { status: "verifying", verification: { ...previousVerification, attempt: previousAttempt + 1, startedAt: input.startedAt, checkResults: [], finishedAt: null, passed: null, error: null, }, updatedAt: new Date(), }, "verification", "verificationCodecVersion", ), ) .where( and(eq(schema.rigChanges.workspaceId, workspaceId), eq(schema.rigChanges.id, changeId)), ) .returning(); if (!row) { throw new Error(`Sandbox Environment change not found: ${changeId}`); } return mapRigChange(row); }); } /** * Live session authority epoch, for stamping viewer-facing claims (stream * tokens, viewer holders). Identity/epoch only; NULL when the session is not * visible in this workspace. */ export async function getSessionAuthorityEpoch( db: Database, input: { accountId: string; workspaceId: string; sessionId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await rawRows<{ epoch: number }>( scopedDb, sql`select authority_epoch::int as epoch from sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and id = ${input.sessionId}`, ); return row?.epoch ?? null; }, ); } /** * ORACLE, NOT AN AUTHORIZATION. It sets `opengeni.subject_id` from its own * argument, so `list_self_organization_memberships`' `42501` guard is satisfied * for whatever subject the caller NAMES: it answers for ANY subject and cannot * establish who the caller is. Passing it a request-derived subject is a * vulnerability. Call it only about a subject you are already entitled to ask * about — one authenticated out of band, or the frozen owner of a delegation * you already hold. The `named` prefix is the warning: you are naming a subject, * not proving you are one. * * When the subject IS the caller, use {@link subjectHasLiveWorkspaceAuthorityInScope} * instead: it refuses to set the subject GUC at all, so the oracle shape is * unrepresentable there. Both exist on purpose — some callers legitimately ask * about a non-caller subject, which the in-scope variant cannot express. * * The authority rule itself lives in that in-scope variant; this is a scope * wrapper over it, so there is one implementation. * * The prior `opengeni.subject_id` is restored before returning, so probing a * named subject cannot leak it into the rest of a caller's transaction. */ export async function namedSubjectHasLiveWorkspaceAuthority( db: Database, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: null }, async (scopedDb) => { // `withRlsContext` restores account_id/workspace_id when it unwinds a // nested scope, but NOT subject_id — so without this the probed subject // would leak out of the savepoint and silently re-scope the caller's // remaining statements to whoever was probed. Restore it explicitly. // Empty string is the canonical "unset": `current_subject_id()` is // `nullif(current_setting(...), '')` (0239 precedent), so restoring "" on // a transaction that had no subject leaves it genuinely unset rather than // pinning it to a literal empty subject. const priorSubjectId = await rlsSubjectIdOrEmpty(scopedDb); let completed = false; try { await setSubjectRlsContext(scopedDb, input.subjectId); const result = await subjectHasLiveWorkspaceAuthorityInScope(scopedDb, input); completed = true; return result; } finally { const restore = scopedDb.execute( sql`select set_config('opengeni.subject_id', ${priorSubjectId}, true)`, ); if (completed) { await restore; } else { // A failed statement can leave a caller-owned transaction aborted. // Preserve the original diagnostic rather than replacing it with the // restore's `25P02`; that transaction is unwinding to rollback anyway. await restore.catch(() => undefined); } } }, ); } /** * The ONLY place a Slack request may reach a managed human's personal * workspace. Returns the grant a routed Slack target may act under, or null. * * A Slack webhook has no caller subject: `subjectId` is read out of band from a * durable `slack_bot_user_links` row, whose only writers sit behind a verified * managed-human cookie or a `members:manage` grant. That is why this uses * {@link namedSubjectHasLiveWorkspaceAuthority} rather than the in-scope * variant - the subject was authenticated elsewhere, and this seam is naming * it, not proving it. Callers must therefore never pass a subject taken from a * Slack payload; pass only `link.subjectId`. * * Ordinary membership first, then a derived-and-fenced pointer path (the same * shape as `requirePersonalGitHubCallbackGrant`): * * - `getWorkspaceGrant` is a bare `workspace_memberships` join and is NOT * widened here, because `accessGrantAuthorization` calls it for every * principal kind including API keys and delegated bearers; widening it would * hand a bearer principal personal-workspace access. * - The pointer path accepts only the subject's OWN `personalWorkspaceId` from * an ACTIVE membership in exactly `targetAccountId`, then re-checks live * authority. The workspace id is never taken from a route row or a Slack * payload - it must equal the pointer. * - No Slack branch is ever added to `canonicalManagedCookieContexts`: that * `WeakSet` has exactly one writer, the Better Auth cookie branch of * `resolveAccessContext`, and a Slack-signed webhook can never be in it. * * Slack sessions stay `workspace_shared`: this grant is passed as an ordinary * grant, and `createSessionForRequest` is still called WITHOUT its * `authorization` argument, so Slack privacy remains * `slack_interactions.visibility`. */ export async function resolveSlackTargetAuthority( db: Database, input: { subjectId: string; targetAccountId: string; targetWorkspaceId: string; }, ): Promise { const grant = await getWorkspaceGrant(db, input.subjectId, input.targetWorkspaceId, { principalKind: "human_session", }); const membershipGrant = grant && grant.accountId === input.targetAccountId ? grant : null; // Both arms answer to the same rule. `getWorkspaceGrant` is a bare membership // join: it cannot see that the organization membership behind that row was // suspended or offboarded, so returning it verbatim would keep serving a // person the organization has already removed. `namedSubjectHasLiveWorkspaceAuthority` // is the canonical implementation of "does this subject hold authority here", // and it covers both a persisted membership row and the personal-workspace // pointer, so it is applied before either grant shape is returned. const personalWorkspaceId = membershipGrant ? null : await namedSubjectPersonalWorkspaceId(db, { accountId: input.targetAccountId, subjectId: input.subjectId, }); if (!membershipGrant && personalWorkspaceId !== input.targetWorkspaceId) return null; const live = await namedSubjectHasLiveWorkspaceAuthority(db, { accountId: input.targetAccountId, workspaceId: input.targetWorkspaceId, subjectId: input.subjectId, }); if (!live) return null; if (membershipGrant) return membershipGrant; return { workspaceId: input.targetWorkspaceId, accountId: input.targetAccountId, subjectId: input.subjectId, permissions: managedPersonalWorkspacePermissions, principalKind: "human_session", }; } /** * Read-only organization tenancy inventory (0285): content-free counts of * every legacy-attribution population the backfill/parity program gates on. * Integers only - no identities, names, keys, or values. */ export async function inventoryOrganizationTenancy( db: Database, input: { organizationId: string }, ): Promise> { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select inventory_organization_tenancy(${input.organizationId}) as result`, ); return (row?.result ?? {}) as Record; }, ); } /** * How much independent evidence a parity gate carries. * * - `constraint` / `trigger`: the property is already enforced by the physical * schema, so the gate is a shadow verification that the enforcement is still * present and validated - it cannot be the first line of defence. * - `runtime`: nothing in the schema prevents the violation. These are the * gates that carry real evidence about a cutover. */ export type TenancyParityGateBasis = "constraint" | "trigger" | "runtime"; export interface TenancyParityGateDefinition { readonly id: string; readonly title: string; readonly basis: TenancyParityGateBasis; /** What a violation means, and why it must never resolve to user authority. */ readonly rule: string; } export interface TenancyParityGateResult extends TenancyParityGateDefinition { readonly status: "pass" | "fail"; readonly violations: number; /** Bounded row identifiers only - never subjects, names, keys, or values. */ readonly evidence: readonly string[]; readonly evidenceTruncated: boolean; } export interface TenancyParityLaneDefinition { readonly id: string; readonly title: string; /** * `drainable`: a backfill can take it to zero. * `observation`: immutable history, reported over a bounded recent window so * that "the lane stopped being exercised" is still a reachable zero. */ readonly kind: "drainable" | "observation"; /** The workstream that owns draining this lane, when it is not this one. */ readonly owner?: string; } export interface TenancyParityLaneResult extends TenancyParityLaneDefinition { readonly count: number; readonly drained: boolean; } export interface TenancyParityUnverifiable { readonly id: string; readonly title: string; /** Why no honest number exists for this property today. */ readonly reason: string; } export interface TenancyParityReport { readonly schemaVersion: 1; readonly organizationId: string; readonly generatedAt: string; readonly evidenceLimit: number; readonly observationWindowDays: number; /** `fail` when any invariant gate has at least one violation. */ readonly status: "pass" | "fail"; /** Every gate passes AND every compatibility lane is drained. */ readonly cutoverReady: boolean; readonly summary: { readonly gates: number; readonly gatesFailed: number; readonly violations: number; readonly lanes: number; readonly lanesUndrained: number; readonly unverifiable: number; }; readonly gates: readonly TenancyParityGateResult[]; readonly lanes: readonly TenancyParityLaneResult[]; readonly unverifiable: readonly TenancyParityUnverifiable[]; } /** * Ordered catalog of the organization-tenancy parity gates (phase E). Every id * matches a key emitted by `check_organization_tenancy_parity` (migration * 0298); a gate present here but absent from the seam is reported as a * structural mismatch rather than silently passing. */ export const TENANCY_PARITY_GATES: readonly TenancyParityGateDefinition[] = [ { id: "membership_personal_workspace_pointer", title: "Every active organization membership identifies a personal workspace", basis: "constraint", rule: "organization_memberships_active_personal_workspace_check (0218).", }, { id: "membership_personal_workspace_exclusive", title: "A personal workspace identifies at most one organization membership", basis: "constraint", rule: "organization_memberships_personal_workspace_idx (0218) partial unique index.", }, { id: "membership_personal_workspace_same_organization", title: "A personal workspace belongs to the membership's organization", basis: "constraint", rule: "organization_memberships_personal_workspace_account_fk (0218) composite FK.", }, { id: "personal_workspace_has_no_membership_row", title: "A managed personal workspace's only workspace_memberships row is its active owner's", basis: "runtime", rule: "Migration 1231 keeps exactly one row there: the active owner's, role member with " + "personal_workspace_owner_permissions(). Any other row (another subject's, an " + "administering one, or one whose owner is no longer active) is exactly how " + "membership CRUD and the subject-membership fallback would widen it into shared access.", }, { id: "authority_resource_single_owner", title: "One owning membership per user resource", basis: "runtime", rule: "The physical unique index is per (account, membership, kind, resource), so two " + "different memberships can still claim one resource. The ambiguity is reported; " + "it must never be resolved toward either claimant's user authority.", }, { id: "grant_delegation_fence_complete", title: "Zero partial delegations", basis: "constraint", rule: "organization_user_resource_grants_session_fence_check (0218).", }, { id: "grant_owner_membership_active", title: "An active grant's owning organization membership is active", basis: "runtime", rule: "Suspension revokes personal-resource grants and offboarding runs the same " + "teardown. A live delegation owned by a suspended or revoked human is a fallback " + "to user authority.", }, { id: "grant_authority_live", title: "An active grant's user-resource authority is not revoked", basis: "runtime", rule: "Revocation is immediate; an active grant over a revoked authority outlives it.", }, { id: "grant_session_fence_not_ahead", title: "A session-fenced grant's epoch is never ahead of its session", basis: "runtime", rule: "Authority epochs are monotonic and the fence is copied from the session at " + "issuance, so a higher grant epoch would survive the advance meant to revoke it.", }, { id: "session_owner_provenance_paired", title: "Session owner provenance is complete and paired", basis: "trigger", rule: "guard_session_authority_write (0225) raises 23514 on a half-set owner pair or a " + "user_private session with no owner.", }, { id: "session_owner_subject_matches_membership", title: "A session's denormalized owner subject names its owning membership", basis: "runtime", rule: "The pair is written together but nothing keeps it consistent afterwards.", }, { id: "session_owner_membership_same_organization", title: "A session's owning membership exists in the session's organization", basis: "constraint", rule: "sessions_owner_membership_fk (0218) composite FK.", }, { id: "login_binding_dispute_propagated", title: "A disputed login binding disputed its canonical identity", basis: "runtime", rule: "The (provider, provider_account) unique index makes a duplicate binding " + "impossible, so a provider-account collision is recorded by disputing the " + "existing binding AND both identities. A disputed binding whose identity is still " + "usable is a collision that never fenced its identity.", }, { id: "identity_active_binding_owned", title: "A canonical identity's active login binding is its own", basis: "runtime", rule: "canonical_human_identities_active_binding_fk proves existence, never ownership.", }, { id: "user_scoped_resource_live_anchor", title: "Shadow scope comparison: every user-scope claim has a live anchor", basis: "runtime", rule: "Legacy effective scope is workspace for every resource. A connection, variable " + "set, rig, Connected Machine, or Document whose proposed effective scope is user " + "must have an active authority owned by an active membership. Without one there " + "is no reachable user resolution: it must fall back to workspace or deny.", }, ]; /** * Compatibility lanes. These are legacy populations, NOT invariant violations: * a non-zero lane blocks a cutover but is not schema corruption. */ export const TENANCY_PARITY_LANES: readonly TenancyParityLaneDefinition[] = [ { // Migration 0340 bounds this lane with a deterministic subject + active // same-organization membership repair. Activation then fences new minting // and hides any unresolved legacy row from runtime reads. id: "connectionsLegacyUser", title: "Connections on the legacy_user authority lane (drainable after the membership backfill)", kind: "drainable", owner: "organization-membership backfill", }, { id: "workspaceWriterAdmissionsLegacyUnattributedInWindow", title: "Workspace writer admissions with legacy_unattributed authority in the observation window", kind: "observation", }, { id: "workspaceWriterProcessesLegacyUnattributedInWindow", title: "Retained workspace processes with legacy_unattributed authority in the observation window", kind: "observation", }, { id: "documentsLegacyPersonalNullAuthority", title: "Legacy personal Documents with no common authority", kind: "drainable", owner: "document authority migration", }, { id: "codexCredentialsUnattributedConnector", title: "Codex subscription credentials with no recorded connecting human", kind: "drainable", owner: "Codex connector ownership repair", }, { id: "workspaceMemberSubjectsWithoutMembershipAnchor", title: "Humans with workspace access but no organization-membership anchor", kind: "drainable", }, { id: "sessionsAttributableButUnattributed", title: "Ownerless sessions whose creator today's write fence would attribute", kind: "drainable", }, { id: "connectionUseLegacyResolutionsInWindow", title: "Legacy/pre-snapshot connection resolutions inside the observation window", kind: "observation", }, ]; /** * Properties phase E names that have no honest measurement today. They are * reported explicitly instead of being emitted as a counter that can never * reach zero. */ export const TENANCY_PARITY_UNVERIFIABLE: readonly TenancyParityUnverifiable[] = [ { id: "variableSetsLegacyClassification", title: "Variable Sets awaiting explicit authority classification", reason: "workspace_variable_sets.authority_scope defaults to 'workspace' and " + "workspace_variable_sets_authority_shape_check REQUIRES authority_id IS NULL for " + "organization/workspace scope. A never-classified legacy row and a deliberately " + "workspace-owned row are therefore byte-identical: no discriminator exists. Any " + "'unclassified' counter here is structurally total minus user-scoped and can " + "never drain to zero.", }, { id: "rigsLegacyClassification", title: "Rigs awaiting explicit authority classification", reason: "Same shape as Variable Sets (rigs_authority_shape_check, 0262): a legacy row and " + "a deliberate workspace row are indistinguishable.", }, { id: "machinesLegacyClassification", title: "Connected Machines awaiting explicit authority classification", reason: "Same shape as Variable Sets (enrollments_authority_shape_check, 0262): a legacy " + "row and a deliberate workspace row are indistinguishable.", }, { id: "sessionsDefaultVisibility", title: "Sessions still on the default visibility", reason: "'workspace_shared' is the permanent correct visibility for a shared session, not " + "a legacy marker. Counting it would count the intended steady state forever.", }, { id: "sessionsOwnerless", title: "Sessions with no owning organization membership", reason: "A null owner is legitimate forever for API-key, delegated, and service-created " + "sessions, and for creators with no active organization membership - " + "guard_session_authority_write (0225, repaired by 0302) attributes only " + "subject-created sessions whose creator holds an active organization membership " + "AND stated authority over that workspace: a workspace_memberships row, or the " + "membership's own personal_workspace_id pointer. Only that attributable subset " + "is drainable; migration 0340 measures both stated-authority forms in the " + "'sessionsAttributableButUnattributed' lane.", }, ]; interface RawTenancyParityGate { violations?: number; evidence?: unknown; truncated?: boolean; } /** * Compose the operator-facing parity report from the raw seam output. Pure and * total: an id the seam did not emit is reported as a failing gate with an * explicit structural-mismatch violation rather than silently passing. */ export function composeTenancyParityReport( raw: Record, options?: { generatedAt?: string }, ): TenancyParityReport { const rawGates = (raw.gates ?? {}) as Record; const rawLanes = (raw.lanes ?? {}) as Record; const gates: TenancyParityGateResult[] = TENANCY_PARITY_GATES.map((definition) => { const observed = rawGates[definition.id]; if (!observed || typeof observed.violations !== "number") { return { ...definition, status: "fail" as const, violations: Number.NaN, evidence: [], evidenceTruncated: false, }; } const evidence = Array.isArray(observed.evidence) ? observed.evidence.filter((entry): entry is string => typeof entry === "string") : []; return { ...definition, status: observed.violations === 0 ? ("pass" as const) : ("fail" as const), violations: observed.violations, evidence, evidenceTruncated: observed.truncated === true, }; }); const lanes: TenancyParityLaneResult[] = TENANCY_PARITY_LANES.map((definition) => { const count = rawLanes[definition.id]; const resolved = typeof count === "number" ? count : Number.NaN; return { ...definition, count: resolved, drained: resolved === 0 }; }); const gatesFailed = gates.filter((gate) => gate.status === "fail").length; const lanesUndrained = lanes.filter((lane) => !lane.drained).length; const violations = gates.reduce( (total, gate) => total + (Number.isFinite(gate.violations) ? gate.violations : 0), 0, ); return { schemaVersion: 1, organizationId: String(raw.organizationId ?? ""), generatedAt: options?.generatedAt ?? new Date().toISOString(), evidenceLimit: typeof raw.evidenceLimit === "number" ? raw.evidenceLimit : 0, observationWindowDays: typeof raw.observationWindowDays === "number" ? raw.observationWindowDays : 0, status: gatesFailed === 0 ? "pass" : "fail", cutoverReady: gatesFailed === 0 && lanesUndrained === 0, summary: { gates: gates.length, gatesFailed, violations, lanes: lanes.length, lanesUndrained, unverifiable: TENANCY_PARITY_UNVERIFIABLE.length, }, gates, lanes, unverifiable: TENANCY_PARITY_UNVERIFIABLE, }; } /** * Read-only organization tenancy parity check (0298, phase E). Verifies the * structural tenancy invariants, reports the compatibility lanes, and names the * properties that are currently unverifiable. It never writes, repairs, or * widens anything, and no reported mismatch is resolved toward user authority. */ export async function checkOrganizationTenancyParity( db: Database, input: { organizationId: string; evidenceLimit?: number; observationWindowDays?: number; generatedAt?: string; }, ): Promise { const raw = await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select check_organization_tenancy_parity( ${input.organizationId}, ${input.evidenceLimit ?? 10}, ${input.observationWindowDays ?? 30} ) as result`, ); return (row?.result ?? {}) as Record; }, ); return composeTenancyParityReport( raw, input.generatedAt === undefined ? undefined : { generatedAt: input.generatedAt }, ); } /** * Organization-tenancy phase D classification assertion (0291) for Variable Sets, Rigs, and * Connected Machines. Read-only over every resource table: it proves each row * already carries an explicit terminal authority classification and never * rewrites one. Supplying `runKey` additionally records the verdicts durably * through the 0286 tenancy backfill ledger (one receipt per family plus one * append-only unresolved row per resource that could not be proven); the * result reports `ledgerAvailable` so a run that could not record its * obligations is visible rather than silent. A run key may be used once - the * ledger refuses to re-open a settled receipt. */ export async function verifyOrganizationResourceClassification( db: Database, input: { organizationId: string; runKey?: string | null }, ): Promise> { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select verify_organization_resource_classification( ${input.organizationId}, ${input.runKey ?? null}::text ) as result`, ); return (row?.result ?? {}) as Record; }, ); } /** * Organization-tenancy phase D session ownership classification (0297). Read-only over * `sessions`: it proves every attributed session points at one live, * internally consistent organization membership, and names a fixed reason code * for every session it refuses to attribute. Supplying `runKey` additionally * records those refusals durably through the tenancy backfill ledger (one * `sessions` receipt plus one append-only unresolved row each); the result * reports `ledgerAvailable` so a run that could not record its obligations is * visible rather than silent. A run key may be used once - the ledger refuses * to re-open a settled receipt. * * It never writes a session row and never infers user authority from * `created_by`, a default workspace, or current workspace access. */ export async function classifyOrganizationSessionOwnership( db: Database, input: { organizationId: string; runKey?: string | null }, ): Promise> { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select classify_organization_session_ownership( ${input.organizationId}, ${input.runKey ?? null}::text ) as result`, ); return (row?.result ?? {}) as Record; }, ); } /** * Organization-tenancy phase D session ownership backfill (0297). One bounded, resumable, * idempotent batch of the only two deterministic repairs: a session sitting in * exactly one active membership's personal workspace whose creator subject is * that same membership, and the parent-inheritance closure migration 0225's own * trigger would have produced. `dryRun` defaults to true. Candidates are * claimed with `FOR UPDATE ... SKIP LOCKED`, so concurrent drivers never * contend; keep calling while `moreLikely` is true. */ export async function backfillOrganizationSessionOwnership( db: Database, input: { organizationId: string; limit?: number; dryRun?: boolean; runKey?: string | null; }, ): Promise> { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select backfill_organization_session_ownership( ${input.organizationId}, ${input.limit ?? 500}::integer, ${input.dryRun ?? true}::boolean, ${input.runKey ?? null}::text ) as result`, ); return (row?.result ?? {}) as Record; }, ); } async function lockOrganizationMembershipLifecycle( scopedDb: Database, accountId: string, ): Promise { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${accountId}`}, 0))`, ); } export class CodexSubscriptionSourceChangeBlockedError extends Error { readonly code = "codex_subscription_source_change_blocked"; constructor() { super("Codex subscription source cannot change while active turns are using it"); this.name = "CodexSubscriptionSourceChangeBlockedError"; } } async function withOrganizationCodexAdministrator( db: Database, input: { organizationId: string; actorSubjectId: string }, use: (scopedDb: Database) => Promise, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { // Shared-workspace creation and every organization membership lifecycle // writer use this canonical prefix. Hold it before the administration // overview and before any Codex workspace inventory so a new workspace // cannot commit after the source snapshot was captured. await lockOrganizationMembershipLifecycle(scopedDb, input.organizationId); // An account administrator the request proved (for example the // deployment's configured key) has no organization membership for the // overview to find; its recorded authority is the check instead. const accountAdministrator = await setSubscriptionAdministrationSubject(scopedDb, { accountId: input.organizationId, subjectId: input.actorSubjectId, }); if (!accountAdministrator) { await scopedDb.execute(sql` select get_organization_administration_overview( ${input.organizationId}::uuid, ${input.actorSubjectId} ) `); } return await use(scopedDb); }, ); } export async function fetchOrganizationCodexUsageForAccount( db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string; }, fetchImpl: CodexFetch = fetch, refresh?: CodexAuthDeps["refresh"], ) { return await readOrganizationCodexUsage( db, settings, input, (targetDb, use) => withOrganizationCodexAdministrator(targetDb, input, use), fetchImpl, refresh, ); } /** * One organization-managed Codex connection (canonical id or legacy alias) * for an organization administrator; null when the id is not one. */ export async function findOrganizationCodexConnectionForAdministrator( db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string }, ) { return await findOrganizationCodexConnection(db, settings, input, (targetDb, use) => withOrganizationCodexAdministrator(targetDb, input, use), ); } /** * The bearer of one organization-managed Codex connection for an * organization administrator (usage limit resets on the organization page). */ export function buildOrganizationCodexAdministratorTokenResolver( db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string }, refresh?: CodexAuthDeps["refresh"], ) { return buildOrganizationCodexConnectionTokenResolver( db, settings, input, (targetDb, use) => withOrganizationCodexAdministrator(targetDb, input, use), refresh, ); } /** * The workspace that files an organization administrator's usage limit reset * redemptions for organization-managed accounts (the redemption ledger is * kept per workspace): the oldest workspace they belong to, else the * organization's oldest. The choice is stable, so prepare, redeem and the * overview's recovery read all see the same attempts; the cross-workspace * credit fence still keeps one logical redemption per provider credit. */ export async function resolveOrganizationCodexRedemptionWorkspace( db: Database, input: { organizationId: string; actorSubjectId: string }, ): Promise { const { workspaces } = await getOrganizationAdministrationOverview(db, input); const ordered = [...workspaces].sort( (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), ); const own = ordered.find((workspace) => workspace.members.some((member) => member.subjectId === input.actorSubjectId), ); return (own ?? ordered[0])?.id ?? null; } /** * The organization administrator check of the organization Codex routes on * its own: the generic administration overview (42501 not authorized, P0002 * unknown organization) with no read of the legacy Codex tables, which 0680 * left read-only and blanked. The route reads the cutover row after this. */ export async function assertOrganizationCodexAdministrator( db: Database, input: { organizationId: string; actorSubjectId: string }, ): Promise { await withOrganizationCodexAdministrator(db, input, async () => undefined); } export type CodexAppsSettings = { credentialId: string | null; version: number; designatedAt: Date | null; }; /** A specific designated-credential unavailability observed at request time. */ export class CodexAppsAuthorizationRevokedError extends CodexAppsCredentialUnavailable { constructor() { super("Codex Apps authorization is no longer active"); this.name = "CodexAppsAuthorizationRevokedError"; } } /** * Single source of truth for "this workspace has an ACTIVE ChatGPT/Codex * subscription connected AND the feature is enabled for this deployment." * * This is the SAME condition `settingsWithCodexCredential` (worker) uses to * decide whether to inject the synthetic codex-subscription provider, so billing * and provider-injection cannot drift. Metadata-only read (never the secret). * * Asks the shared core whether a connection can serve new work of * `context.subjectId` here (shared capacity only without a human subject). */ export async function workspaceCodexSubscriptionActive( db: Database, settings: Pick, workspaceId: string, acceptedTurnId?: string, context: { accountId?: string | null; subjectId?: string | null } = {}, ): Promise { if (!settings.codexSubscriptionEnabled) { return false; } return await withCodexActiveReadRetry(async () => { const accountId = context.accountId ?? (await rlsContextForWorkspace(db, workspaceId)).accountId; const serving = await listSubscriptionCoreCodexServingConnections(db, { accountId, workspaceId, subjectId: context.subjectId ?? null, }); return serving.length > 0; }); } async function withCodexActiveReadRetry(read: () => Promise): Promise { // Bounded re-read. A TRANSIENT read failure (a pooled-connection blip or a // lost RLS GUC — now thrown loud by withRlsContext's read-back guard rather // than silently returning zero rows) must never permanently decide a // genuinely-active subscription is disconnected, which would throw the // fail-loud CodexSubscriptionUnavailableError at model resolution and fail the // turn. Retry only on a THROWN error (the transient signature); a cleanly // returned status — a row (any status) or a confirmed absent row (null) — is // authoritative and resolves immediately, so the common no-subscription turn // pays no extra latency. let lastError: unknown; for (let attempt = 0; attempt < CODEX_ACTIVE_READ_ATTEMPTS; attempt++) { try { return await read(); } catch (error) { lastError = error; if (attempt < CODEX_ACTIVE_READ_ATTEMPTS - 1) { await new Promise((resolve) => setTimeout(resolve, CODEX_ACTIVE_READ_RETRY_MS * (attempt + 1)), ); } } } // Every attempt threw: this is a real, persistent read outage, not a one-off // blip. Surface the underlying error (truthful + retryable) instead of // silently denying an active subscription. console.error("workspace Codex subscription credential read failed after retries", { errorClass: "CredentialReadOperationError", errorCode: "codex_active_credential_read_failed", origin: "db", }); throw lastError instanceof Error ? lastError : new Error(String(lastError)); } // Bounded re-read tuning for the codex active-credential check. A handful of // attempts with a short linear backoff rides out a transient pooler/RLS blip // without materially delaying a genuine outage's failure. const CODEX_ACTIVE_READ_ATTEMPTS = 3; const CODEX_ACTIVE_READ_RETRY_MS = 50; /** * CANONICAL "is this a Codex-billed turn?" predicate. * * True iff: the turn's model is a `codex/` id (`isCodexBilledModel`) AND * the deployment flag is on AND the workspace has an ACTIVE credential. A true * result means the turn is paid by the USER's ChatGPT/Codex plan and MUST consume * ZERO Opengeni credits: callers skip the credit-balance / model-cost / token * gates and skip Opengeni pricing + credit debit. * * The prefix ALONE never returns true: an unconnected user typing `codex/...` * gets the normal gates (and the worker fails the turn for a missing credential), * so there is no free/uncapped-run bypass. */ export async function isCodexBilledTurn(input: { db: Database; settings: Pick; workspaceId: string; model: string | null | undefined; /** The organization, when the caller holds it (saves one lookup). */ accountId?: string | null; /** * The accepted work's causal human. On the shared core their own personal * Codex connection in their Personal workspace also funds the turn. */ subjectId?: string | null; /** * Precomputed `workspaceCodexSubscriptionActive` result (P2-b). When the caller * already resolved the active flag for provider injection, pass it here so the * billed-turn predicate and the routing overlay read the credential ONCE and * cannot disagree across a concurrent disconnect/reconnect — a drift that would * either wrongly debit Opengeni credits for a ChatGPT-paid turn or the inverse. */ active?: boolean; /** Exact durable work; required for personal funding outside a Personal workspace. */ acceptedTurn?: { sessionId: string; turnId: string }; }): Promise { if (!isCodexBilledModel(input.model)) { return false; // cheap; no db hit on the common path } if (!input.settings.codexSubscriptionEnabled) return false; if (input.acceptedTurn) { const accountId = input.accountId ?? (await rlsContextForWorkspace(input.db, input.workspaceId)).accountId; const { subscriptionCoreAcceptedCodexTurnIsFunded } = await import("./subscription-core-codex"); return subscriptionCoreAcceptedCodexTurnIsFunded(input.db, { accountId, workspaceId: input.workspaceId, ...input.acceptedTurn, productModelId: input.model!, }); } if (input.active !== undefined) { return input.active; } return workspaceCodexSubscriptionActive(input.db, input.settings, input.workspaceId, undefined, { accountId: input.accountId ?? null, subjectId: input.subjectId ?? null, }); } // --------------------------------------------------------------------------- // Multi-account (P1) metadata accessors. All metadata-only — NEVER decrypt. // --------------------------------------------------------------------------- export class CodexCredentialLeaseAttemptFencedError extends Error { readonly code = "codex_credential_lease_attempt_fenced"; constructor() { super("Codex credential lease acquisition lost exact attempt ownership"); this.name = "CodexCredentialLeaseAttemptFencedError"; } } export class CodexCredentialFailoverExhaustedError extends Error { readonly code = "codex_credential_failover_exhausted"; constructor( readonly failoverCount: number, readonly maxFailovers: number, ) { super("Codex credential failover budget was already exhausted"); this.name = "CodexCredentialFailoverExhaustedError"; } } /** * Five minutes is deliberately much longer than the one-minute heartbeat and * much shorter than a five-hour allowance window. A killed worker therefore * stops biasing selection promptly, while a transient heartbeat write failure * cannot duplicate a live holder immediately. */ export const CODEX_CREDENTIAL_LEASE_TTL_MS = 5 * 60_000; function codexMetadataDate(value: Date | string | null | undefined): Date | null { if (value == null) return null; return value instanceof Date ? value : new Date(value); } // --------------------------------------------------------------------------- // Durable zero-capacity wait / wake state machine. // --------------------------------------------------------------------------- export type CodexCapacityWaitStatus = "waiting" | "resumed" | "superseded"; export type CodexCapacityResetKind = "authoritative" | "bounded_refresh" | "mutation_only"; export type CodexCapacityWait = { id: string; accountId: string; workspaceId: string; sessionId: string; goalId: string | null; blockedTurnId: string; blockedTurnGeneration: number; workflowId: string; generation: number; status: CodexCapacityWaitStatus; goalVersion: number | null; policyHash: string | null; earliestResetAt: Date | null; nextCheckAt: Date; resetKind: CodexCapacityResetKind; refreshAttempt: number; wakeRevision: number; observedWakeRevision: number; lastWakeReason: string; resumedUpdateId: string | null; createdAt: Date; updatedAt: Date; }; export type ReconcileCodexCapacityWaitResult = | { action: "waiting"; waiter: CodexCapacityWait; events: SessionEvent[] } | { action: "resumed"; waiter: CodexCapacityWait; events: SessionEvent[]; } | { action: "paused"; waiter: CodexCapacityWait; events: SessionEvent[] } | { action: "superseded"; waiter: CodexCapacityWait; events: SessionEvent[] } | { action: "stale"; waiter: CodexCapacityWait | null; events: SessionEvent[]; }; export const CODEX_CAPACITY_REFRESH_MIN_MS = 60_000; export const CODEX_CAPACITY_REFRESH_MAX_MS = 15 * 60_000; /** * Unknown/stale reset data uses bounded control-plane refresh backoff. This is * never a model turn and never consumes an entitlement. The value is pure so * crash/timer tests can pin the exact progression. */ export function codexCapacityRefreshBackoffMs(attempt: number): number { const safeAttempt = Number.isInteger(attempt) && attempt > 0 ? attempt : 0; return Math.min(CODEX_CAPACITY_REFRESH_MIN_MS * 2 ** safeAttempt, CODEX_CAPACITY_REFRESH_MAX_MS); } // --------------------------------------------------------------------------- // Durable Codex capacity waits on the shared subscription core (M3 PR 2a). // // The waiter row lives in subscription_capacity_waiters (one per session) and // exists only while the blocked turn waits: resuming or superseding deletes // it, so a stale timer or signal carrying an older waiter id finds nothing. // Workflow activity names, signal names and argument shapes are unchanged: // a core waiter is addressed by the same { waiterId, generation, nextCheckAt, // wakeRevision } reference as a legacy Codex waiter, and the activities look // the waiter id up in the core table first, then in the legacy table. // // The state machine is provider-neutral (SuperGrok track X1b): the waiter's // `provider` selects only the session-event vocabulary below, which keeps // each provider's shipped event types, reasons and codes. The Codex-named // entry points are Codex's bindings and are unchanged. // --------------------------------------------------------------------------- /** * A provider whose chat turns park on the shared core waiter. Derived from * the exhausted-code table, so a waiter provider cannot exist (nor get a wait * vocabulary) without the terminal code that human Retry replenishes. */ export type SubscriptionCoreWaiterProvider = keyof typeof SUBSCRIPTION_CORE_WAIT_EXHAUSTED_CODES; /** * The session-event vocabulary of one provider's core waiter. Codex keeps * the names its core waiter shipped with (M3); SuperGrok and Claude keep the * names of their legacy waiters, so a wait reads the same before and after * the provider's cutover. */ type SubscriptionCoreWaitVocabulary = { /** Product name in internal error texts. */ label: string; waitingEventType: "codex.capacity.waiting" | "turn.capacity_waiting"; /** Payload fields that name the wait's recovery (and the provider, when the type does not). */ waitingPayload: Record; /** `session.status.changed` reason while waiting and when resuming. */ statusReason: string; /** Why pending tool calls close when the turn parks. */ closeToolsReason: string; resumedEvent: (waiter: SubscriptionCoreCodexCapacityWait) => { type: "codex.capacity.resumed" | "turn.recovery.requested"; payload: Record; }; supersededEvent: ( waiter: SubscriptionCoreCodexCapacityWait, reason: string, ) => { type: "codex.capacity.superseded" | "turn.superseded"; payload: Record }; /** `session_turns.cancelled_by` of a superseded blocked turn. */ cancelledBy: string; /** * The provider's usage read can end a quota exhaustion before its stored * reset (its adapter's `usageReadEndsQuotaExhaustion`; a test keeps the two * equal), so a waiter rechecks on the bounded backoff, capped at the reset, * instead of sleeping until the reset. */ recheckBeforeReset: boolean; }; const SUBSCRIPTION_CORE_WAIT_VOCABULARY: { [P in SubscriptionCoreWaiterProvider]: SubscriptionCoreWaitVocabulary; } = { codex: { label: "Codex", waitingEventType: "codex.capacity.waiting", waitingPayload: { recovery: "codex_capacity", retryable: true, rotated: true }, statusReason: "codex_capacity", closeToolsReason: "codex_capacity_wait", resumedEvent: (waiter) => ({ type: "codex.capacity.resumed", payload: { waiterId: waiter.waiterId, generation: waiter.generation, wakeRevision: waiter.wakeRevision, goalId: waiter.goalId, goalVersion: waiter.goalVersion, blockedTurnGeneration: waiter.blockedTurnGeneration, policyHash: null, diagnostic: null, }, }), supersededEvent: (waiter, reason) => ({ type: "codex.capacity.superseded", payload: { waiterId: waiter.waiterId, generation: waiter.generation, reason }, }), cancelledBy: "codex_capacity_reconcile", recheckBeforeReset: true, }, xai: { label: "SuperGrok", waitingEventType: "turn.capacity_waiting", waitingPayload: { provider: "supergrok-subscription", recovery: "provider_capacity", retryable: true, }, statusReason: "xai_capacity", closeToolsReason: "xai_capacity_wait", resumedEvent: (waiter) => ({ type: "turn.recovery.requested", payload: { reason: "xai_capacity_available", provider: "supergrok-subscription", waiterId: waiter.waiterId, generation: waiter.generation, wakeRevision: waiter.wakeRevision, }, }), supersededEvent: (waiter, reason) => ({ type: "turn.superseded", payload: { provider: "supergrok-subscription", waiterId: waiter.waiterId, generation: waiter.generation, reason, }, }), cancelledBy: "xai_capacity_reconcile", recheckBeforeReset: true, }, // Claude keeps the names of its legacy waiter (Claude track C1b). claude: { label: "Claude", waitingEventType: "turn.capacity_waiting", waitingPayload: { provider: "claude-subscription", recovery: "provider_capacity", retryable: true, }, statusReason: "claude_capacity", closeToolsReason: "claude_capacity_wait", resumedEvent: (waiter) => ({ type: "turn.recovery.requested", payload: { reason: "claude_capacity_available", provider: "claude-subscription", waiterId: waiter.waiterId, generation: waiter.generation, wakeRevision: waiter.wakeRevision, }, }), supersededEvent: (waiter, reason) => ({ type: "turn.superseded", payload: { provider: "claude-subscription", waiterId: waiter.waiterId, generation: waiter.generation, reason, }, }), cancelledBy: "claude_capacity_reconcile", // Anthropic can reset a plan limit before the reset a refused request // reported, and Claude's usage read ends the stored exhaustion and model // cooldowns then, so its waiter rechecks on the bounded backoff. recheckBeforeReset: true, }, }; /** Whether a provider's core waiter rechecks before its stored reset (see the vocabulary). */ export function subscriptionCoreWaiterRechecksBeforeReset( provider: SubscriptionCoreWaiterProvider, ): boolean { return subscriptionCoreWaitVocabulary(provider).recheckBeforeReset; } function subscriptionCoreWaitVocabulary(provider: string): SubscriptionCoreWaitVocabulary { const vocabulary = SUBSCRIPTION_CORE_WAIT_VOCABULARY[provider as SubscriptionCoreWaiterProvider]; if (!vocabulary) throw new Error("Core capacity waiter has an unsupported provider"); return vocabulary; } export type SubscriptionCoreCodexCapacityWait = { waiterId: string; /** The provider whose turn waits (the Codex-named readers return only Codex rows). */ provider: SubscriptionCoreWaiterProvider; /** Fresh evaluation hints only; null denotes a legacy home-only waiter. */ candidateProviders: string[] | null; accountId: string; workspaceId: string; sessionId: string; blockedTurnId: string; blockedTurnGeneration: number | null; generation: number; wakeRevision: number; observedWakeRevision: number; waitReason: string; resetKind: string | null; refreshAttempt: number; earliestResetAt: Date | null; nextCheckAt: Date; goalId: string | null; goalVersion: number | null; lastWakeReason: string | null; /** * False when the row no longer belongs to the session's active turn in * `waiting_capacity` (a Steer, Cancel or other transition left it behind). * Only lookups compute it; rows returned by arm/reconcile are live. */ blockedTurnLive?: boolean; }; type SubscriptionCoreCodexWaiterRow = { waiter_id: string; provider: string; candidate_providers: string[] | null; account_id: string; workspace_id: string; session_id: string; turn_id: string; blocked_turn_generation: number | string | null; generation: number | string; wake_revision: number | string; observed_wake_revision: number | string; wait_reason: string; reset_kind: string | null; refresh_attempt: number | string; earliest_reset_at: Date | string | null; next_check_at: Date | string | null; goal_id: string | null; goal_version: number | string | null; last_wake_reason: string | null; updated_at: Date | string; blocked_turn_live?: boolean | null; }; const SUBSCRIPTION_CORE_CODEX_WAITER_COLUMNS = sql.raw(`waiter_id::text as waiter_id, provider, candidate_providers, account_id::text as account_id, workspace_id::text as workspace_id, session_id::text as session_id, turn_id::text as turn_id, blocked_turn_generation, generation, wake_revision, observed_wake_revision, wait_reason, reset_kind, refresh_attempt, earliest_reset_at, next_check_at, goal_id::text as goal_id, goal_version, last_wake_reason, updated_at`); /** * The providers whose turns park on the core waiter: exactly those with a * wait vocabulary. A row of any other provider is never read as a session's * core wait (the provider-neutral readers filter on this list) and fails * closed if it is ever mapped. */ const SUBSCRIPTION_CORE_WAITER_PROVIDERS = Object.keys( SUBSCRIPTION_CORE_WAIT_VOCABULARY, ) as SubscriptionCoreWaiterProvider[]; function subscriptionCoreWaiterProvider(provider: string): SubscriptionCoreWaiterProvider { if (!(SUBSCRIPTION_CORE_WAITER_PROVIDERS as string[]).includes(provider)) throw new Error("Core capacity waiter has an unsupported provider"); return provider as SubscriptionCoreWaiterProvider; } function mapSubscriptionCoreCodexWaiter( row: SubscriptionCoreCodexWaiterRow, ): SubscriptionCoreCodexCapacityWait { return { waiterId: row.waiter_id, provider: subscriptionCoreWaiterProvider(row.provider), candidateProviders: row.candidate_providers, accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, blockedTurnId: row.turn_id, blockedTurnGeneration: row.blocked_turn_generation === null ? null : Number(row.blocked_turn_generation), generation: Number(row.generation), wakeRevision: Number(row.wake_revision), observedWakeRevision: Number(row.observed_wake_revision), waitReason: row.wait_reason, resetKind: row.reset_kind, refreshAttempt: Number(row.refresh_attempt), earliestResetAt: row.earliest_reset_at === null ? null : new Date(row.earliest_reset_at), nextCheckAt: new Date(row.next_check_at ?? row.updated_at), goalId: row.goal_id, goalVersion: row.goal_version === null ? null : Number(row.goal_version), lastWakeReason: row.last_wake_reason, ...(row.blocked_turn_live === undefined || row.blocked_turn_live === null ? {} : { blockedTurnLive: row.blocked_turn_live }), }; } /** * The workflow reference for a core waiter, in the legacy Codex shape. An * unobserved wake revision (a capacity change whose signal may have been * lost, or that landed across continue-as-new) becomes an immediate check, * and so does a row that no longer belongs to the session's active waiting * turn: the reconcile then supersedes and deletes it instead of the workflow * sleeping on it until its next check. */ export function subscriptionCoreCodexCapacityWaitRef(wait: SubscriptionCoreCodexCapacityWait): { /** Absent for Codex (the legacy peek's "absent means Codex"); every other provider names itself. */ provider?: Exclude; waiterId: string; generation: number; nextCheckAt: string; wakeRevision: number; } { return { ...(wait.provider !== "codex" ? { provider: wait.provider } : {}), waiterId: wait.waiterId, generation: wait.generation, nextCheckAt: wait.wakeRevision > wait.observedWakeRevision || wait.blockedTurnLive === false ? new Date(0).toISOString() : wait.nextCheckAt.toISOString(), wakeRevision: wait.wakeRevision, }; } /** The workflow reference of any provider's core waiter (Codex's carries no `provider`). */ export const subscriptionCoreCapacityWaitRef = subscriptionCoreCodexCapacityWaitRef; /** * The session's core waiter (one per session, whatever its provider), or * only `provider`'s when given. A waiter id looks the exact row up. */ async function readSubscriptionCoreWaiterInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; waiterId?: string; forUpdate?: boolean; provider?: SubscriptionCoreWaiterProvider; }, ): Promise { const [row] = await rawRows( tx, sql`select ${SUBSCRIPTION_CORE_CODEX_WAITER_COLUMNS}, exists ( select 1 from sessions s join session_turns t on t.workspace_id = s.workspace_id and t.id = s.active_turn_id where s.workspace_id = w.workspace_id and s.id = w.session_id and s.active_turn_id = w.turn_id and s.status = 'waiting_capacity' and t.status = 'waiting_capacity' ) as blocked_turn_live from subscription_capacity_waiters w where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid ${ input.provider ? sql`and provider = ${input.provider}` : sql`and provider = any(${`{${SUBSCRIPTION_CORE_WAITER_PROVIDERS.join(",")}}`}::text[])` } ${input.waiterId ? sql`and waiter_id = ${input.waiterId}::uuid` : sql``} ${input.forUpdate ? sql`for update` : sql``}`, ); return row ? mapSubscriptionCoreCodexWaiter(row) : null; } /** The session's waiting core Codex waiter, if any (workflow peek and recovery). */ export async function getSubscriptionCoreCodexCapacityWaitForSession( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, (scopedDb) => readSubscriptionCoreWaiterInTransaction(scopedDb, { workspaceId, sessionId, provider: "codex", }), ); } /** Same lookup by the exact waiter id a workflow history recorded. */ export async function getSubscriptionCoreCodexCapacityWaitById( db: Database, input: { workspaceId: string; sessionId: string; waiterId: string }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, (scopedDb) => readSubscriptionCoreWaiterInTransaction(scopedDb, { ...input, provider: "codex" }), ); } /** The session's core waiter of any provider (the provider-neutral workflow peek). */ export async function getSubscriptionCoreCapacityWaitForSession( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, (scopedDb) => readSubscriptionCoreWaiterInTransaction(scopedDb, { workspaceId, sessionId }), ); } /** * A core waiter of any provider by the exact id a workflow history recorded. * The reconcile looks a waiter up by id and generation whatever `provider` * the history carries: a SuperGrok waiter the cutover moved to the core keeps * its id and generation. */ export async function getSubscriptionCoreCapacityWaitById( db: Database, input: { workspaceId: string; sessionId: string; waiterId: string }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, (scopedDb) => readSubscriptionCoreWaiterInTransaction(scopedDb, input), ); } /** * When a core waiter checks again: at the earliest known reset when there is * one (authoritative), else at a quarantine's end when sooner than the bounded * control-plane backoff (no provider call is made at a check, only placement). * For a provider whose usage read can end an exhaustion early * (`rechecksBeforeReset`), a future reset only caps the bounded backoff * (`bounded_refresh`): its waiter's reconcile re-reads usage first, so it * never sleeps until the end of a credit period after credits are back. */ export function subscriptionCoreCodexNextCheckAt(input: { earliestResetAt: Date | null; healthRetryAt: Date | null; refreshAttempt: number; now: Date; rechecksBeforeReset?: boolean; /** Also refresh an empty candidate set after settings/pool/cutover changes. */ failoverAware?: boolean; }): { nextCheckAt: Date; resetKind: CodexCapacityResetKind } { const { now } = input; const retryAt = input.healthRetryAt?.getTime(); const futureRetryAt = retryAt !== undefined && retryAt > now.getTime() ? retryAt : null; if (input.earliestResetAt && input.earliestResetAt.getTime() > now.getTime()) { if (input.rechecksBeforeReset === true || input.failoverAware === true) { // A quarantine that ends sooner than the bounded check moves it earlier. const backoff = now.getTime() + codexCapacityRefreshBackoffMs(input.refreshAttempt); const bounded = futureRetryAt !== null ? Math.min(futureRetryAt, backoff) : backoff; if (bounded < input.earliestResetAt.getTime()) { return { nextCheckAt: new Date(bounded), resetKind: "bounded_refresh" }; } } return { nextCheckAt: input.earliestResetAt, resetKind: "authoritative" }; } const backoff = now.getTime() + codexCapacityRefreshBackoffMs(input.refreshAttempt); return { nextCheckAt: new Date(futureRetryAt !== null ? Math.min(futureRetryAt, backoff) : backoff), resetKind: "mutation_only", }; } export type ArmSubscriptionCoreCodexCapacityWaitResult = | { action: "waiting"; waiter: SubscriptionCoreCodexCapacityWait; events: SessionEvent[] } | { action: "stale"; events: SessionEvent[] }; /** * Atomically close one attempt whose core placement said wait and park the * same logical turn on the session's core waiter. Same lock order and * boundary as the legacy Codex arm: workspace control -> workspace -> session * -> exact turn -> exact attempt -> optional goal -> live core lease (when a * reactive failure owns one) -> waiter. The waiting turn/session pointers, * durable events, exact lease release and waiter generation commit together. */ export async function armSubscriptionCoreCodexCapacityWait( db: Database, input: ArmSubscriptionCoreCapacityWaitInput, ): Promise { return await armSubscriptionCoreCapacityWait(db, "codex", input); } export type ArmSubscriptionCoreCapacityWaitInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; goalId?: string | null; goalVersion?: number | null; waitReason: string; reconnectAccount?: SubscriptionReconnectAccount; earliestResetAt: Date | null; healthRetryAt?: Date | null; /** From a fresh failover-aware accepted-turn evaluation; never caller authority. * Supply [] when that evaluation currently has no alternative providers. * Omission preserves the legacy home-only path until worker integration. */ candidateProviders?: readonly string[]; failurePayload: Record; /** The live core lease a reactive refusal still holds; released atomically. */ leaseFence?: { connectionId: string; holderId: string; generation: number }; now?: Date; }; /** * The provider-neutral arm: `provider` names the core lease and the waiter * row, and selects its session-event vocabulary. */ export async function armSubscriptionCoreCapacityWait( db: Database, provider: SubscriptionCoreWaiterProvider, input: ArmSubscriptionCoreCapacityWaitInput, ): Promise { const vocabulary = subscriptionCoreWaitVocabulary(provider); const candidateProviders = capacityWaitCandidateProviders(input.candidateProviders); const label = vocabulary.label; const now = input.now ?? new Date(); const goalId = input.goalId ?? null; const goalVersion = input.goalVersion ?? null; if ( (goalId === null) !== (goalVersion === null) || (goalVersion !== null && (!Number.isSafeInteger(goalVersion) || goalVersion < 1)) ) { throw new Error( `Core ${label} capacity goal fence must be absent or contain a positive version`, ); } if (!/^[a-z][a-z0-9_]{0,127}$/.test(input.waitReason)) { throw new Error(`Core ${label} wait reason must be a bounded identifier`); } return await retrySessionActivityRls( db, input.workspaceId, { stage: provider === "codex" ? "session_lifecycle_outbox.arm_subscription_core_codex_capacity_wait" : "session_lifecycle_outbox.arm_subscription_core_capacity_wait", eventTypes: [ vocabulary.waitingEventType, "turn.failed", "session.status.changed", "session.notification.posted", ], maxAttempts: 3, }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockChildLifecycleOutboxWriteRowsTx(tx, input.workspaceId, { sessionId: input.sessionId, turnId: input.turnId, attemptId: input.attemptId, }); const session = locks.session; const turn = locks.turns[0]; const attempt = locks.attempts[0]; const effectiveControl = session ? await evaluateSessionControl(tx, input.workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined, }) : null; const [goal] = goalId ? await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.id, goalId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1) : []; const leaseRows = input.leaseFence ? await rawRows<{ holder_id: string; generation: number | string }>( tx, sql`select holder_id, generation from subscription_leases where account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and turn_id = ${input.turnId}::uuid and provider = ${provider} and connection_id = ${input.leaseFence.connectionId}::uuid and leased_until > clock_timestamp() for update`, ) : []; const existing = await readSubscriptionCoreWaiterInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, forUpdate: true, }); const exactRowsMatch = session?.accountId === input.accountId && turn?.accountId === input.accountId && turn?.sessionId === input.sessionId && attempt?.accountId === input.accountId && attempt?.sessionId === input.sessionId && attempt?.turnId === input.turnId && attempt?.executionGeneration === turn?.executionGeneration; if (!exactRowsMatch) return { action: "stale", events: [] } as const; if ( existing && existing.blockedTurnId === input.turnId && existing.blockedTurnGeneration === turn?.executionGeneration && turn?.status === "waiting_capacity" && session?.status === "waiting_capacity" && session.activeTurnId === input.turnId ) { return { action: "waiting", waiter: existing, events: [] } as const; } const lease = leaseRows[0]; const leaseFenceValid = !input.leaseFence || (lease?.holder_id === input.leaseFence.holderId && Number(lease.generation) === input.leaseFence.generation); if ( !session || !turn || effectiveControl?.state !== "active" || effectiveControl.settlement !== null || session.activeTurnId !== input.turnId || session.status !== "running" || (goalId !== null && (!goal || goal.status !== "active" || goal.version !== goalVersion)) || turn.status !== "running" || turn.activeAttemptId !== input.attemptId || !leaseFenceValid ) { return { action: "stale", events: [] } as const; } // A resumed attempt that lands straight back on unavailable capacity // without completing a model call is a false resumption. It delays // the next resume by the persisted backoff; it never ends the turn. // The reconcile resumes only when the turn's own placement would run // (`refreshBeforeReconcile`), so a false resumption is a race with // another turn taking the capacity, and the message is still owed // an answer once capacity returns. const recovery = readCodexCapacityRecovery(turn.metadata); const falseResumption = recovery.resumeGeneration !== null && recovery.resumeGeneration <= turn.executionGeneration; const falseResumptions = recovery.falseResumptions + (falseResumption ? 1 : 0); const retryNotBefore = falseResumption ? new Date(now.getTime() + codexFalseResumptionBackoffMs(falseResumptions)).toISOString() : recovery.retryNotBefore; const recoveryMetadata = { ...metadataWithoutTurnDispatchAttempt(turn.metadata), [CODEX_CAPACITY_RECOVERY_KEY]: { falseResumptions, resumeGeneration: null, retryNotBefore, }, }; // A long wait is announced once, as it starts: a worker's parent gets // child_waiting_capacity, a top-level chat's person an inbox notice. const explanation = isProviderCapacityWaitReason(input.waitReason) ? (subscriptionCapacityWaitReasonText(input.waitReason, label, input.reconnectAccount) ?? undefined) : undefined; const attention = capacityWaitAttention({ waitReason: input.waitReason, earliestResetAt: input.earliestResetAt, healthRetryAt: input.healthRetryAt ?? null, now, }); const personNotice = attention && !session.parentSessionId ? SessionNotificationPostedPayload.parse( capacityWaitNotificationPayload({ turnId: input.turnId, provider, resetsAt: attention.resetsAt, waitReason: input.waitReason, ...(input.reconnectAccount ? { reconnectAccount: input.reconnectAccount } : {}), }), ) : null; // A worker's turn remembers the reset its parent is told below (set // once the waiter exists), so a later check can restate it; a short // wait tells the parent nothing. const { [CAPACITY_WAIT_PARENT_NOTICE_KEY]: _toldParent, ...unannouncedMetadata } = recoveryMetadata as Record; const waitingMetadata = { ...unannouncedMetadata, ...(personNotice ? { [CAPACITY_WAIT_NOTICE_KEY]: capacityWaitNoticeMarker( personNotice.key, attention!.resetsAt, explanation, ), } : {}), }; await closeSessionTurnAttemptInTransaction(tx, { id: input.attemptId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: turn.executionGeneration, outcome: "waiting_capacity", closedAt: now, }); const scheduled = subscriptionCoreCodexNextCheckAt({ earliestResetAt: input.earliestResetAt, healthRetryAt: input.healthRetryAt ?? null, refreshAttempt: 0, now, rechecksBeforeReset: vocabulary.recheckBeforeReset, failoverAware: candidateProviders !== null, }); const nextCheckAt = new Date( Math.max( scheduled.nextCheckAt.getTime(), retryNotBefore ? Date.parse(retryNotBefore) : 0, ), ); // Arming follows a placement evaluation, so this generation has // already observed its own initial revision; only a later capacity // change creates pending wake work. const generation = (existing?.generation ?? 0) + 1; const wakeRevision = (existing?.wakeRevision ?? 0) + 1; const [row] = await rawRows( tx, sql`insert into subscription_capacity_waiters ( account_id, workspace_id, session_id, turn_id, provider, candidate_providers, wait_reason, policy_hash, reset_kind, refresh_attempt, resumed_update_id, earliest_reset_at, generation, wake_revision, observed_wake_revision, next_check_at, blocked_turn_generation, goal_id, goal_version, last_wake_reason, updated_at ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${provider}, ${ candidateProviders === null ? sql`null` : sql`array[${sql.join( candidateProviders.map((id) => sql`${id}`), sql`, `, )}]::text[]` }, ${input.waitReason}, null, ${scheduled.resetKind}, 0, null, ${input.earliestResetAt?.toISOString() ?? null}::timestamptz, ${generation}, ${wakeRevision}, ${wakeRevision}, ${nextCheckAt.toISOString()}::timestamptz, ${turn.executionGeneration}, ${goalId}::uuid, ${goalVersion}, 'capacity_wait_armed', ${now.toISOString()}::timestamptz ) on conflict (workspace_id, session_id) do update set turn_id = excluded.turn_id, provider = excluded.provider, candidate_providers = excluded.candidate_providers, wait_reason = excluded.wait_reason, policy_hash = null, reset_kind = excluded.reset_kind, refresh_attempt = 0, resumed_update_id = null, earliest_reset_at = excluded.earliest_reset_at, generation = excluded.generation, wake_revision = excluded.wake_revision, observed_wake_revision = excluded.observed_wake_revision, next_check_at = excluded.next_check_at, blocked_turn_generation = excluded.blocked_turn_generation, goal_id = excluded.goal_id, goal_version = excluded.goal_version, last_wake_reason = excluded.last_wake_reason, updated_at = excluded.updated_at where subscription_capacity_waiters.account_id = excluded.account_id returning ${SUBSCRIPTION_CORE_CODEX_WAITER_COLUMNS}`, ); if (!row) throw new Error(`Core ${label} capacity wait arm returned no waiter row`); const waiter = mapSubscriptionCoreCodexWaiter(row); let sequence = session.lastSequence; const closedTools = await closePendingSessionToolCallsInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, reason: vocabulary.closeToolsReason, sequence, now, preserveInterruptionRows: true, }); sequence = closedTools.sequence; const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: vocabulary.waitingEventType, payload: { ...input.failurePayload, ...vocabulary.waitingPayload, ...(explanation ? { error: explanation, waitReason: input.waitReason, actionRequired: subscriptionCapacityWaitNeedsAction(input.waitReason), } : {}), waiterId: waiter.waiterId, generation: waiter.generation, goalId, goalVersion, blockedTurnGeneration: turn.executionGeneration, policyHash: null, resetKind: scheduled.resetKind, earliestResetAt: input.earliestResetAt?.toISOString() ?? null, nextCheckAt: nextCheckAt.toISOString(), falseResumptions, }, turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", occurredAt: now, }, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.status.changed", payload: { status: "waiting_capacity", reason: vocabulary.statusReason, }, turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", occurredAt: now, }, ...(personNotice ? [ { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.notification.posted", payload: personNotice, turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current" as const, occurredAt: now, }, ] : []), ], "payload", "payloadCodecVersion", ), ) .returning(); const [waitingTurn] = await tx .update(schema.sessionTurns) .set({ status: "waiting_capacity", activeAttemptId: null, metadata: attention && session.parentSessionId ? { ...waitingMetadata, [CAPACITY_WAIT_PARENT_NOTICE_KEY]: capacityWaitNoticeMarker( childWaitingCapacityDedupeKey({ childSessionId: input.sessionId, waiterId: waiter.waiterId, }), attention.resetsAt, explanation, ), } : waitingMetadata, version: turn.version + 1, finishedAt: null, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), eq(schema.sessionTurns.status, "running"), eq(schema.sessionTurns.activeAttemptId, input.attemptId), ), ) .returning({ id: schema.sessionTurns.id }); if (!waitingTurn) throw new Error(`Core ${label} capacity blocked turn changed during arm`); const [waitingSession] = await tx .update(schema.sessions) .set({ status: "waiting_capacity", activeTurnId: input.turnId, lastSequence: sequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.status, "running"), eq(schema.sessions.activeTurnId, input.turnId), ), ) .returning({ id: schema.sessions.id }); if (!waitingSession) throw new Error(`Core ${label} capacity session changed during arm`); if (attention) { await enqueueChildWaitingCapacityOutboxTx(tx, input.workspaceId, session, { turnId: input.turnId, waiterId: waiter.waiterId, provider, nextCheckAt, resetsAt: attention.resetsAt, ...(explanation ? { explanation } : {}), }); } if (input.leaseFence) { await tx.execute(sql`delete from subscription_leases where account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and turn_id = ${input.turnId}::uuid and provider = ${provider} and connection_id = ${input.leaseFence.connectionId}::uuid and holder_id = ${input.leaseFence.holderId} and generation = ${input.leaseFence.generation}`); } const events = [...closedTools.events, ...inserted.map(mapEvent)]; return { action: "waiting", waiter, events } as const; }), ); } /** What core placement says about a blocked turn, evaluated before the reconcile transaction. */ export type SubscriptionCoreCodexWaitEvaluation = | { kind: "run"; candidateProviders?: readonly string[] } | { kind: "wait"; waitReason: string; reconnectAccount?: SubscriptionReconnectAccount; earliestResetAt: Date | null; healthRetryAt: Date | null; /** Entire freshly derived candidate set, not a union with stored hints. */ candidateProviders?: readonly string[]; } /** The accepted turn can no longer use the core under its frozen authority. */ | { kind: "revoked" } /** The cutover is switched off: keep the work parked (maintenance), check later. */ | { kind: "paused" }; export type ReconcileSubscriptionCoreCodexCapacityWaitResult = | { action: "waiting"; waiter: SubscriptionCoreCodexCapacityWait; events: SessionEvent[] } | { action: "resumed"; events: SessionEvent[]; /** When the turn parked: its waiting attempt's close (null if unknown). */ parkedAt: Date | null; } | { action: "superseded"; events: SessionEvent[]; /** Why, when this call ended the wait (deleted its waiter). */ reason?: string; parkedAt?: Date | null; } | { action: "paused" | "stale"; events: SessionEvent[] }; /** * When a parked turn's current capacity wait began: the close of its latest * attempt that parked (outcome `waiting_capacity`), as the turn hold * summary (1485) reads it. Null when no such attempt is visible. */ async function readCapacityWaitParkedAtInTransaction( tx: SessionActivityDatabase, input: { workspaceId: string; sessionId: string; turnId: string }, ): Promise { const [row] = await rawRows<{ parked_at: Date | string | null }>( tx, sql`select max(closed_at) as parked_at from session_turn_attempts where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and turn_id = ${input.turnId}::uuid and outcome = 'waiting_capacity'`, ); return row?.parked_at == null ? null : new Date(row.parked_at); } /** * Row-lock and settle one core waiter after the caller evaluated placement * for its blocked turn (without leasing). Resuming makes the exact blocked * turn `recovering` and deletes the waiter; waiting acknowledges only the * wake revision the evaluation actually observed, so a capacity change that * lands during the evaluation is checked again immediately. Pause leaves the * waiter untouched; a changed goal, turn or session supersedes it without * inference, as for the legacy Codex waiter. */ export async function reconcileSubscriptionCoreCodexCapacityWait( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; /** The waiter's wake revision when the evaluation started. */ evaluatedWakeRevision: number; evaluation: SubscriptionCoreCodexWaitEvaluation; now?: Date; }, ): Promise { return await reconcileSubscriptionCoreCapacityWait(db, { ...input, provider: "codex" }); } /** * The provider-neutral reconcile: the waiter is looked up by its exact id * and generation (of `provider` only, when given) and settles with its own * provider's session-event vocabulary. */ export async function reconcileSubscriptionCoreCapacityWait( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; /** The waiter's wake revision when the evaluation started. */ evaluatedWakeRevision: number; evaluation: SubscriptionCoreCodexWaitEvaluation; provider?: SubscriptionCoreWaiterProvider; now?: Date; }, ): Promise { const now = input.now ?? new Date(); return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const prefix = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", }); const waiterRead = await readSubscriptionCoreWaiterInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, waiterId: input.waiterId, ...(input.provider ? { provider: input.provider } : {}), }); if (!waiterRead || waiterRead.generation !== input.generation) { return { action: "stale", events: [] } as const; } const vocabulary = subscriptionCoreWaitVocabulary(waiterRead.provider); // A worker's parent is locked with it, as for every child lifecycle // notice: the wait below may restate its reset to the parent. const [preview] = await tx .select({ parentSessionId: schema.sessions.parentSessionId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: [ input.sessionId, ...(preview?.parentSessionId ? [preview.parentSessionId] : []), ], turnIds: [waiterRead.blockedTurnId], }); const session = locks.sessions.find((row) => row.id === input.sessionId); if (session && session.parentSessionId !== (preview?.parentSessionId ?? null)) { throw new Error(`Session parent changed while locking: ${input.sessionId}`); } const blockedTurn = locks.turns[0]; const effectiveControl = session ? await evaluateSessionControl(tx, input.workspaceId, input.sessionId, { workspaceControl: prefix.control ?? undefined, }) : null; const [goal] = waiterRead.goalId ? await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.id, waiterRead.goalId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1) : []; const waiter = await readSubscriptionCoreWaiterInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, waiterId: input.waiterId, provider: waiterRead.provider, forUpdate: true, }); if ( !session || !blockedTurn || !waiter || session.accountId !== input.accountId || blockedTurn.accountId !== input.accountId || blockedTurn.sessionId !== input.sessionId || waiter.accountId !== input.accountId || waiter.blockedTurnId !== blockedTurn.id || waiter.generation !== input.generation ) { return { action: "stale", events: [] } as const; } if (effectiveControl?.state !== "active" || effectiveControl.settlement !== null) { return { action: "paused", events: [] } as const; } let supersedeReason: string | null = null; if (session.status === "cancelled") supersedeReason = "session_cancelled"; else if ( waiter.goalId !== null && (!goal || goal.status !== "active" || goal.version !== waiter.goalVersion) ) { supersedeReason = "goal_changed"; } else if (session.activeTurnId !== blockedTurn.id) { supersedeReason = "active_turn_changed"; } else if (session.status !== "waiting_capacity") { supersedeReason = "session_not_waiting_capacity"; } else if ( blockedTurn.status !== "waiting_capacity" || blockedTurn.activeAttemptId !== null || blockedTurn.executionGeneration !== waiter.blockedTurnGeneration ) { supersedeReason = "blocked_turn_changed"; } else if (input.evaluation.kind === "revoked") { supersedeReason = "subscription_access_revoked"; } if (supersedeReason) { return await supersedeSubscriptionCoreCodexCapacityWaitInTransaction(tx, { session, blockedTurn, waiter, reason: supersedeReason, now, }); } // Only the revision the evaluation saw is acknowledged. const observed = Math.min(waiter.wakeRevision, input.evaluatedWakeRevision); const recovery = readCodexCapacityRecovery(blockedTurn.metadata); const evaluation = input.evaluation; // A legacy evaluation cannot leave a previously failover-aware waiter // asleep until a distant reset. Discard its old hints and keep the // bounded recheck; the next full evaluation rebuilds eligibility. const candidateProviders = capacityWaitCandidateProviders( evaluation.kind === "wait" || evaluation.kind === "run" ? (evaluation.candidateProviders ?? (waiter.candidateProviders === null ? null : [])) : waiter.candidateProviders, ); if ( evaluation.kind !== "run" || (recovery.retryNotBefore && Date.parse(recovery.retryNotBefore) > now.getTime()) ) { const waitEvaluation = evaluation.kind === "wait" ? evaluation : { kind: "wait" as const, waitReason: waiter.waitReason, earliestResetAt: null, healthRetryAt: null, }; const authoritative = waitEvaluation.earliestResetAt !== null && waitEvaluation.earliestResetAt.getTime() > now.getTime(); // A provider that rechecks before its reset backs off across checks. const refreshAttempt = authoritative && !vocabulary.recheckBeforeReset && candidateProviders === null ? 0 : waiter.refreshAttempt + 1; const scheduled = subscriptionCoreCodexNextCheckAt({ earliestResetAt: waitEvaluation.earliestResetAt, healthRetryAt: waitEvaluation.healthRetryAt, refreshAttempt, now, rechecksBeforeReset: vocabulary.recheckBeforeReset, failoverAware: candidateProviders !== null, }); // Capacity changes can prompt a recheck but never bypass a persisted // false-resumption delay. const nextCheckAt = new Date( Math.max( scheduled.nextCheckAt.getTime(), recovery.retryNotBefore ? Date.parse(recovery.retryNotBefore) : 0, ), ); const [row] = await rawRows( tx, sql`update subscription_capacity_waiters set wait_reason = ${waitEvaluation.waitReason}, candidate_providers = ${ candidateProviders === null ? sql`null` : sql`array[${sql.join( candidateProviders.map((id) => sql`${id}`), sql`, `, )}]::text[]` }, earliest_reset_at = ${waitEvaluation.earliestResetAt?.toISOString() ?? null}::timestamptz, next_check_at = ${nextCheckAt.toISOString()}::timestamptz, reset_kind = ${scheduled.resetKind}, refresh_attempt = ${refreshAttempt}, observed_wake_revision = greatest(observed_wake_revision, ${observed}), updated_at = ${now.toISOString()}::timestamptz where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and waiter_id = ${waiter.waiterId}::uuid and generation = ${waiter.generation} returning ${SUBSCRIPTION_CORE_CODEX_WAITER_COLUMNS}`, ); if (!row) return { action: "stale", events: [] } as const; const reasonText = subscriptionCapacityWaitReasonText( waitEvaluation.waitReason, vocabulary.label, waitEvaluation.reconnectAccount, ); const explanation = isProviderCapacityWaitReason(waitEvaluation.waitReason) ? (reasonText ?? undefined) : undefined; // Whoever was told when the wait ends (a top-level chat's person, // or a worker's parent) is told again once the reset they heard no // longer holds (it passed without capacity, or a longer limit // binds), and told for the first time when a short wait has become // a long one; the session's timeline gets a waiting event naming // the reset that now holds. Only an evaluation that found no // capacity says when it returns; a held false-resumption delay or // legacy evaluation restates nothing. const toldKey = session.parentSessionId ? CAPACITY_WAIT_PARENT_NOTICE_KEY : CAPACITY_WAIT_NOTICE_KEY; const told = readCapacityWaitNotice(blockedTurn.metadata, toldKey); const attention = evaluation.kind !== "wait" ? null : (capacityWaitAttention({ waitReason: waitEvaluation.waitReason, earliestResetAt: waitEvaluation.earliestResetAt, healthRetryAt: waitEvaluation.healthRetryAt, now, }) ?? (told?.explanation ? { resetsAt: waitEvaluation.earliestResetAt } : null)); const explanationChanged = attention !== null && told?.explanation !== explanation; const changedReason = waiter.waitReason !== waitEvaluation.waitReason || explanationChanged; const restate = attention !== null && (!told || explanationChanged || capacityWaitNoticeNeedsRestating(told, attention.resetsAt)); // What agents see (a worker's parent woken by a notice, the // session's own timeline) is restated only for a real change: the // first long wait, a told time that passed without capacity, a // limit's reset that now binds later, or a reset that became // unknown. A health-retry time that moves later at each check while // the told time still lies ahead would otherwise wake the parent at // every check; the person's silent in-place notification still // follows it. const toldTimePassed = typeof told?.resetsAt === "string" && Date.parse(told.resetsAt) <= now.getTime(); const restateToAgents = restate && (!told || explanationChanged || toldTimePassed || waitEvaluation.earliestResetAt !== null || attention!.resetsAt === null); const openNotice = session.parentSessionId ? null : told; const personNotice = restate && !session.parentSessionId ? SessionNotificationPostedPayload.parse({ ...capacityWaitNotificationPayload({ turnId: blockedTurn.id, provider: waiter.provider, resetsAt: attention!.resetsAt, waitReason: waitEvaluation.waitReason, ...(waitEvaluation.reconnectAccount ? { reconnectAccount: waitEvaluation.reconnectAccount } : {}), }), // Same key: the open notification is updated in place, silently. replaced: openNotice !== null, }) : null; const waitingText = changedReason || restateToAgents ? reasonText : null; const restated = [ ...(waitingText ? [ { type: vocabulary.waitingEventType, payload: { ...vocabulary.waitingPayload, code: "subscription_capacity_unavailable", error: waitingText, waitReason: waitEvaluation.waitReason, actionRequired: subscriptionCapacityWaitNeedsAction( waitEvaluation.waitReason, ), waiterId: waiter.waiterId, generation: waiter.generation, resetKind: scheduled.resetKind, earliestResetAt: waitEvaluation.earliestResetAt?.toISOString() ?? null, nextCheckAt: nextCheckAt.toISOString(), } as Record, }, ] : []), ...(personNotice ? [{ type: "session.notification.posted", payload: personNotice }] : []), ]; let restatedEvents: SessionEvent[] = []; if (restated.length > 0) { const insertedEvents = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( restated.map((event, index) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1 + index, type: event.type, turnId: blockedTurn.id, turnGeneration: blockedTurn.executionGeneration, turnAssociation: "current" as const, occurredAt: now, payload: event.payload, })), "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + restated.length, updatedAt: now }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); restatedEvents = insertedEvents.map(mapEvent); } // A worker's parent hears the restated reset in a new notice (the // system-update outbox delivers it), keyed by that reset so it never // collides with the arm's notice or an earlier restatement. const restatedReasonSequence = explanationChanged ? session.lastSequence + 1 : undefined; const restatement = { ...(restatedReasonSequence === undefined ? {} : { restatedReasonSequence }), restatedResetsAt: attention?.resetsAt?.toISOString() ?? null, }; const parentNoticeKey = restateToAgents && session.parentSessionId ? childWaitingCapacityDedupeKey({ childSessionId: session.id, waiterId: waiter.waiterId, ...restatement, }) : null; if (parentNoticeKey) { await enqueueChildWaitingCapacityOutboxTx(tx, input.workspaceId, session, { turnId: blockedTurn.id, waiterId: waiter.waiterId, provider: waiter.provider, nextCheckAt, resetsAt: attention!.resetsAt, restatement, ...(explanation ? { explanation } : {}), }); } const noticeKey = personNotice?.key ?? parentNoticeKey; if (noticeKey) { // The turn remembers what it said and to whom; the person's // notification key also serves its withdrawal when the wait ends. const [noticedTurn] = await tx .update(schema.sessionTurns) .set({ metadata: { ...blockedTurn.metadata, [toldKey]: capacityWaitNoticeMarker(noticeKey, attention!.resetsAt, explanation), }, version: blockedTurn.version + 1, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, blockedTurn.id), eq(schema.sessionTurns.status, "waiting_capacity"), isNull(schema.sessionTurns.activeAttemptId), ), ) .returning({ id: schema.sessionTurns.id }); if (!noticedTurn) { throw new Error( `Core ${vocabulary.label} capacity blocked turn changed during reconcile`, ); } } return { action: "waiting", waiter: mapSubscriptionCoreCodexWaiter(row), events: restatedEvents, } as const; } const noticeWithdrawal = capacityWaitNoticeWithdrawal(blockedTurn.metadata); const events = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, ...vocabulary.resumedEvent(waiter), turnId: blockedTurn.id, turnGeneration: blockedTurn.executionGeneration, turnAssociation: "current", occurredAt: now, }, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2, type: "session.status.changed", payload: { status: "recovering", reason: vocabulary.statusReason }, turnId: blockedTurn.id, turnGeneration: blockedTurn.executionGeneration, turnAssociation: "current", occurredAt: now, }, ...(noticeWithdrawal ? [ { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 3, ...noticeWithdrawal, turnId: blockedTurn.id, turnGeneration: blockedTurn.executionGeneration, turnAssociation: "current" as const, occurredAt: now, }, ] : []), ], "payload", "payloadCodecVersion", ), ) .returning(); const deleted = await rawRows<{ waiter_id: string }>( tx, sql`delete from subscription_capacity_waiters where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and waiter_id = ${waiter.waiterId}::uuid and generation = ${waiter.generation} returning waiter_id::text as waiter_id`, ); if (deleted.length !== 1) throw new Error(`Core ${vocabulary.label} waiter changed during atomic resume`); const [recoveringTurn] = await tx .update(schema.sessionTurns) .set({ status: "recovering", activeAttemptId: null, metadata: { ...withoutCapacityWaitNotice( metadataWithoutTurnDispatchAttempt(blockedTurn.metadata), ), [CODEX_CAPACITY_RECOVERY_KEY]: { ...recovery, resumeGeneration: blockedTurn.executionGeneration + 1, }, }, version: blockedTurn.version + 1, finishedAt: null, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, blockedTurn.id), eq(schema.sessionTurns.status, "waiting_capacity"), isNull(schema.sessionTurns.activeAttemptId), eq(schema.sessionTurns.executionGeneration, waiter.blockedTurnGeneration ?? -1), ), ) .returning({ id: schema.sessionTurns.id }); if (!recoveringTurn) { throw new Error( `Core ${vocabulary.label} capacity blocked turn changed during atomic resume`, ); } const [recoveringSession] = await tx .update(schema.sessions) .set({ status: "recovering", activeTurnId: blockedTurn.id, lastSequence: session.lastSequence + events.length, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.status, "waiting_capacity"), eq(schema.sessions.activeTurnId, blockedTurn.id), ), ) .returning({ id: schema.sessions.id }); if (!recoveringSession) { throw new Error(`Core ${vocabulary.label} capacity session changed during atomic resume`); } const parkedAt = await readCapacityWaitParkedAtInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: blockedTurn.id, }); return { action: "resumed", events: events.map(mapEvent), parkedAt } as const; }), ); } async function supersedeSubscriptionCoreCodexCapacityWaitInTransaction( tx: SessionActivityDatabase, input: { session: typeof schema.sessions.$inferSelect; blockedTurn: typeof schema.sessionTurns.$inferSelect; waiter: SubscriptionCoreCodexCapacityWait; reason: string; now: Date; }, ): Promise<{ action: "superseded"; events: SessionEvent[]; reason?: string; parkedAt?: Date | null; }> { const vocabulary = subscriptionCoreWaitVocabulary(input.waiter.provider); const deleted = await rawRows<{ waiter_id: string }>( tx, sql`delete from subscription_capacity_waiters where workspace_id = ${input.session.workspaceId}::uuid and session_id = ${input.session.id}::uuid and waiter_id = ${input.waiter.waiterId}::uuid and generation = ${input.waiter.generation} returning waiter_id::text as waiter_id`, ); if (deleted.length !== 1) return { action: "superseded", events: [] }; const parkedAt = await readCapacityWaitParkedAtInTransaction(tx, { workspaceId: input.session.workspaceId, sessionId: input.session.id, turnId: input.blockedTurn.id, }); const turnWasCurrent = input.session.activeTurnId === input.blockedTurn.id; const terminalTurnStatus = input.session.status === "cancelled" ? "cancelled" : "superseded"; if (input.blockedTurn.status === "waiting_capacity") { const [supersededTurn] = await tx .update(schema.sessionTurns) .set({ status: terminalTurnStatus, activeAttemptId: null, cancelledBy: vocabulary.cancelledBy, cancelReason: input.reason, version: input.blockedTurn.version + 1, finishedAt: input.now, updatedAt: input.now, }) .where( and( eq(schema.sessionTurns.workspaceId, input.session.workspaceId), eq(schema.sessionTurns.id, input.blockedTurn.id), eq(schema.sessionTurns.status, "waiting_capacity"), isNull(schema.sessionTurns.activeAttemptId), eq(schema.sessionTurns.executionGeneration, input.waiter.blockedTurnGeneration ?? -1), ), ) .returning({ id: schema.sessionTurns.id }); if (!supersededTurn) { throw new Error( `Core ${vocabulary.label} capacity blocked turn changed during atomic supersession`, ); } } const queued = turnWasCurrent ? await runnableQueuedTurnExists(tx, { accountId: input.session.accountId, workspaceId: input.session.workspaceId, sessionId: input.session.id, }) : false; const nextSessionStatus = input.session.status === "cancelled" ? "cancelled" : queued ? "queued" : "idle"; const eventValues: SessionEventInsertWithPayload[] = [ { accountId: input.session.accountId, workspaceId: input.session.workspaceId, sessionId: input.session.id, sequence: input.session.lastSequence + 1, ...vocabulary.supersededEvent(input.waiter, input.reason), turnId: input.blockedTurn.id, turnGeneration: input.blockedTurn.executionGeneration, ...(turnWasCurrent ? { turnAssociation: "current" } : {}), occurredAt: input.now, }, ]; if (turnWasCurrent && input.session.status !== nextSessionStatus) { eventValues.push({ accountId: input.session.accountId, workspaceId: input.session.workspaceId, sessionId: input.session.id, sequence: input.session.lastSequence + 2, type: "session.status.changed", payload: { status: nextSessionStatus, reason: input.reason }, turnId: input.blockedTurn.id, turnGeneration: input.blockedTurn.executionGeneration, turnAssociation: "current", occurredAt: input.now, }); } const noticeWithdrawal = capacityWaitNoticeWithdrawal(input.blockedTurn.metadata); if (noticeWithdrawal) { eventValues.push({ accountId: input.session.accountId, workspaceId: input.session.workspaceId, sessionId: input.session.id, sequence: input.session.lastSequence + eventValues.length + 1, ...noticeWithdrawal, turnId: input.blockedTurn.id, turnGeneration: input.blockedTurn.executionGeneration, occurredAt: input.now, }); } const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(eventValues), "payload", "payloadCodecVersion", ), ) .returning(); const [updatedSession] = await tx .update(schema.sessions) .set({ ...(turnWasCurrent ? { status: nextSessionStatus, activeTurnId: null } : {}), lastSequence: input.session.lastSequence + inserted.length, updatedAt: input.now, }) .where( and( eq(schema.sessions.workspaceId, input.session.workspaceId), eq(schema.sessions.id, input.session.id), ...(turnWasCurrent ? [eq(schema.sessions.activeTurnId, input.blockedTurn.id)] : []), ), ) .returning({ id: schema.sessions.id }); if (!updatedSession) throw new Error(`Core ${vocabulary.label} capacity session changed during supersession`); return { action: "superseded", events: inserted.map(mapEvent), reason: input.reason, parkedAt }; } /** * The trusted empty-subject worker scope the provider-neutral wake outbox * requires (its own RLS policy), for exactly one account and workspace, even * when the caller runs under a turn's ambient session actor. */ export async function withSubscriptionCapacityWakeOutboxScope( db: Database, scope: { accountId: string; workspaceId: string }, operation: (tx: Database) => Promise, ): Promise { return await withRlsContext(db, scope, (tx) => withPoolWakeServiceScopeInTransaction(tx, () => operation(tx)), ); } /** One workspace whose core waiters were woken; deliver its outbox after commit. */ export type SubscriptionCoreCodexWakeScope = SubscriptionCoreWakeScope; /** * Capacity changed for the account's Codex pool (a quota exhaustion ended, a * quarantine cleared, a plan changed, a binding or assignment changed): * advance every waiting core Codex waiter's wake revision, record the typed * wake in the provider-neutral outbox and the generic session workflow wake * in the same transaction. Codex's binding of the provider-neutral * `wakeSubscriptionCoreCapacityWaiters`, with its own validation texts. * Returns the workspaces whose outbox the caller should drain after commit. */ export async function wakeSubscriptionCoreCodexCapacityWaiters( db: Database, input: { accountId: string; reason: string; workspaceIds?: readonly string[]; /** * Wake only these sessions' waiters (for example a session pin, which * changes nothing another session can place on). Requires exactly one * workspace in `workspaceIds`. */ sessionIds?: readonly string[]; }, ): Promise { if (!/^[a-z][a-z0-9_]{0,127}$/.test(input.reason)) throw new Error("Core Codex wake reason must be a bounded identifier"); if (input.sessionIds !== undefined && input.workspaceIds?.length !== 1) throw new Error("A session-scoped core Codex wake names exactly one workspace"); return await wakeSubscriptionCoreCapacityWaiters( db, SUBSCRIPTION_CORE_CODEX_PROVIDER, input, enqueueSessionWorkflowWakeInTransaction, ); } /** * The same wake for any provider on the core (the generic session workflow * wake included). Refused for a provider without a registered binding. */ export async function wakeSubscriptionCoreProviderCapacityWaiters( db: Database, provider: SubscriptionCoreWaiterProvider, input: { accountId: string; reason: string; workspaceIds?: readonly string[]; sessionIds?: readonly string[]; }, ): Promise { return await wakeSubscriptionCoreCapacityWaiters( db, provider, input, enqueueSessionWorkflowWakeInTransaction, ); } // --------------------------------------------------------------------------- // Durable scoped-subscription (legacy Claude) capacity wait / wake state // machine. SuperGrok's legacy instance was deleted with its runtime (M4 X4): // SuperGrok waits park on the shared core waiter. // --------------------------------------------------------------------------- async function withTemporarySubjectRls( tx: Database, subjectId: string, fn: () => Promise, ): Promise { const [prior] = await rawRows<{ subject_id: string | null }>( tx, sql`select current_setting('opengeni.subject_id', true) as subject_id`, ); await setSubjectRlsContext(tx, subjectId); const restoreSubjectScope = async () => await tx.execute( sql`select set_config('opengeni.subject_id', ${prior?.subject_id ?? ""}, true)`, ); let result: T; try { result = await fn(); } catch (error) { // Restoring the scope inside an already-aborted transaction raises 25P02, // which would replace the real error with a useless one. Callers on the // claim path classify the original SQLSTATE (40P01/40001) for the // idempotent-persistence retry, so that substitution is not cosmetic: it // silently disables the retry. The transaction is unwinding here and the // scope dies with it, so a failed restore is moot. await restoreSubjectScope().catch(() => undefined); throw error; } // `fn` succeeded, so the transaction is still usable and the caller keeps // running inside it: a restore failure here is real and must surface. await restoreSubjectScope(); return result; } /** Shared durable scoped-subscription waiter state machine. */ /** Commit organization subscription policy and its durable capacity wake atomically. */ export async function updateModelConnectionAccess( db: Database, target: ModelConnectionTarget, policy: ModelConnectionAccess, ): Promise { // A Claude policy has no legacy pool to write (C4): the relation refuses it. if (target.workspaceId !== null || (target.kind !== "codex" && target.kind !== "supergrok")) { return await updateModelConnectionAccessPolicy(db, target, policy); } const actor = { organizationId: target.accountId, actorSubjectId: target.subjectId }; return await withOrganizationCodexAdministrator(db, actor, async (_tx) => { // Subscription access policies live on the shared core. return null; }); } /** Compose existing pool metadata without a leaf-to-root database import cycle. */ export async function getWorkspaceConnectionModelRestrictions( db: Database, workspaceId: string, subjectId: string, claudeAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1, claudeCoreRestrictions?: ClaudeCoreModelRestrictions, workspaceConnections?: Promise, ) { const sharedMetadata = workspaceConnections?.catch(() => undefined); return await resolveWorkspaceConnectionModelRestrictions( db, workspaceId, subjectId, await codexAccountsForModelRestrictions(db, workspaceId, subjectId), claudeAuthoritySnapshot, claudeCoreRestrictions, sharedMetadata, ); } /** * The Codex accounts whose model allowlists bound the `codex/` restriction: * the core connections that can serve this subject's new work. */ async function codexAccountsForModelRestrictions( db: Database, workspaceId: string, subjectId: string, ): Promise< Array<{ status: string; allocatorEnabled: boolean; allowedModelIds?: string[] | null }> > { const { accountId } = await rlsContextForWorkspace(db, workspaceId); const serving = await listSubscriptionCoreCodexServingConnections(db, { accountId, workspaceId, subjectId, }); return serving.map((connection) => ({ status: "active", allocatorEnabled: true, allowedModelIds: subscriptionCoreCodexConnectionAllowlist(connection), })); } export const CODEX_RESET_REDEMPTION_OUTCOMES = [ "reset", "nothingToReset", "noCredit", "alreadyRedeemed", ] as const; export type CodexResetRedemptionOutcome = (typeof CODEX_RESET_REDEMPTION_OUTCOMES)[number]; export type CodexResetRedemptionStatus = "processing" | "provider_started" | "completed"; export type CodexResetRedemptionAttempt = { id: string; accountId: string; workspaceId: string; credentialId: string; subjectId: string; browserSessionHash: string; creditId: string; upstreamIdempotencyKey: string; status: CodexResetRedemptionStatus; outcome: CodexResetRedemptionOutcome | null; claimHolderId: string | null; claimExpiresAt: Date | null; confirmationExpiresAt: Date; providerStartedAt: Date | null; completedAt: Date | null; lastFailureKind: string | null; retryCount: number; createdAt: Date; updatedAt: Date; }; function mapCodexResetRedemptionAttempt( row: typeof schema.codexResetRedemptionAttempts.$inferSelect, ): CodexResetRedemptionAttempt { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, credentialId: row.credentialId, subjectId: row.subjectId, browserSessionHash: row.browserSessionHash, creditId: row.creditId, upstreamIdempotencyKey: row.upstreamIdempotencyKey, status: row.status as CodexResetRedemptionStatus, outcome: row.outcome as CodexResetRedemptionOutcome | null, claimHolderId: row.claimHolderId, claimExpiresAt: codexMetadataDate(row.claimExpiresAt), confirmationExpiresAt: codexMetadataDate(row.confirmationExpiresAt)!, providerStartedAt: codexMetadataDate(row.providerStartedAt), completedAt: codexMetadataDate(row.completedAt), lastFailureKind: row.lastFailureKind, retryCount: row.retryCount, createdAt: codexMetadataDate(row.createdAt)!, updatedAt: codexMetadataDate(row.updatedAt)!, }; } /** Metadata-only attempt read used to resume a browser-session-bound ambiguity. */ export async function getCodexResetRedemptionAttempt( db: Database, workspaceId: string, attemptId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, workspaceId), eq(schema.codexResetRedemptionAttempts.id, attemptId), ), ) .limit(1); return row ? mapCodexResetRedemptionAttempt(row) : null; }); } export type CodexResetRedemptionRecovery = { attemptId: string; credentialId: string; creditId: string; status: "provider_started" | "completed"; outcome: CodexResetRedemptionOutcome | null; providerStartedAt: Date | null; completedAt: Date | null; createdAt: Date; updatedAt: Date; }; /** * Who may redeem a credential's reset credits, read (and share-locked * against disconnect or credential replacement) inside the ledger * transaction. `null` is an unknown credential in this workspace. The legacy * rule is the human who connected it; the shared core supplies its own * section 6.3 authority (M3 PR 2c). */ export type CodexResetRedemptionCredentialAuthority = ( tx: Database, input: { accountId: string; workspaceId: string; credentialId: string; subjectId: string }, ) => Promise<{ status: string; owned: boolean } | null>; /** * The cross-workspace fence of one provider credit (M3 PR 3b): `clear` when * no other workspace holds the credit, `refiled` when the caller's own * logical attempt was moved here from another workspace for recovery, * `held_elsewhere` when another workspace holds it, `refused` without * redemption authority. The legacy ledger passes none (per-workspace). */ export type CodexResetCreditFence = ( tx: Database, input: { accountId: string; workspaceId: string; credentialId: string; subjectId: string; creditId: string; attemptId: string; }, ) => Promise<"clear" | "refiled" | "held_elsewhere" | "refused">; export type AdoptCodexResetRedemptionResult = | { kind: "current" | "adopted"; attempt: CodexResetRedemptionAttempt } | { kind: "in_progress" } | { kind: "not_found" } | { kind: "forbidden" } | { kind: "conflict" }; /** Adopt a released durable ambiguity/completion into the owner's current browser session. */ export async function adoptCodexResetRedemptionAttempt( db: Database, input: { accountId: string; workspaceId: string; attemptId: string; credentialId: string; creditId: string; subjectId: string; browserSessionHash: string; }, authority: CodexResetRedemptionCredentialAuthority, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const credential = await authority(tx as unknown as Database, input); if (!credential) return { kind: "not_found" } as const; if (!credential.owned) { return { kind: "forbidden" } as const; } const [attempt] = await tx .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), ), ) .for("update") .limit(1); if (!attempt) return { kind: "not_found" } as const; if ( attempt.accountId !== input.accountId || attempt.credentialId !== input.credentialId || attempt.creditId !== input.creditId || attempt.subjectId !== input.subjectId ) { return { kind: "conflict" } as const; } if (attempt.browserSessionHash === input.browserSessionHash) { return { kind: "current", attempt: mapCodexResetRedemptionAttempt(attempt), } as const; } if (attempt.status !== "provider_started" && attempt.status !== "completed") { return { kind: "conflict" } as const; } const claim = await tx.execute<{ claim_live: boolean }>(sql` select claim_expires_at > now() as claim_live from codex_reset_redemption_attempts where workspace_id = ${input.workspaceId} and id = ${input.attemptId} `); if (claim[0]?.claim_live) return { kind: "in_progress" } as const; const [adopted] = await tx .update(schema.codexResetRedemptionAttempts) .set({ browserSessionHash: input.browserSessionHash, claimHolderId: null, claimExpiresAt: null, updatedAt: sql`now()`, }) .where(eq(schema.codexResetRedemptionAttempts.id, input.attemptId)) .returning(); if (!adopted) throw new Error("Codex redemption adoption returned no row"); return { kind: "adopted", attempt: mapCodexResetRedemptionAttempt(adopted), } as const; }), ); } export type ClaimCodexResetRedemptionResult = | { kind: "claimed"; attempt: CodexResetRedemptionAttempt } | { kind: "in_progress"; attempt: CodexResetRedemptionAttempt } | { kind: "completed"; attempt: CodexResetRedemptionAttempt } | { kind: "not_found" } | { kind: "forbidden" } | { kind: "conflict" }; /** * Claim or reclaim one logical redemption across API replicas/crashes. * * A transaction advisory lock closes the initial INSERT race. A live claim * yields `in_progress`; an expired/released claim is reclaimed without changing * the status or upstream key. Existing attempt identity is immutable. */ export async function claimCodexResetRedemption( db: Database, input: { id: string; accountId: string; workspaceId: string; credentialId: string; subjectId: string; browserSessionHash: string; creditId: string; confirmationExpiresAt: Date; claimHolderId: string; claimTtlMs?: number; }, authority: CodexResetRedemptionCredentialAuthority, creditFence: CodexResetCreditFence | null = null, ): Promise { const claimTtlMs = input.claimTtlMs ?? 60_000; if (!Number.isFinite(claimTtlMs) || claimTtlMs <= 0) { throw new Error("Codex redemption claim TTL must be positive"); } if ( !Number.isFinite(input.confirmationExpiresAt.getTime()) || input.confirmationExpiresAt.getTime() <= Date.now() ) { return { kind: "forbidden" }; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`codex-reset-attempt:${input.id}`}, 0))`, ); // A second browser tab has a different attempt UUID. Serialize on the // irreversible provider credit too, then let the unique index provide // the durable fail-closed backstop. await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`codex-reset-credit:${input.workspaceId}:${input.credentialId}:${input.creditId}`}, 0))`, ); const credential = await authority(tx as unknown as Database, input); if (!credential) return { kind: "not_found" } as const; // The core ledger also fences the credit across workspaces: another // workspace's open or consumed attempt for the same credit wins, and // the caller's own attempt filed elsewhere is moved here to recover. if (creditFence) { const fence = await creditFence(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, credentialId: input.credentialId, subjectId: input.subjectId, creditId: input.creditId, attemptId: input.id, }); if (fence === "refused") return { kind: "forbidden" } as const; if (fence === "held_elsewhere") return { kind: "conflict" } as const; } const [existing] = await tx .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.id), ), ) .for("update") .limit(1); const now = new Date(); if (existing) { if ( existing.accountId !== input.accountId || existing.credentialId !== input.credentialId || existing.subjectId !== input.subjectId || existing.browserSessionHash !== input.browserSessionHash || existing.creditId !== input.creditId ) { return { kind: "conflict" } as const; } if (!credential.owned) { return { kind: "forbidden" } as const; } const mapped = mapCodexResetRedemptionAttempt(existing); // Completion is durable truth. A token-health transition after the // provider outcome committed must not turn an HTTP-response-loss // replay into a false 403 or trigger a second consume. Current human // ownership remains mandatory, but active health is needed only when // work may still have to reach the provider. if (mapped.status === "completed") return { kind: "completed", attempt: mapped }; if (credential.status !== "active") { return { kind: "forbidden" } as const; } const claimState = await tx.execute(sql<{ claim_live: boolean }>` select claim_expires_at > now() as claim_live from codex_reset_redemption_attempts where workspace_id = ${input.workspaceId} and id = ${input.id} `); if (claimState[0]?.claim_live) { return { kind: "in_progress", attempt: mapped }; } const [reclaimed] = await tx .update(schema.codexResetRedemptionAttempts) .set({ claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimTtlMs} * interval '1 millisecond')`, confirmationExpiresAt: input.confirmationExpiresAt, lastFailureKind: null, retryCount: sql`${schema.codexResetRedemptionAttempts.retryCount} + 1`, updatedAt: now, }) .where(eq(schema.codexResetRedemptionAttempts.id, input.id)) .returning(); if (!reclaimed) throw new Error("Codex redemption reclaim returned no row"); return { kind: "claimed", attempt: mapCodexResetRedemptionAttempt(reclaimed), }; } // Authorize before looking up credit-attempt state so a non-owner cannot // distinguish an unused provider credit from one with an existing attempt. if (credential.status !== "active" || !credential.owned) { return { kind: "forbidden" } as const; } const [creditAttempt] = await tx.execute<{ id: string; status: CodexResetRedemptionStatus; claim_live: boolean | null; }>(sql` select id, status, claim_expires_at > now() as claim_live from codex_reset_redemption_attempts where workspace_id = ${input.workspaceId} and credential_id = ${input.credentialId} and credit_id = ${input.creditId} and (status <> 'completed' or outcome in ('reset', 'alreadyRedeemed')) limit 1 for update `); if (creditAttempt) { // A different browser UUID may replace only definite pre-provider // work whose claim is released/expired. The per-credit advisory lock // serializes replacement with a late original claimant, and the // DB-time predicate prevents an application-clock race. Once // provider_started (or successfully completed), preserve the one // upstream idempotency key and fail closed. if (creditAttempt.status !== "processing" || creditAttempt.claim_live) { return { kind: "conflict" } as const; } const removed = await tx .delete(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, creditAttempt.id), eq(schema.codexResetRedemptionAttempts.status, "processing"), sql`(${schema.codexResetRedemptionAttempts.claimExpiresAt} is null or ${schema.codexResetRedemptionAttempts.claimExpiresAt} <= now())`, ), ) .returning({ id: schema.codexResetRedemptionAttempts.id }); if (removed.length !== 1) return { kind: "conflict" } as const; } const [created] = await tx .insert(schema.codexResetRedemptionAttempts) .values({ id: input.id, accountId: input.accountId, workspaceId: input.workspaceId, credentialId: input.credentialId, subjectId: input.subjectId, browserSessionHash: input.browserSessionHash, creditId: input.creditId, status: "processing", claimHolderId: input.claimHolderId, claimExpiresAt: sql`now() + (${claimTtlMs} * interval '1 millisecond')`, confirmationExpiresAt: input.confirmationExpiresAt, }) .returning(); if (!created) throw new Error("Codex redemption claim returned no row"); return { kind: "claimed", attempt: mapCodexResetRedemptionAttempt(created), }; }), ); } export type CodexResetRedemptionSendNotReadyReason = | "not_found" | "identity_mismatch" | "claim_expired" | "confirmation_expired" | "credential_unavailable" | "already_completed"; export type FenceCodexResetRedemptionSendResult = | { kind: "ready"; attempt: CodexResetRedemptionAttempt } | { kind: "not_ready"; reason: CodexResetRedemptionSendNotReadyReason; }; /** * Final DB-time irreversible-send fence, called only after preflight and token * resolution and immediately before every provider POST (including ambiguity * retries). The credential SHARE lock serializes against disconnect and * ownership-changing reconnect. The claim is extended beyond the bounded * consume operation in the same transaction that persists provider_started. */ export async function fenceCodexResetRedemptionSend( db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; credentialId: string; subjectId: string; browserSessionHash: string; sendLeaseMs?: number; }, authority: CodexResetRedemptionCredentialAuthority, ): Promise { const sendLeaseMs = input.sendLeaseMs ?? 30_000; if (!Number.isFinite(sendLeaseMs) || sendLeaseMs <= 10_000) { throw new Error("Codex redemption send lease must exceed the bounded provider call"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const credential = await authority(tx as unknown as Database, input); const [attempt] = await tx .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.accountId, input.accountId), eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), ), ) .for("update") .limit(1); if (!attempt) return { kind: "not_ready", reason: "not_found" } as const; if ( attempt.credentialId !== input.credentialId || attempt.subjectId !== input.subjectId || attempt.browserSessionHash !== input.browserSessionHash || attempt.claimHolderId !== input.claimHolderId ) { return { kind: "not_ready", reason: "identity_mismatch" } as const; } if (attempt.status === "completed") { return { kind: "not_ready", reason: "already_completed" } as const; } const [liveness] = await tx.execute<{ claim_live: boolean; confirmation_live: boolean; }>(sql` select claim_expires_at > now() as claim_live, confirmation_expires_at > now() as confirmation_live from codex_reset_redemption_attempts where workspace_id = ${input.workspaceId} and id = ${input.attemptId} `); let reason: CodexResetRedemptionSendNotReadyReason; if (!liveness?.claim_live) reason = "claim_expired"; else if (!liveness.confirmation_live) reason = "confirmation_expired"; else if (!credential || credential.status !== "active" || !credential.owned) { reason = "credential_unavailable"; } else { const [ready] = await tx .update(schema.codexResetRedemptionAttempts) .set({ status: "provider_started", providerStartedAt: sql`coalesce(${schema.codexResetRedemptionAttempts.providerStartedAt}, now())`, claimExpiresAt: sql`now() + (${sendLeaseMs} * interval '1 millisecond')`, lastFailureKind: null, updatedAt: sql`now()`, }) .where(eq(schema.codexResetRedemptionAttempts.id, input.attemptId)) .returning(); if (!ready) throw new Error("Codex redemption send fence returned no row"); return { kind: "ready", attempt: mapCodexResetRedemptionAttempt(ready), } as const; } // Before provider_started it is safe to remove the false logical // attempt. Once provider work may have begun, preserve the upstream key // and merely release this request's stale claim for owner recovery. if (attempt.status === "processing") { await tx .delete(schema.codexResetRedemptionAttempts) .where(eq(schema.codexResetRedemptionAttempts.id, input.attemptId)); } else { await tx .update(schema.codexResetRedemptionAttempts) .set({ claimHolderId: null, claimExpiresAt: null, lastFailureKind: `send_fence_${reason}`, updatedAt: sql`now()`, }) .where(eq(schema.codexResetRedemptionAttempts.id, input.attemptId)); } return { kind: "not_ready", reason } as const; }), ); } /** Delete only definite pre-provider work still owned by this request. */ export async function abandonCodexResetRedemptionBeforeProvider( db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const deleted = await scopedDb .delete(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), eq(schema.codexResetRedemptionAttempts.status, "processing"), eq(schema.codexResetRedemptionAttempts.claimHolderId, input.claimHolderId), ), ) .returning({ id: schema.codexResetRedemptionAttempts.id }); return deleted.length === 1; }, ); } /** Release a failed claim while preserving processing/provider_started truth. */ export async function releaseCodexResetRedemptionClaim( db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; failureKind: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.codexResetRedemptionAttempts) .set({ claimHolderId: null, claimExpiresAt: null, lastFailureKind: input.failureKind.slice(0, 100), updatedAt: new Date(), }) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), eq(schema.codexResetRedemptionAttempts.claimHolderId, input.claimHolderId), sql`${schema.codexResetRedemptionAttempts.status} <> 'completed'`, ), ) .returning({ id: schema.codexResetRedemptionAttempts.id }); return rows.length === 1; }, ); } /** * Section 6.3 reset-credit authority on the shared core (M3 PR 2c): the * database decides, inside the ledger transaction, whether the RLS subject is * an organization administrator or an administrator of the workspace that * manages this shared Codex connection, and share-locks the connection * against disconnect or credential replacement. Nothing without an enabled * Codex cutover. */ export const subscriptionCoreCodexResetAuthority: CodexResetRedemptionCredentialAuthority = async ( tx, input, ) => { const [row] = await rawRows<{ status: string; authorized: boolean }>( tx, sql`select status, authorized from opengeni_private.subscription_codex_reset_authority( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.credentialId}::uuid, ${input.subjectId} )`, ); return row ? { status: row.status, owned: row.authorized === true } : null; }; /** The core ledger's cross-workspace credit fence (`subscription_codex_reset_credit_fence`). */ export const subscriptionCoreCodexResetCreditFence: CodexResetCreditFence = async (tx, input) => { const [row] = await rawRows<{ outcome: string }>( tx, sql`select outcome from opengeni_private.subscription_codex_reset_credit_fence( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.credentialId}::uuid, ${input.subjectId}, ${input.creditId}, ${input.attemptId}::uuid )`, ); const outcome = row?.outcome; return outcome === "clear" || outcome === "refiled" || outcome === "held_elsewhere" ? outcome : "refused"; }; /** * Run the cross-workspace credit fence on its own (redemption prepare): a * person recovering their own attempt from another workspace gets it moved * here, so the ordinary adopt and claim continue on the same upstream key. */ export async function fenceSubscriptionCoreCodexResetCredit( db: Database, input: Parameters[1], ): Promise>> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction( async (tx) => await subscriptionCoreCodexResetCreditFence(tx as unknown as Database, input), ), ); } /** * Persist the exact provider outcome of a core redemption with its audit * record. A credit that restores capacity (`reset` or `alreadyRedeemed`) * invalidates the connection's stored usage windows and exhaustion deadline * (`recordSubscriptionCoreRateLimitResetInTransaction`: they were read before * the reset), so a woken waiter places on the connection again instead of * re-waiting on a stale window's reset; only a quota observed with the * connection's current refresh generation is rewritten. It returns a core * wake for the caller to deliver after commit. The legacy credential columns * and outbox are never touched. */ export async function completeSubscriptionCoreCodexResetRedemption( db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; outcome: CodexResetRedemptionOutcome; }, ): Promise<{ attempt: CodexResetRedemptionAttempt | null; wake: SubscriptionCoreCodexWake | null; }> { if (!CODEX_RESET_REDEMPTION_OUTCOMES.includes(input.outcome)) { throw new Error("Unknown Codex redemption outcome"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`codex-reset-attempt:${input.attemptId}`}, 0))`, ); const [current] = await tx .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.accountId, input.accountId), eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), ), ) .for("update") .limit(1); if (!current) return { attempt: null, wake: null }; if (current.status === "completed") { return { attempt: mapCodexResetRedemptionAttempt(current), wake: null }; } if ( current.status !== "provider_started" || current.claimHolderId !== input.claimHolderId ) { return { attempt: null, wake: null }; } const completedAt = new Date(); const [completed] = await tx .update(schema.codexResetRedemptionAttempts) .set({ status: "completed", outcome: input.outcome, completedAt, claimHolderId: null, claimExpiresAt: null, lastFailureKind: null, updatedAt: completedAt, }) .where( and( eq(schema.codexResetRedemptionAttempts.accountId, input.accountId), eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.id, input.attemptId), ), ) .returning(); if (!completed) throw new Error("Codex redemption completion returned no row"); const restoresCapacity = input.outcome === "reset" || input.outcome === "alreadyRedeemed"; if (restoresCapacity) { await recordSubscriptionCoreRateLimitResetInTransaction(tx as unknown as Database, { accountId: input.accountId, provider: "codex", connectionId: current.credentialId, resetAt: completedAt, }); } await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: current.subjectId, action: "codex.reset_credit.redemption.completed", targetType: "codex_reset_redemption_attempt", targetId: input.attemptId, metadata: { outcome: input.outcome }, }, "metadata", "metadataCodecVersion", ), ); return { attempt: mapCodexResetRedemptionAttempt(completed), // A successful or already-applied reset can make waiters eligible // even when no exhaustion was stored. wake: restoresCapacity ? { accountId: input.accountId, reason: "codex_reset_credit_redeemed" } : null, }; }), ); } /** * The owner's durable ambiguous/completed core redemptions in this * workspace, limited to connections the same person may still redeem on * (the section 6.3 authority, read in the same transaction). */ export async function listSubscriptionCoreCodexResetRedemptionRecoveries( db: Database, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.codexResetRedemptionAttempts) .where( and( eq(schema.codexResetRedemptionAttempts.workspaceId, input.workspaceId), eq(schema.codexResetRedemptionAttempts.subjectId, input.subjectId), inArray(schema.codexResetRedemptionAttempts.status, ["provider_started", "completed"]), ), ) .orderBy(desc(schema.codexResetRedemptionAttempts.createdAt)); const allowed = new Map(); for (const credentialId of new Set(rows.map((row) => row.credentialId))) { const authority = await subscriptionCoreCodexResetAuthority(scopedDb, { ...input, credentialId, }); allowed.set(credentialId, authority?.owned === true); } return rows .filter((row) => allowed.get(row.credentialId) === true) .map((row) => ({ attemptId: row.id, credentialId: row.credentialId, creditId: row.creditId, status: row.status as "provider_started" | "completed", outcome: row.outcome as CodexResetRedemptionOutcome | null, providerStartedAt: codexMetadataDate(row.providerStartedAt), completedAt: codexMetadataDate(row.completedAt), createdAt: codexMetadataDate(row.createdAt)!, updatedAt: codexMetadataDate(row.updatedAt)!, })); }, ); } /** Per-connection redemption authority for the caller, read outside the ledger. */ export async function readSubscriptionCoreCodexResetAuthority( db: Database, input: { accountId: string; workspaceId: string; credentialId: string; subjectId: string }, ): Promise<{ status: string; owned: boolean } | null> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => await subscriptionCoreCodexResetAuthority(tx, input), ); } /** * Per-workspace model/provider availability policy. NULL fields = unrestricted. * Non-null allowedProviders is a strict allowlist over resolved provider * identities; non-null allowedModels an additional exact model-id allowlist. * Consumers: the API model choke points (fail 422) and the worker's * post-resolution gate (a blocked provider never reaches a model call and * never silently remaps). * * The organization's allowlist (organization_model_defaults) is a ceiling for * every workspace in it. A workspace row only narrows it: a model must pass * both. Without a row the workspace uses the organization's list as is; with * neither, every model is allowed. */ export type WorkspaceModelPolicy = { allowedProviders: string[] | null; allowedModels: string[] | null; }; /** * The policy a workspace runs with: the allowlists it follows plus its own * credit switch (`allowCreditModels`, the workspace setting). The switch is * independent of where the allowlists come from, so following the * organization's allowlists never turns credits back on. */ export type EffectiveWorkspaceModelPolicy = WorkspaceModelPolicy & { /** False blocks every model billed in Opengeni credits, current and future. */ allowCreditModels: boolean; }; function restrictsAnything(policy: WorkspaceModelPolicy | null | undefined): boolean { return Boolean(policy && (policy.allowedProviders !== null || policy.allowedModels !== null)); } /** One allowlist narrowed by another; null allows everything. */ function narrowAllowlist(ceiling: string[] | null, own: string[] | null): string[] | null { if (ceiling === null) return own; if (own === null) return ceiling; const allowed = new Set(ceiling); return own.filter((id) => allowed.has(id)); } /** * What a workspace may use: its own allowlists within the organization's. A * model passes only when both allow its provider and both allow the model. */ function narrowWorkspaceModelPolicy( organization: WorkspaceModelPolicy | null, workspace: WorkspaceModelPolicy | null, ): WorkspaceModelPolicy | null { if (!organization) return workspace; if (!workspace) return organization; return { allowedProviders: narrowAllowlist(organization.allowedProviders, workspace.allowedProviders), allowedModels: narrowAllowlist(organization.allowedModels, workspace.allowedModels), }; } /** * The workspace's own policy row and the organization's ceiling above it. * `organization` is null when the organization allows every model. */ export async function getWorkspaceModelPolicyLayers( db: Database, workspaceId: string, ): Promise<{ workspace: WorkspaceModelPolicy | null; organization: WorkspaceModelPolicy | null; /** The workspace's credit switch; true unless its setting is explicitly false. */ allowCreditModels: boolean; }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ workspaceSettings: schema.workspaces.settings, workspaceAllowedProviders: schema.workspaceModelPolicies.allowedProviders, workspaceAllowedModels: schema.workspaceModelPolicies.allowedModels, workspacePolicyId: schema.workspaceModelPolicies.id, organizationAllowedProviders: schema.organizationModelDefaults.allowedProviders, organizationAllowedModels: schema.organizationModelDefaults.allowedModels, }) .from(schema.workspaces) .leftJoin( schema.workspaceModelPolicies, eq(schema.workspaceModelPolicies.workspaceId, schema.workspaces.id), ) .leftJoin( schema.organizationModelDefaults, eq(schema.organizationModelDefaults.accountId, schema.workspaces.accountId), ) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if (!row) return { workspace: null, organization: null, allowCreditModels: true }; const organization = { allowedProviders: row.organizationAllowedProviders ?? null, allowedModels: row.organizationAllowedModels ?? null, }; return { workspace: row.workspacePolicyId ? { allowedProviders: row.workspaceAllowedProviders ?? null, allowedModels: row.workspaceAllowedModels ?? null, } : null, organization: restrictsAnything(organization) ? organization : null, allowCreditModels: workspaceSettingsAllowCreditModels(row.workspaceSettings), }; }); } /** * The policy this workspace runs with: its own allowlists narrowed within its * organization's, plus its credit switch. Null only when nothing is * restricted (every model allowed and credits on). */ export async function getWorkspaceModelPolicy( db: Database, workspaceId: string, ): Promise { return effectiveWorkspaceModelPolicy(await getWorkspaceModelPolicyLayers(db, workspaceId)); } /** The policy a workspace runs with, from its already-read layers. */ function effectiveWorkspaceModelPolicy( layers: Awaited>, ): EffectiveWorkspaceModelPolicy | null { const allowlists = narrowWorkspaceModelPolicy(layers.organization, layers.workspace); if (!restrictsAnything(allowlists) && layers.allowCreditModels) return null; return { allowedProviders: allowlists?.allowedProviders ?? null, allowedModels: allowlists?.allowedModels ?? null, allowCreditModels: layers.allowCreditModels, }; } /** Remove the workspace's own policy so it uses its organization's list as is. */ export async function deleteWorkspaceModelPolicy( db: Database, input: { accountId: string; workspaceId: string }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .delete(schema.workspaceModelPolicies) .where(eq(schema.workspaceModelPolicies.workspaceId, input.workspaceId)); }, ); } /** * Create or replace the workspace's own model policy. Passing null for a field * clears that restriction. It only ever narrows the organization's list, so * {null, null} allows exactly what the organization allows. */ export async function upsertWorkspaceModelPolicy( db: Database, input: { accountId: string; workspaceId: string; allowedProviders: string[] | null; allowedModels: string[] | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.workspaceModelPolicies) .values({ accountId: input.accountId, workspaceId: input.workspaceId, allowedProviders: input.allowedProviders, allowedModels: input.allowedModels, }) .onConflictDoUpdate({ target: [schema.workspaceModelPolicies.workspaceId], set: { allowedProviders: input.allowedProviders, allowedModels: input.allowedModels, updatedAt: new Date(), }, }) .returning({ allowedProviders: schema.workspaceModelPolicies.allowedProviders, allowedModels: schema.workspaceModelPolicies.allowedModels, }); return row!; }, ); } /** Lease-backed serving audit, written after placement in its own fenced * transaction. Proposals and claim-time provenance alone emit no transition. */ export async function recordSubscriptionCoreServingSelectionForTurnAttempt( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; provider: string; connectionId: string; modelId: string; reason: import("@opengeni/contracts").TurnServingPolicyV1["reason"]; }, ): Promise<{ events: SessionEvent[]; previousProvider: string | null }> { return withWorkspaceSessionEventActivityRls(db, input.workspaceId, true, async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, sessionLock: "no_key_update" }); if (!fence.allowed || !fence.session || fence.turn.accountId !== input.accountId) throw new Error("Subscription selection attempt fenced"); const stored = readTurnServingPolicyV1(fence.turn.metadata); const revision = stored.kind === "valid" ? stored.revisions.at(-1) : undefined; if ( !revision || revision.executionGeneration !== input.executionGeneration || revision.policy.productModelId !== input.modelId ) throw new Error("Subscription selection requires this generation's serving revision"); const key = `opengeni:subscription-selection:${input.attemptId}`; const prior = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), inArray(schema.sessionEvents.clientEventId, [key, `${key}:switch`]), ), ) .orderBy(asc(schema.sessionEvents.sequence)); if (prior.length) { const selected = prior.find((event) => event.type === "subscription.account.selected"); if (!selected) throw new Error("Subscription selection receipt missing"); const payload = sessionEventPayloadRecord(selected.payload, selected.payloadCodecVersion); if ( payload.connectionId !== input.connectionId || payload.provider !== input.provider || payload.modelId !== input.modelId ) throw new Error("An attempt cannot record conflicting subscription selections"); return { events: prior.map(mapEvent), previousProvider: typeof payload.previousProvider === "string" ? payload.previousProvider : null, }; } // Provenance is not dispatch permission. An event describes only a live, // committed placement of this exact generation, never a pending proposal. const [lease] = await rawRows<{ present: boolean }>( tx, sql`select exists ( select 1 from subscription_leases where account_id=${input.accountId}::uuid and workspace_id=${input.workspaceId}::uuid and session_id=${input.sessionId}::uuid and turn_id=${input.turnId}::uuid and provider=${input.provider} and connection_id=${input.connectionId}::uuid and generation=${input.executionGeneration} and leased_until > clock_timestamp() ) as present`, ); if (!lease?.present) throw new Error("Subscription selection requires its live placed lease"); const [last] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "subscription.account.selected"), ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); const previous = last ? sessionEventPayloadRecord(last.payload, last.payloadCodecVersion) : null; const previousProvider = typeof previous?.provider === "string" ? previous.provider : null; const fromAccountId = typeof previous?.connectionId === "string" ? previous.connectionId : null; const accepted = readTurnExecutionPolicyV1(fence.turn.metadata); const fromModelId = typeof previous?.modelId === "string" ? previous.modelId : accepted.kind === "valid" ? accepted.policy.productModelId : input.modelId; const common = { provider: input.provider, executionGeneration: input.executionGeneration, servingHistoryPosition: revision.historyPosition, reason: input.reason, preferredModelId: accepted.kind === "valid" ? accepted.policy.productModelId : input.modelId, reasoningEffort: revision.policy.reasoningEffort, latencyMode: revision.policy.latencyMode, }; const events: AppendEventInput[] = []; if ( (fromAccountId !== null && fromAccountId !== input.connectionId) || fromModelId !== input.modelId ) events.push({ type: "subscription.account.switched", clientEventId: `${key}:switch`, payload: { ...common, fromProvider: previousProvider, fromAccountId, toAccountId: input.connectionId, fromModelId, toModelId: input.modelId, }, }); events.push({ type: "subscription.account.selected", clientEventId: key, payload: { ...common, previousProvider, connectionId: input.connectionId, modelId: input.modelId, }, }); const appended = await appendSessionEventsForTurnAttempt( tx, input.workspaceId, input.sessionId, input.turnId, input.executionGeneration, input.attemptId, events, ); if (!appended.accepted) throw new Error("Subscription selection attempt fenced"); return { events: appended.events, previousProvider }; }); } /** Legacy Codex audit/alias, projected from core placement without writing * the old session credential pointer. Idempotent under the same attempt fence. */ export async function recordSubscriptionCoreCodexSelectionForTurnAttempt( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; credentialId: string; previousCredentialId: string | null; strategy: string; reusedLease: boolean; pinnedCredentialId: string | null; eligibleCount: number; connectedCount: number; }, ): Promise<{ events: SessionEvent[]; diagnostics: ReturnType }> { return await withWorkspaceSessionEventActivityRls(db, input.workspaceId, true, async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, sessionLock: "no_key_update", }); if (!fence.allowed || !fence.session) throw new CodexCredentialLeaseAttemptFencedError(); const key = `opengeni:codex-selection:${input.attemptId}`; const prior = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), inArray(schema.sessionEvents.clientEventId, [key, `${key}:switch`]), ), ) .orderBy(asc(schema.sessionEvents.sequence)); if (prior.length) { const receipt = prior.find((event) => event.type === "codex.credential.selected"); if (!receipt) throw new Error("Codex selection receipt missing"); const payload = sessionEventPayloadRecord(receipt.payload, receipt.payloadCodecVersion); if (payload.credentialId !== input.credentialId) throw new Error("An attempt cannot record two different Codex selections"); return { events: prior.map(mapEvent), diagnostics: { transition: payload.transition, source: payload.source, reason: payload.reason, } as ReturnType, }; } const previousCredentialId = input.previousCredentialId; const diagnostics = codexSelectionDiagnostics({ ...input, pinSource: input.pinnedCredentialId ? "manual" : null, }); const events: AppendEventInput[] = []; if (previousCredentialId !== null && previousCredentialId !== input.credentialId) { events.push({ type: "codex.account.switched", clientEventId: `${key}:switch`, payload: { fromAccountId: previousCredentialId, toAccountId: input.credentialId, reason: diagnostics.source === "manual_pin" ? "manual" : "rotation", }, }); } events.push({ type: "codex.credential.selected", clientEventId: key, payload: { credentialId: input.credentialId, strategy: input.strategy, ...diagnostics, previousCredentialId, eligibleCount: input.eligibleCount, connectedCount: input.connectedCount, reused: input.reusedLease, }, }); const appended = await appendSessionEventsForTurnAttempt( tx, input.workspaceId, input.sessionId, input.turnId, input.executionGeneration, input.attemptId, events, ); if (!appended.accepted) throw new CodexCredentialLeaseAttemptFencedError(); return { events: appended.events, diagnostics }; }); } /** * The session Codex projection (`GET .../sessions/:id/codex-accounts`) for an * organization whose Codex cutover is enabled: the same shape as * `getSessionCodexAccounts`, projected from the session's core binding, the * active turn's core lease and the workspace's core account pool. The * "Running on" account of a running turn is its live core lease; a waiting * turn shows only an explicit choice. Never reads a legacy Codex table. * * A turn running on a personal connection shows it only to that connection's * owner (`viewerSubjectId`), read through the owner-only reader (M3 PR 3b); * anyone else sees the id with a null account, as before. */ export async function getSubscriptionCoreSessionCodexAccounts( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; viewerSubjectId?: string | null; }, ) { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const [session] = await tx .select({ id: schema.sessions.id, activeTurnId: schema.sessions.activeTurnId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session) return null; const projection = await projectSubscriptionCoreCodexWorkspace(tx, input); const codexBinding = await readCoreSessionBinding(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, provider: "codex", }); const [turn] = session.activeTurnId ? await rawRows<{ id: string; status: string; connection_id: string | null }>( tx, sql`select turn.id::text as id, turn.status, lease.connection_id::text as connection_id from session_turns turn left join subscription_leases lease on lease.account_id = turn.account_id and lease.workspace_id = turn.workspace_id and lease.turn_id = turn.id and lease.provider = 'codex' and lease.leased_until > clock_timestamp() where turn.account_id = ${input.accountId}::uuid and turn.workspace_id = ${input.workspaceId}::uuid and turn.session_id = ${input.sessionId}::uuid and turn.id = ${session.activeTurnId}::uuid and turn.status in ('running', 'recovering', 'waiting_capacity', 'requires_action') and turn.model like 'codex/%' limit 1`, ) : []; const waiting = turn?.status === "waiting_capacity"; const pinnedAccountId = codexBinding?.choice === "explicit" ? codexBinding.connectionId : null; const currentSelection = turn ? { waiting, credentialId: waiting ? pinnedAccountId : turn.connection_id } : null; let currentAccount = projection.accounts.find((account) => account.id === currentSelection?.credentialId) ?? null; if (!currentAccount && currentSelection?.credentialId && input.viewerSubjectId) { const personal = await listSubscriptionCoreCodexPersonalAccountsInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.viewerSubjectId, }); currentAccount = personal.find((account) => account.id === currentSelection.credentialId) ?? null; } return { accounts: projection.accounts, rotation: projection.rotation, currentSelection, currentAccount, pinnedAccountId, lastAccountId: codexBinding?.connectionId ?? null, }; }, ); } /** * The legacy session pointers (`codexPinnedCredentialId`, * `codexLastCredentialId`) of core sessions, projected from their bindings. * A core session without a Codex binding projects nulls: the legacy columns * are never written with core ids and are not shown after the cutover. */ export async function getSubscriptionCoreCodexSessionPointers( db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[] }, ): Promise> { const pointers = new Map< string, { pinnedCredentialId: string | null; lastCredentialId: string | null } >(); const ids = [...new Set(input.sessionIds)]; for (const id of ids) pointers.set(id, { pinnedCredentialId: null, lastCredentialId: null }); if (ids.length === 0) return pointers; const rows = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => await rawRows<{ session_id: string; connection_id: string | null; choice: string }>( tx, sql`select session_id::text as session_id, connection_id::text as connection_id, choice from subscription_session_bindings where account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and provider = 'codex' and session_id in (${sql.join( ids.map((id) => sql`${id}::uuid`), sql`, `, )})`, ), ); for (const row of rows) { pointers.set(row.session_id, { pinnedCredentialId: row.choice === "explicit" ? row.connection_id : null, lastCredentialId: row.connection_id, }); } return pointers; } /** * The legacy `codexCurrentSelection` of core sessions (M3 PR 3): for an * active Codex turn, the live core lease of a running turn, or the session's * explicit core choice while it waits for capacity; null otherwise. The same * rule as `getSubscriptionCoreSessionCodexAccounts`. Never reads a legacy * Codex table (the legacy lease and pin columns are frozen after 0680). */ export async function getSubscriptionCoreCodexCurrentSelections( db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[] }, ): Promise> { const selections = new Map(); const ids = [...new Set(input.sessionIds)]; if (ids.length === 0) return selections; const rows = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => await rawRows<{ session_id: string; status: string; lease_connection_id: string | null; binding_connection_id: string | null; binding_choice: string | null; }>( tx, sql`select session.id::text as session_id, turn.status, lease.connection_id::text as lease_connection_id, binding.connection_id::text as binding_connection_id, binding.choice as binding_choice from sessions session join session_turns turn on turn.account_id = session.account_id and turn.workspace_id = session.workspace_id and turn.session_id = session.id and turn.id = session.active_turn_id left join subscription_leases lease on lease.account_id = turn.account_id and lease.workspace_id = turn.workspace_id and lease.turn_id = turn.id and lease.provider = 'codex' and lease.leased_until > clock_timestamp() left join subscription_session_bindings binding on binding.account_id = session.account_id and binding.workspace_id = session.workspace_id and binding.session_id = session.id and binding.provider = 'codex' where session.account_id = ${input.accountId}::uuid and session.workspace_id = ${input.workspaceId}::uuid and session.id in (${sql.join( ids.map((id) => sql`${id}::uuid`), sql`, `, )}) and turn.status in ('running', 'recovering', 'waiting_capacity', 'requires_action') and turn.model like 'codex/%'`, ), ); for (const row of rows) { const waiting = row.status === "waiting_capacity"; selections.set(row.session_id, { waiting, credentialId: waiting ? row.binding_choice === "explicit" ? row.binding_connection_id : null : row.lease_connection_id, }); } return selections; } /** * Deliver a core Codex wake after the mutation that caused it committed. * Codex's binding of the provider-neutral `deliverSubscriptionCoreWake`. */ export async function deliverSubscriptionCoreCodexWake( db: Database, wake: SubscriptionCoreCodexWake | null, ): Promise { await deliverSubscriptionCoreWake(db, SUBSCRIPTION_CORE_CODEX_PROVIDER, wake, "Codex"); } /** * Deliver a core wake of one provider after the mutation that caused it * committed. A failed wake never fails the committed change: every core * waiter also has its own bounded recheck, so the change is observed at the * latest then. The failure is logged (identifiers and error class only). */ export async function deliverSubscriptionCoreWake( db: Database, provider: string, wake: SubscriptionCoreWake | null, /** The provider's display name in the log line. */ label: string = provider, ): Promise { if (!wake) return; try { await wakeSubscriptionCoreCapacityWaiters( db, provider, { accountId: wake.accountId, reason: wake.reason, ...(wake.workspaceIds ? { workspaceIds: wake.workspaceIds } : {}), ...(wake.sessionIds ? { sessionIds: wake.sessionIds } : {}), ...(wake.ownerMembershipId ? { ownerMembershipId: wake.ownerMembershipId } : {}), }, enqueueSessionWorkflowWakeInTransaction, ); } catch (error) { // Bounded waiter recheck is the backstop (see above). console.warn(`core ${label} wake delivery failed; waiters recheck on their own timer`, { accountId: wake.accountId, reason: wake.reason, workspaceIds: wake.workspaceIds ?? null, sessionIds: wake.sessionIds ?? null, ownerMembershipId: wake.ownerMembershipId ?? null, error: error instanceof Error ? error.name : typeof error, code: (error as { code?: unknown } | null)?.code ?? (error as { cause?: { code?: unknown } } | null)?.cause?.code ?? null, }); } } /** * Deliver a committed capacity change to one provider's core waiters (the * provider-neutral form of `deliverSubscriptionCoreCodexWake`, for the * providers that have no own wake binding), through * `deliverSubscriptionCoreWake`. Never fails the committed change: every core * waiter has its own bounded recheck. */ export async function deliverSubscriptionCoreProviderWake( db: Database, provider: import("@opengeni/subscriptions").ProviderId, wake: { accountId: string; reason: string; workspaceIds?: readonly string[] }, ): Promise { await deliverSubscriptionCoreWake(db, provider, wake); } /** * Deliver the provider wakes of a committed session account choice or * preference change (any registered provider), each through * `deliverSubscriptionCoreWake`. A failed wake never fails the committed * change: every core waiter also has its own bounded recheck. */ export async function deliverSubscriptionCoreProviderWakes( db: Database, wakes: readonly SubscriptionCoreProviderWake[], ): Promise { for (const { provider, ...wake } of wakes) { await deliverSubscriptionCoreWake(db, provider, wake); } } export async function recordAuditEvent( db: Database, input: { accountId: string; workspaceId?: string | null; subjectId?: string | null; action: string; targetType?: string | null; targetId?: string | null; metadata?: Record; }, ): Promise { // audit_events has a FORCED RLS policy keyed on the account/workspace GUCs, // so the insert must run inside an RLS context. await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId ?? null }, async (scopedDb) => { await scopedDb.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId ?? null, subjectId: input.subjectId ?? null, action: input.action, targetType: input.targetType ?? null, targetId: input.targetId ?? null, metadata: input.metadata ?? {}, }, "metadata", "metadataCodecVersion", ), ); }, ); } function mapSessionMcpServerMetadata( row: typeof schema.sessionMcpServers.$inferSelect, ): SessionMcpServerMetadata { return { id: row.serverId, name: row.name ?? null, url: row.url, headerNames: Object.keys(row.headersEncrypted ?? {}).sort(), credentialVersion: Number(row.credentialVersion), requireApproval: row.requireApproval ?? false, connectionRef: row.connectionRef ?? null, }; } async function sessionMcpServerMetadataForSessions( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { const grouped = new Map(); if (sessionIds.length === 0) { return grouped; } const rows = await db .select() .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), inArray(schema.sessionMcpServers.sessionId, sessionIds), ), ) .orderBy(asc(schema.sessionMcpServers.createdAt), asc(schema.sessionMcpServers.serverId)); for (const row of rows) { const list = grouped.get(row.sessionId) ?? []; list.push(mapSessionMcpServerMetadata(row)); grouped.set(row.sessionId, list); } return grouped; } async function insertSessionMcpServers( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; servers: CreateSessionMcpServerInput[]; }, ): Promise { if (input.servers.length === 0) { return []; } const rows = await db .insert(schema.sessionMcpServers) .values( input.servers.map((server) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, serverId: server.id, name: server.name ?? null, url: server.url, allowedTools: server.allowedTools ?? null, timeoutMs: server.timeoutMs ?? null, cacheToolsList: server.cacheToolsList ?? false, requireApproval: server.requireApproval ?? null, connectionRef: server.connectionRef ?? null, headersEncrypted: server.headersEncrypted ?? {}, })), ) .returning(); return rows.map(mapSessionMcpServerMetadata); } export async function createSessionMcpServers( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; servers: CreateSessionMcpServerInput[]; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await insertSessionMcpServers(scopedDb, input), ); } export async function listSessionMcpServerMetadata( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const grouped = await sessionMcpServerMetadataForSessions(scopedDb, workspaceId, [sessionId]); return grouped.get(sessionId) ?? []; }); } /** * Returns the complete stored server configuration needed to snapshot an * immediate parent's MCP context onto a child session. Credential values stay * encrypted throughout this path: the core can copy the ciphertext into the * child's rows, but it never receives plaintext headers. * * This is intentionally distinct from `listSessionMcpServersForRun`, whose * worker-only responsibility is decrypting credentials at the execution * boundary. */ export async function listSessionMcpServersForChildInheritance( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionMcpServers.createdAt), asc(schema.sessionMcpServers.serverId)); return rows.map((row) => ({ id: row.serverId, name: row.name ?? null, url: row.url, allowedTools: row.allowedTools ?? null, timeoutMs: row.timeoutMs ?? null, cacheToolsList: row.cacheToolsList, requireApproval: row.requireApproval ?? null, connectionRef: row.connectionRef ?? null, headersEncrypted: { ...(row.headersEncrypted ?? {}) }, })); }); } export async function updateSessionMcpServerCredentials( db: Database, input: { workspaceId: string; sessionId: string; updates: UpdateSessionMcpServerCredentialsInput[]; }, ): Promise { return await withWorkspaceRls( db, input.workspaceId, async (scopedDb) => await scopedDb.transaction( async (tx) => await updateSessionMcpServerCredentialsInTransaction(tx, input), ), ); } async function updateSessionMcpServerCredentialsInTransaction( tx: Pick, input: { workspaceId: string; sessionId: string; updates: UpdateSessionMcpServerCredentialsInput[]; }, ): Promise { const servers: SessionMcpServerMetadata[] = []; const missingIds: string[] = []; for (const update of input.updates) { const [row] = await tx .update(schema.sessionMcpServers) .set({ headersEncrypted: update.headersEncrypted, credentialVersion: sql`${schema.sessionMcpServers.credentialVersion} + 1`, updatedAt: new Date(), }) .where( and( eq(schema.sessionMcpServers.workspaceId, input.workspaceId), eq(schema.sessionMcpServers.sessionId, input.sessionId), eq(schema.sessionMcpServers.serverId, update.id), ), ) .returning(); if (!row) { missingIds.push(update.id); } else { servers.push(mapSessionMcpServerMetadata(row)); } } return { servers, missingIds }; } /** A response and its write-only header replacements share one commit. */ async function applySessionResponseMcpCredentialUpdatesInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; mcpCredentialUpdates?: UpdateSessionMcpServerCredentialsInput[]; }, ): Promise { if (!input.mcpCredentialUpdates?.length) return; const result = await updateSessionMcpServerCredentialsInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, updates: input.mcpCredentialUpdates, }); if (result.missingIds.length) { throw new Error(`Unknown session MCP server: ${result.missingIds[0]}`); } } export async function updateSessionMcpApprovalPolicy( db: Database, input: { workspaceId: string; sessionId: string; serverId: string; requireApproval: SessionMcpApprovalPolicy; }, ): Promise { return await withWorkspaceSessionActivityRls( db, input.workspaceId, async (scopedDb) => await scopedDb.transaction( async (tx) => await updateSessionMcpApprovalPolicyInTransaction(tx as unknown as Database, input), ), ); } async function updateSessionMcpApprovalPolicyInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; serverId: string; requireApproval: SessionMcpApprovalPolicy; }, ): Promise { const [existing] = await tx .select() .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, input.workspaceId), eq(schema.sessionMcpServers.sessionId, input.sessionId), eq(schema.sessionMcpServers.serverId, input.serverId), ), ) .for("update") .limit(1); if (!existing) { const enabled = await listEnabledMcpCapabilityServers(tx, input.workspaceId); const inherited = enabled.find((server) => server.id === input.serverId); if (!inherited) return { server: null, changed: false }; const [session] = await tx .select({ policies: schema.sessions.mcpApprovalPolicies }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("update") .limit(1); if (!session) return { server: null, changed: false }; const policy = resolveMcpApprovalRecommendation(input.requireApproval, inherited.approvalFloor) ?? false; const server = { id: input.serverId, source: "workspace" as const, requireApproval: policy }; if ( Object.hasOwn(session.policies, input.serverId) && JSON.stringify(session.policies[input.serverId]) === JSON.stringify(policy) ) { return { server, changed: false }; } await withWorkspaceSessionActivityRls(tx, input.workspaceId, async (activityDb) => activityDb .update(schema.sessions) .set({ mcpApprovalPolicies: { ...session.policies, [input.serverId]: policy } }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ), ); return { server, changed: true }; } const current = existing.requireApproval ?? false; if (JSON.stringify(current) === JSON.stringify(input.requireApproval)) { return { server: mapSessionMcpServerMetadata(existing), changed: false }; } const [updated] = await tx .update(schema.sessionMcpServers) .set({ requireApproval: input.requireApproval, updatedAt: new Date(), }) .where( and( eq(schema.sessionMcpServers.workspaceId, input.workspaceId), eq(schema.sessionMcpServers.sessionId, input.sessionId), eq(schema.sessionMcpServers.serverId, input.serverId), ), ) .returning(); if (!updated) { throw new Error(`Session MCP server disappeared during policy update: ${input.serverId}`); } return { server: mapSessionMcpServerMetadata(updated), changed: true }; } export async function listSessionMcpServersForRun( db: Database, workspaceId: string, sessionId: string, attemptId: string, encryptionKey: Uint8Array | null, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [attempt] = await scopedDb .select({ sessionId: schema.sessionTurnAttempts.sessionId, mcpApprovalPolicies: schema.sessionTurnAttempts.mcpApprovalPolicies, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.id, attemptId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); if (!attempt || attempt.sessionId !== sessionId) { throw new Error(`session MCP policy snapshot is unavailable for attempt ${attemptId}`); } const rows = await scopedDb .select() .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionMcpServers.createdAt), asc(schema.sessionMcpServers.serverId)); return rows.map((row) => { if (!Object.hasOwn(attempt.mcpApprovalPolicies, row.serverId)) { throw new Error( `session MCP policy snapshot is missing server ${row.serverId} for attempt ${attemptId}`, ); } let headers: Record; try { if (!encryptionKey && Object.keys(row.headersEncrypted ?? {}).length > 0) { throw new Error("missing encryption key"); } headers = Object.fromEntries( Object.entries(row.headersEncrypted ?? {}).map(([name, stored]) => [ name, decryptEnvironmentValue(encryptionKey!, stored), ]), ); } catch { throw new Error("session MCP server credential decryption failed"); } return { ...mapSessionMcpServerMetadata(row), ...(row.allowedTools ? { allowedTools: row.allowedTools } : {}), ...(row.timeoutMs ? { timeoutMs: row.timeoutMs } : {}), ...(row.cacheToolsList ? { cacheToolsList: row.cacheToolsList } : {}), requireApproval: attempt.mcpApprovalPolicies[row.serverId]!, headers, }; }); }); } export type ConnectorActionPolicyDecision = schema.ConnectorActionPolicyDecision; export type ConnectorActionPolicySnapshotEntry = schema.ConnectorActionPolicySnapshotEntry; export type ConnectorActionAttemptIdentity = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; initiator: Pick; }; export type ConnectorActionInvocation = { approvalId: string; connectionId?: string | null; serverId: string; toolName: string; arguments: unknown; reviewContext?: import("@opengeni/contracts").ToolReviewContext; /** Recommended decision when no explicit user choice matches. */ defaultDecision?: "allow" | "ask"; /** Schema-validated discriminator supplied by the trusted tool adapter. */ actionName?: string; /** Legacy recommendation or capability-authorized mutation ledger mode. */ approvalMode?: "session_mcp" | "connector_write"; /** * Ask (or block) even when the policy allows: destructive or unrecognised * requests (the personal GitHub gateway), or an agent's Can use rule. An * explicit Block still blocks; nothing here loosens a decision. */ minimumDecision?: "ask" | "block"; /** The agent's Can use rule behind `minimumDecision`, recorded on its request. */ minimumDecisionBy?: import("@opengeni/contracts").ToolReviewAgentRule; /** * This execution only tells the provider that the person declined the * question it asked mid-call (MCP elicitation). It is admitted once, from * the rejected round of a request that asked. */ deliversDecline?: true; }; export type PrepareConnectorActionApprovalResult = | { managed: false; decision: "unmanaged" } | { managed: true; decision: ConnectorActionPolicyDecision; requestId?: string; approvalStatus?: string; actionFingerprint: string; /** The agent's Can use rule that made it ask or blocked it. */ agentRule?: import("@opengeni/contracts").ToolReviewAgentRule; }; export type BeginConnectorActionExecutionResult = | { allowed: true; managed: false } | { allowed: true; managed: true; requestId: string; actionFingerprint: string; } | { allowed: false; managed: true; reason: | "approval_required" | "blocked" | "rejected" | "already_executed" | "uncertain_retry" | "not_executed"; requestId: string; actionFingerprint: string; /** With `blocked`, the agent's Can use rule that blocked it. */ agentRule?: import("@opengeni/contracts").ToolReviewAgentRule; }; const CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX = 2048; const CONNECTOR_ACTION_APPROVAL_ID_MAX = 1024; const CONNECTOR_ACTION_CONNECTION_ID_MAX = 512; const CONNECTOR_ACTION_SERVER_ID_MAX = 256; const CONNECTOR_ACTION_NAME_MAX = 512; function boundedConnectorActionText(value: string, label: string, max: number): string { const trimmed = value.trim(); if (trimmed.length === 0 || Buffer.byteLength(trimmed, "utf8") > max) { throw new Error(`${label} must be between 1 and ${max} UTF-8 bytes`); } return trimmed; } function connectorActionEvidenceName( resolved: Exclude, ): string { return resolved.entry?.actionName ?? ("actionName" in resolved ? resolved.actionName : "*"); } function connectorActionAuditMetadata( row: typeof schema.connectorActionRequests.$inferSelect, extra: Record = {}, ): Record { return { requestId: row.id, sessionId: row.sessionId, turnId: row.turnId, attemptId: row.creationAttemptId, creationExecutionGeneration: row.creationExecutionGeneration, executionAttemptId: row.executionAttemptId, executionAttemptGeneration: row.executionAttemptGeneration, approvalId: row.approvalId, initiatorKind: row.initiatorKind, initiatorSubjectId: row.initiatorSubjectId, connectionId: row.connectionId, connectionVersion: row.connectionVersion, serverId: row.serverId, toolName: row.toolName, actionName: row.actionName, policyId: row.policyId, policyVersion: row.policyVersion, policySource: row.policySource, policyDecision: row.policyDecision, actionFingerprint: row.actionFingerprint, ...extra, }; } async function insertConnectorActionAudit( db: Database, input: { row: typeof schema.connectorActionRequests.$inferSelect; action: string; subjectId: string; extra?: Record; }, ): Promise { await db.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.row.accountId, workspaceId: input.row.workspaceId, subjectId: input.subjectId, action: input.action, targetType: "connector_action_request", targetId: input.row.id, metadata: connectorActionAuditMetadata(input.row, input.extra), }, "metadata", "metadataCodecVersion", ), ); } function normalizedConnectorActionInvocation( identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation, ): { approvalId: string; connectionId: string | null; serverId: string; toolName: string; policyActionSelector: string; arguments: unknown; reviewContext?: import("@opengeni/contracts").ToolReviewContext; approvalMode: "connector" | "session_mcp" | "connector_write"; defaultDecision?: "allow" | "ask"; } { const approvalId = boundedConnectorActionText( invocation.approvalId, "connector approval id", CONNECTOR_ACTION_APPROVAL_ID_MAX, ); const serverId = boundedConnectorActionText( invocation.serverId, "connector server id", CONNECTOR_ACTION_SERVER_ID_MAX, ); const toolName = boundedConnectorActionText( invocation.toolName, "connector tool name", CONNECTOR_ACTION_NAME_MAX, ); const policyActionSelector = invocation.actionName === undefined ? toolName : boundedConnectorActionText( invocation.actionName, "connector action name", CONNECTOR_ACTION_NAME_MAX, ); const connectionId = invocation.connectionId?.trim() ? boundedConnectorActionText( invocation.connectionId, "connector connection id", CONNECTOR_ACTION_CONNECTION_ID_MAX, ) : null; const approvalMode = invocation.approvalMode ?? "connector"; if ( approvalMode !== "connector" && approvalMode !== "session_mcp" && approvalMode !== "connector_write" ) { throw new Error("connector approval mode is unsupported"); } if (approvalMode === "session_mcp" && !connectionId?.startsWith("session-mcp:")) { throw new Error("session MCP approval is missing its synthetic connection identity"); } return { approvalId, connectionId, serverId, toolName, policyActionSelector, arguments: invocation.arguments, ...(invocation.reviewContext ? { reviewContext: ToolReviewContext.parse(invocation.reviewContext) } : {}), approvalMode, ...(invocation.defaultDecision !== undefined ? { defaultDecision: invocation.defaultDecision } : approvalMode === "session_mcp" ? { defaultDecision: "ask" as const } : approvalMode === "connector_write" ? { defaultDecision: "allow" as const } : {}), }; } function durableConnectorActionInvocation( identity: ConnectorActionAttemptIdentity, invocation: ReturnType & { connectionId: string; }, resolved: Exclude, ): { approvalId: string; connectionId: string; serverId: string; toolName: string; actionName: string; actionFingerprint: string; reviewArguments: string; reviewContext?: import("@opengeni/contracts").ToolReviewContext; } { const actionName = connectorActionEvidenceName(resolved); const reviewArguments = JSON.stringify(invocation.arguments) ?? "null"; const reviewContext = invocation.reviewContext ? ToolReviewContext.parse(invocation.reviewContext) : undefined; if ( Buffer.byteLength(reviewArguments, "utf8") > 4 * 1024 * 1024 || (reviewContext && Buffer.byteLength(JSON.stringify(reviewContext), "utf8") > 4 * 1024 * 1024) ) { recordToolApproval("size_rejected"); throw new Error("Tool review exceeds the supported size. Prepare smaller independent actions."); } return { approvalId: invocation.approvalId, connectionId: invocation.connectionId, serverId: invocation.serverId, toolName: invocation.toolName, actionName, reviewArguments, ...(reviewContext ? { reviewContext } : {}), actionFingerprint: connectorActionFingerprint({ workspaceId: identity.workspaceId, connectionId: invocation.connectionId, serverId: invocation.serverId, toolName: invocation.toolName, actionName, arguments: invocation.arguments, }), }; } async function connectorActionAttemptSnapshot( db: Database, identity: ConnectorActionAttemptIdentity, ): Promise { const [attempt] = await db .select({ accountId: schema.sessionTurnAttempts.accountId, sessionId: schema.sessionTurnAttempts.sessionId, turnId: schema.sessionTurnAttempts.turnId, executionGeneration: schema.sessionTurnAttempts.executionGeneration, state: schema.sessionTurnAttempts.state, connectorActionPolicies: schema.sessionTurnAttempts.connectorActionPolicies, mcpAccountBindings: schema.sessionTurns.mcpAccountBindings, }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.id, schema.sessionTurnAttempts.turnId), eq(schema.sessionTurns.workspaceId, schema.sessionTurnAttempts.workspaceId), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, identity.workspaceId), eq(schema.sessionTurnAttempts.id, identity.attemptId), ), ) .limit(1); if ( !attempt || attempt.accountId !== identity.accountId || attempt.sessionId !== identity.sessionId || attempt.turnId !== identity.turnId || attempt.executionGeneration !== identity.executionGeneration || !["claimed", "running"].includes(attempt.state) ) { throw new Error(`connector action attempt ownership is unavailable: ${identity.attemptId}`); } if (attempt.connectorActionPolicies.length > CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX) { throw new Error("connector action policy snapshot exceeds the runtime bound"); } return connectorActionPoliciesForAccountRoutes( attempt.connectorActionPolicies, attempt.mcpAccountBindings, ); } function connectorActionRequestMatches( row: typeof schema.connectorActionRequests.$inferSelect, input: { identity: ConnectorActionAttemptIdentity; invocation: ReturnType; resolved: Exclude; }, ): boolean { const entry = input.resolved.entry; return ( row.accountId === input.identity.accountId && row.workspaceId === input.identity.workspaceId && row.sessionId === input.identity.sessionId && row.turnId === input.identity.turnId && row.creationAttemptId === input.identity.attemptId && row.creationExecutionGeneration === input.identity.executionGeneration && row.approvalId === input.invocation.approvalId && row.initiatorKind === input.identity.initiator.kind && row.initiatorSubjectId === input.identity.initiator.subjectId && row.connectionId === input.invocation.connectionId && row.serverId === input.invocation.serverId && row.toolName === input.invocation.toolName && row.actionName === input.invocation.actionName && row.policyId === (entry?.id ?? null) && row.policyVersion === (entry?.version ?? null) && row.policySource === input.resolved.source && row.policyDecision === connectorActionPolicyDecision(input.resolved) && row.actionFingerprint === input.invocation.actionFingerprint ); } function connectorActionRequestMatchesLogicalCall( row: typeof schema.connectorActionRequests.$inferSelect, identity: ConnectorActionAttemptIdentity, invocation: ReturnType, ): boolean { if (!invocation.connectionId) return false; return ( row.accountId === identity.accountId && row.workspaceId === identity.workspaceId && row.sessionId === identity.sessionId && row.turnId === identity.turnId && row.approvalId === invocation.approvalId && row.initiatorKind === identity.initiator.kind && row.initiatorSubjectId === identity.initiator.subjectId && row.connectionId === invocation.connectionId && row.serverId === invocation.serverId && row.toolName === invocation.toolName && row.actionFingerprint === connectorActionFingerprint({ workspaceId: identity.workspaceId, connectionId: invocation.connectionId, serverId: invocation.serverId, toolName: invocation.toolName, actionName: row.actionName, arguments: invocation.arguments, }) ); } async function insertConnectorActionRequest( db: Database, input: { identity: ConnectorActionAttemptIdentity; invocation: ReturnType; resolved: Exclude; status: "pending" | "blocked" | "executing"; }, ): Promise<{ row: typeof schema.connectorActionRequests.$inferSelect; inserted: boolean; }> { const entry = input.resolved.entry; const [inserted] = await db .insert(schema.connectorActionRequests) .values({ accountId: input.identity.accountId, workspaceId: input.identity.workspaceId, sessionId: input.identity.sessionId, turnId: input.identity.turnId, creationAttemptId: input.identity.attemptId, creationExecutionGeneration: input.identity.executionGeneration, approvalId: input.invocation.approvalId, initiatorKind: input.identity.initiator.kind, initiatorSubjectId: input.identity.initiator.subjectId, connectionId: input.invocation.connectionId!, serverId: input.invocation.serverId, toolName: input.invocation.toolName, actionName: input.invocation.actionName, policyId: entry?.id ?? null, policyVersion: entry?.version ?? null, policySource: input.resolved.source, policyDecision: connectorActionPolicyDecision(input.resolved), agentRule: input.resolved.source === "default" ? (input.resolved.agentRule ?? null) : null, actionFingerprint: input.invocation.actionFingerprint!, ...(input.status === "pending" ? { reviewArguments: input.invocation.reviewArguments, reviewContext: input.invocation.reviewContext ?? null, } : {}), status: input.status, ...(input.status === "executing" ? { executionAttemptId: input.identity.attemptId, executionAttemptGeneration: input.identity.executionGeneration, executionStartedAt: new Date(), } : {}), }) .onConflictDoNothing({ target: [ schema.connectorActionRequests.workspaceId, schema.connectorActionRequests.sessionId, schema.connectorActionRequests.turnId, schema.connectorActionRequests.approvalId, ], }) .returning(); if (inserted) return { row: inserted, inserted: true }; const [existing] = await db .select() .from(schema.connectorActionRequests) .where( and( eq(schema.connectorActionRequests.workspaceId, input.identity.workspaceId), eq(schema.connectorActionRequests.sessionId, input.identity.sessionId), eq(schema.connectorActionRequests.turnId, input.identity.turnId), eq(schema.connectorActionRequests.approvalId, input.invocation.approvalId), ), ) .for("update") .limit(1); if (!existing || !connectorActionRequestMatches(existing, input)) { throw new Error("connector action approval id conflicts with different immutable inputs"); } return { row: existing, inserted: false }; } export type ConnectorActionPolicyWrite = { accountId: string; workspaceId: string; subjectId: string; connectionId: string; serverId: string; toolName: string; actionName: string; policy: ConnectorActionPolicyDecision; }; type NormalizedConnectorActionPolicyWrite = ConnectorActionPolicyWrite & { subjectId: string; }; function normalizeConnectorActionPolicyWrite( input: ConnectorActionPolicyWrite, ): NormalizedConnectorActionPolicyWrite { return { ...input, subjectId: boundedConnectorActionText(input.subjectId, "policy actor", 1024), connectionId: boundedConnectorActionText( input.connectionId, "connector connection id", CONNECTOR_ACTION_CONNECTION_ID_MAX, ), serverId: boundedConnectorActionText( input.serverId, "connector server id", CONNECTOR_ACTION_SERVER_ID_MAX, ), toolName: boundedConnectorActionText( input.toolName, "connector tool name", CONNECTOR_ACTION_NAME_MAX, ), actionName: boundedConnectorActionText( input.actionName, "connector action name", CONNECTOR_ACTION_NAME_MAX, ), }; } function connectorActionPolicyScopeKey(input: ConnectorActionPolicyWrite): string { return [input.connectionId, input.serverId, input.toolName, input.actionName].join("\0"); } async function upsertConnectorActionPolicyInTransaction( db: Database, input: NormalizedConnectorActionPolicyWrite, ): Promise<{ policy: typeof schema.connectorActionPolicies.$inferSelect; changed: boolean; }> { const [existing] = await db .select() .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.connectionId), eq(schema.connectorActionPolicies.serverId, input.serverId), eq(schema.connectorActionPolicies.toolName, input.toolName), eq(schema.connectorActionPolicies.actionName, input.actionName), ), ) .for("update") .limit(1); if (existing?.policy === input.policy) return { policy: existing, changed: false }; const now = new Date(); const [row] = existing ? await db .update(schema.connectorActionPolicies) .set({ policy: input.policy, version: existing.version + 1, updatedBySubjectId: input.subjectId, updatedAt: now, }) .where(eq(schema.connectorActionPolicies.id, existing.id)) .returning() : await db .insert(schema.connectorActionPolicies) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId: input.connectionId, serverId: input.serverId, toolName: input.toolName, actionName: input.actionName, policy: input.policy, createdBySubjectId: input.subjectId, updatedBySubjectId: input.subjectId, }) .returning(); if (!row) throw new Error("Failed to persist connector action policy"); await db.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "connector.action.policy_changed", targetType: "connector_action_policy", targetId: row.id, metadata: { connectionId: row.connectionId, serverId: row.serverId, toolName: row.toolName, actionName: row.actionName, policy: row.policy, version: row.version, previousPolicy: existing?.policy ?? null, previousVersion: existing?.version ?? null, }, }, "metadata", "metadataCodecVersion", ), ); return { policy: row, changed: true }; } export async function upsertConnectorActionPolicies( db: Database, inputs: readonly ConnectorActionPolicyWrite[], ): Promise< Array<{ policy: typeof schema.connectorActionPolicies.$inferSelect; changed: boolean; }> > { if (inputs.length === 0 || inputs.length > 128) { throw new Error("connector action policy batch must contain between 1 and 128 entries"); } const normalized = inputs.map(normalizeConnectorActionPolicyWrite); const first = normalized[0]!; if ( normalized.some( (input) => input.accountId !== first.accountId || input.workspaceId !== first.workspaceId || input.subjectId !== first.subjectId, ) ) { throw new Error("connector action policy batch must share one workspace and actor"); } const sorted = [...normalized].sort((left, right) => connectorActionPolicyScopeKey(left).localeCompare(connectorActionPolicyScopeKey(right)), ); if ( sorted.some( (input, index) => index > 0 && connectorActionPolicyScopeKey(input) === connectorActionPolicyScopeKey(sorted[index - 1]!), ) ) { throw new Error("connector action policy batch contains duplicate scopes"); } return await withRlsContext( db, { accountId: first.accountId, workspaceId: first.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await assertWorkspaceAccountPairInScope(tx, first.accountId, first.workspaceId); const results = []; for (const input of sorted) { results.push( await upsertConnectorActionPolicyInTransaction(tx as unknown as Database, input), ); } return results; }), ); } export async function upsertConnectorActionPolicy( db: Database, input: ConnectorActionPolicyWrite, ): Promise<{ policy: typeof schema.connectorActionPolicies.$inferSelect; changed: boolean; }> { return (await upsertConnectorActionPolicies(db, [input]))[0]!; } export async function listConnectorActionPolicies( db: Database, input: { accountId: string; workspaceId: string; connectionIds: readonly string[]; }, ): Promise { if (input.connectionIds.length === 0) return []; if (input.connectionIds.length > 128) { throw new Error("connector action policy read exceeds 128 connections"); } const connectionIds = [ ...new Set( input.connectionIds.map((connectionId) => boundedConnectorActionText( connectionId, "connector connection id", CONNECTOR_ACTION_CONNECTION_ID_MAX, ), ), ), ]; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await assertWorkspaceAccountPairInScope(scopedDb, input.accountId, input.workspaceId); return await scopedDb .select({ id: schema.connectorActionPolicies.id, connectionId: schema.connectorActionPolicies.connectionId, serverId: schema.connectorActionPolicies.serverId, toolName: schema.connectorActionPolicies.toolName, actionName: schema.connectorActionPolicies.actionName, policy: schema.connectorActionPolicies.policy, version: schema.connectorActionPolicies.version, }) .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.accountId, input.accountId), eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), inArray(schema.connectorActionPolicies.connectionId, connectionIds), ), ) .orderBy( asc(schema.connectorActionPolicies.connectionId), asc(schema.connectorActionPolicies.serverId), asc(schema.connectorActionPolicies.toolName), asc(schema.connectorActionPolicies.actionName), asc(schema.connectorActionPolicies.id), ); }, ); } const connectorActionPolicySnapshotColumns = { id: schema.connectorActionPolicies.id, connectionId: schema.connectorActionPolicies.connectionId, serverId: schema.connectorActionPolicies.serverId, toolName: schema.connectorActionPolicies.toolName, actionName: schema.connectorActionPolicies.actionName, policy: schema.connectorActionPolicies.policy, version: schema.connectorActionPolicies.version, }; /** * The tool choices a turn starts with. A workspace login's choices are that * workspace's. A personal login's choices belong to the login: they are stored * once, in the workspace it was connected from, and follow it to every * workspace where its owner's turn uses it. A copy left in this workspace is * ignored. A login whose choices don't fit the snapshot bound is left out * whole, so its recommendations apply; never part of its rules. The * workspace's own rows keep database order and followed logins come after * them, so exact-attempt re-entry compares equal snapshots. */ export async function connectorActionPolicySnapshotForTurn( db: Database, input: { accountId: string; workspaceId: string; bindings: readonly McpConnectionAccountBinding[] | null; }, ): Promise { const followed = new Map>(); for (const binding of input.bindings ?? []) { if (binding.subjectScope !== "subject" || binding.originWorkspaceId === input.workspaceId) continue; const ids = followed.get(binding.originWorkspaceId) ?? new Set(); ids.add(binding.connectionId); followed.set(binding.originWorkspaceId, ids); } const followedIds = new Set([...followed.values()].flatMap((ids) => [...ids])); const stored = await db .select(connectorActionPolicySnapshotColumns) .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.accountId, input.accountId), eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), ), ) .orderBy( asc(schema.connectorActionPolicies.connectionId), asc(schema.connectorActionPolicies.serverId), asc(schema.connectorActionPolicies.toolName), asc(schema.connectorActionPolicies.actionName), asc(schema.connectorActionPolicies.id), ) .limit(CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX + 1); if (stored.length > CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX) { throw new Error("Connector action policy snapshot exceeds the 2048-row bound"); } const snapshot: ConnectorActionPolicySnapshotEntry[] = stored.filter( (row) => !followedIds.has(row.connectionId), ); for (const [originWorkspaceId, ids] of [...followed].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0, )) { // Read the login's home under that workspace's tenant scope, without the // session-tenancy fence: this is a read inside the claim transaction. const rows = await withRlsContext( db, { accountId: input.accountId, workspaceId: originWorkspaceId }, async (scoped) => await scoped .select(connectorActionPolicySnapshotColumns) .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.accountId, input.accountId), eq(schema.connectorActionPolicies.workspaceId, originWorkspaceId), inArray(schema.connectorActionPolicies.connectionId, [...ids].sort()), ), ) .orderBy( asc(schema.connectorActionPolicies.connectionId), asc(schema.connectorActionPolicies.serverId), asc(schema.connectorActionPolicies.toolName), asc(schema.connectorActionPolicies.actionName), asc(schema.connectorActionPolicies.id), ) .limit(CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX + 1), undefined, "none", ); for (const connectionId of [...ids].sort()) { const group = rows.filter((row) => row.connectionId === connectionId); if (snapshot.length + group.length <= CONNECTOR_ACTION_POLICY_SNAPSHOT_MAX) snapshot.push(...group); } } return snapshot; } /** * Install a risk-appropriate connector default without overwriting an explicit * user choice that already exists for the same immutable connector action. */ export async function ensureConnectorActionPolicyDefault( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; connectionId: string; serverId: string; toolName: string; actionName: string; policy: ConnectorActionPolicyDecision; }, ): Promise<{ policy: typeof schema.connectorActionPolicies.$inferSelect; changed: boolean; }> { const scope = { connectionId: boundedConnectorActionText( input.connectionId, "connector connection id", CONNECTOR_ACTION_CONNECTION_ID_MAX, ), serverId: boundedConnectorActionText( input.serverId, "connector server id", CONNECTOR_ACTION_SERVER_ID_MAX, ), toolName: boundedConnectorActionText( input.toolName, "connector tool name", CONNECTOR_ACTION_NAME_MAX, ), actionName: boundedConnectorActionText( input.actionName, "connector action name", CONNECTOR_ACTION_NAME_MAX, ), }; const subjectId = boundedConnectorActionText(input.subjectId, "policy actor", 1024); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await assertWorkspaceAccountPairInScope(tx, input.accountId, input.workspaceId); const [inserted] = await tx .insert(schema.connectorActionPolicies) .values({ accountId: input.accountId, workspaceId: input.workspaceId, ...scope, policy: input.policy, createdBySubjectId: subjectId, updatedBySubjectId: subjectId, }) .onConflictDoNothing({ target: [ schema.connectorActionPolicies.workspaceId, schema.connectorActionPolicies.connectionId, schema.connectorActionPolicies.serverId, schema.connectorActionPolicies.toolName, schema.connectorActionPolicies.actionName, ], }) .returning(); if (!inserted) { const [existing] = await tx .select() .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, scope.connectionId), eq(schema.connectorActionPolicies.serverId, scope.serverId), eq(schema.connectorActionPolicies.toolName, scope.toolName), eq(schema.connectorActionPolicies.actionName, scope.actionName), ), ) .limit(1); if (!existing) throw new Error("Failed to reconcile connector action policy default"); return { policy: existing, changed: false }; } await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId, action: "connector.action.policy_changed", targetType: "connector_action_policy", targetId: inserted.id, metadata: { connectionId: inserted.connectionId, serverId: inserted.serverId, toolName: inserted.toolName, actionName: inserted.actionName, policy: inserted.policy, version: inserted.version, previousPolicy: null, previousVersion: null, source: "connector_default", }, }, "metadata", "metadataCodecVersion", ), ); return { policy: inserted, changed: true }; }), ); } /** An already prepared action keeps its original choice across resumed attempts. */ async function priorConnectorActionPreparation( db: Database, identity: ConnectorActionAttemptIdentity, invocation: ReturnType, ): Promise { const [row] = await db .select() .from(schema.connectorActionRequests) .where( and( eq(schema.connectorActionRequests.workspaceId, identity.workspaceId), eq(schema.connectorActionRequests.sessionId, identity.sessionId), eq(schema.connectorActionRequests.turnId, identity.turnId), eq(schema.connectorActionRequests.approvalId, invocation.approvalId), ), ) .limit(1); if (!row) return null; if (!connectorActionRequestMatchesLogicalCall(row, identity, invocation)) { throw new Error("connector action approval id conflicts with different immutable inputs"); } return { managed: true, decision: row.policyDecision, approvalStatus: row.status, requestId: row.id, actionFingerprint: row.actionFingerprint, ...(row.agentRule ? { agentRule: row.agentRule } : {}), }; } /** Exact rows of one attempt whose canonical write prefix a ledger write takes. */ type ConnectorActionLedgerPrefix = (scope: { sessionId: string; turnId: string; attemptId: string; }) => Promise; /** * One idempotent connector-ledger transaction. Before its first ledger write it * takes the canonical session event-write prefix (workspace KEY SHARE, session, * event cursor, exact turn, exact attempt): a ledger row's attempt FK otherwise * KEY SHAREs the attempt outside that order while parallel tool calls of the * same attempt append events and settle receipts. Reads before the prefix take * no row locks. The whole transaction retries on 40P01/40001; it never contains * a provider effect, so a retry cannot replay one. */ async function runConnectorActionLedgerTransaction( db: Database, input: { accountId: string; workspaceId: string; stage: string; correlationId: string }, fn: (tx: Database, lockPrefix: ConnectorActionLedgerPrefix) => Promise, ): Promise { return await retryRlsPersistence( db, { accountId: input.accountId, workspaceId: input.workspaceId }, { stage: input.stage, correlationId: input.correlationId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; let locked: string | null = null; return await fn(tx, async (scope) => { const key = `${scope.sessionId}:${scope.turnId}:${scope.attemptId}`; if (locked === key) return; if (locked) throw new Error("connector ledger transaction spans two attempts"); await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "none", sessionLock: "key_share", sessionIds: [scope.sessionId], turnIds: [scope.turnId], attemptIds: [scope.attemptId], }); locked = key; }); }), ); } export async function prepareConnectorActionApproval( db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation, ): Promise { const normalized = normalizedConnectorActionInvocation(identity, invocation); if (!normalized.connectionId) { return { managed: false, decision: "unmanaged" }; } return await runConnectorActionLedgerTransaction( db, { accountId: identity.accountId, workspaceId: identity.workspaceId, stage: "connector_action_prepare", correlationId: normalized.approvalId, }, async (tx, lockPrefix) => { const snapshot = await connectorActionAttemptSnapshot(tx, identity); const prior = await priorConnectorActionPreparation(tx, identity, normalized); if (prior) return prior; const resolved = withMinimumConnectorDecision( resolveConnectorActionPolicy(snapshot, { connectionId: normalized.connectionId!, serverId: normalized.serverId, toolName: normalized.toolName, actionName: normalized.policyActionSelector, ...(normalized.defaultDecision !== undefined ? { defaultDecision: normalized.defaultDecision } : {}), }), invocation.minimumDecision, normalized.toolName, invocation.minimumDecisionBy, ); if (!resolved.managed) return { managed: false, decision: "unmanaged" } as const; const durable = durableConnectorActionInvocation( identity, { ...normalized, connectionId: normalized.connectionId! }, resolved, ); const decision = connectorActionPolicyDecision(resolved); recordToolApproval(decision, resolved.source); if (decision === "allow") { return { managed: true, decision, actionFingerprint: durable.actionFingerprint, } as const; } await lockPrefix(identity); const { row, inserted } = await insertConnectorActionRequest(tx, { identity, invocation: durable, resolved, status: decision === "ask" ? "pending" : "blocked", }); if (inserted) { await insertConnectorActionAudit(tx, { row, action: decision === "ask" ? "connector.action.approval_requested" : "connector.action.blocked", subjectId: identity.initiator.subjectId, extra: { outcome: decision }, }); } return { managed: true, decision, approvalStatus: row.status, requestId: row.id, actionFingerprint: row.actionFingerprint, ...(row.agentRule ? { agentRule: row.agentRule } : {}), } as const; }, ); } /** Resolve the frozen connector policy without creating approval or audit state. */ export async function previewConnectorActionApproval( db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation, ): Promise { const normalized = normalizedConnectorActionInvocation(identity, invocation); if (!normalized.connectionId) { return { managed: false, decision: "unmanaged" }; } return await withRlsContext( db, { accountId: identity.accountId, workspaceId: identity.workspaceId }, async (scopedDb) => { const snapshot = await connectorActionAttemptSnapshot(scopedDb, identity); const prior = await priorConnectorActionPreparation(scopedDb, identity, normalized); if (prior) return prior; const resolved = withMinimumConnectorDecision( resolveConnectorActionPolicy(snapshot, { connectionId: normalized.connectionId!, serverId: normalized.serverId, toolName: normalized.toolName, actionName: normalized.policyActionSelector, ...(normalized.defaultDecision !== undefined ? { defaultDecision: normalized.defaultDecision } : {}), }), invocation.minimumDecision, normalized.toolName, invocation.minimumDecisionBy, ); if (!resolved.managed) return { managed: false, decision: "unmanaged" } as const; const durable = durableConnectorActionInvocation( identity, { ...normalized, connectionId: normalized.connectionId! }, resolved, ); return { managed: true, decision: connectorActionPolicyDecision(resolved), actionFingerprint: durable.actionFingerprint, ...(resolved.source === "default" && resolved.agentRule ? { agentRule: resolved.agentRule } : {}), } as const; }, ); } /** * The decision this attempt's frozen tool permissions give one connector tool * on one connection, as a call of it would resolve: an explicit choice, else * `defaultDecision`. Reads only the snapshot; creates no request or audit row. * Lets one tool follow the choice a person made for another, such as a bot * send following the person's own Slack send permission. */ export async function resolveAttemptConnectorToolDecision( db: Database, identity: ConnectorActionAttemptIdentity, input: { connectionId: string; serverId: string; toolName: string; defaultDecision: "allow" | "ask"; /** Decide from the resolved policy instead of its plain decision. */ decide?: (resolved: ResolvedConnectorActionPolicy) => "allow" | "ask" | "block"; }, ): Promise<"allow" | "ask" | "block"> { const { decide, ...policyInput } = input; return await withRlsContext( db, { accountId: identity.accountId, workspaceId: identity.workspaceId }, async (scopedDb) => { const snapshot = await connectorActionAttemptSnapshot(scopedDb, identity); const resolved = resolveConnectorActionPolicy(snapshot, { ...policyInput, actionName: policyInput.toolName, }); if (decide) return decide(resolved); return resolved.managed ? connectorActionPolicyDecision(resolved) : input.defaultDecision; }, ); } export async function beginConnectorActionExecution( db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation, ): Promise { const normalized = normalizedConnectorActionInvocation(identity, invocation); if (!normalized.connectionId) { return { allowed: true, managed: false }; } const resolveFrom = (snapshot: ConnectorActionPolicySnapshotEntry[]) => { const resolved = resolveConnectorActionPolicy(snapshot, { connectionId: normalized.connectionId!, serverId: normalized.serverId, toolName: normalized.toolName, actionName: normalized.policyActionSelector, ...(normalized.defaultDecision !== undefined ? { defaultDecision: normalized.defaultDecision } : {}), }); return withMinimumConnectorDecision( resolved, invocation.minimumDecision, normalized.toolName, invocation.minimumDecisionBy, ); }; return await runConnectorActionLedgerTransaction( db, { accountId: identity.accountId, workspaceId: identity.workspaceId, stage: "connector_action_begin", correlationId: normalized.approvalId, }, async (tx, lockPrefix) => { const snapshot = await connectorActionAttemptSnapshot(tx, identity); const existingRequest = () => tx .select() .from(schema.connectorActionRequests) .where( and( eq(schema.connectorActionRequests.workspaceId, identity.workspaceId), eq(schema.connectorActionRequests.sessionId, identity.sessionId), eq(schema.connectorActionRequests.turnId, identity.turnId), eq(schema.connectorActionRequests.approvalId, normalized.approvalId), ), ); const [unlocked] = await existingRequest().limit(1); if (!unlocked) { const resolved = resolveFrom(snapshot); if (!resolved.managed) return { allowed: true, managed: false } as const; // A recommended Allow with no explicit rule is ordinary tool use, not // a reviewed action: no ledger row, audit pair, or row lock. Every Ask, // Block, explicit rule, and connector write keeps its execute-once record. if ( resolved.source === "default" && connectorActionPolicyDecision(resolved) === "allow" && normalized.approvalMode === "connector" ) { return { allowed: true, managed: false } as const; } } await lockPrefix(identity); const [existing] = await existingRequest().for("update").limit(1); if (existing && !connectorActionRequestMatchesLogicalCall(existing, identity, normalized)) { throw new Error("connector action approval id conflicts with different immutable inputs"); } let row = existing; let inserted = false; if (!row) { const resolved = resolveFrom(snapshot); if (!resolved.managed) return { allowed: true, managed: false } as const; const decision = connectorActionPolicyDecision(resolved); const durable = durableConnectorActionInvocation( identity, { ...normalized, connectionId: normalized.connectionId! }, resolved, ); const created = await insertConnectorActionRequest(tx, { identity, invocation: durable, resolved, status: decision === "ask" ? "pending" : decision === "block" ? "blocked" : "executing", }); row = created.row; inserted = created.inserted; if (inserted) { await insertConnectorActionAudit(tx, { row, action: decision === "ask" ? "connector.action.approval_requested" : decision === "block" ? "connector.action.blocked" : "connector.action.execution_started", subjectId: identity.initiator.subjectId, extra: { outcome: decision === "allow" ? "started" : decision }, }); } } if (row.status === "approved") { const [executing] = await tx .update(schema.connectorActionRequests) .set({ status: "executing", executionAttemptId: identity.attemptId, executionAttemptGeneration: identity.executionGeneration, executionStartedAt: new Date(), updatedAt: new Date(), }) .where(eq(schema.connectorActionRequests.id, row.id)) .returning(); if (!executing) throw new Error("Approved connector action request disappeared"); row = executing; await insertConnectorActionAudit(tx, { row, action: "connector.action.execution_started", subjectId: identity.initiator.subjectId, extra: { outcome: "started" }, }); return { allowed: true, managed: true, requestId: row.id, actionFingerprint: row.actionFingerprint, } as const; } if (row.status === "rejected" && row.inputRound > 0 && invocation.deliversDecline) { // The person declined the provider's question: the call runs once // more under that rejection, only to tell the provider so. const [executing] = await tx .update(schema.connectorActionRequests) .set({ status: "executing", executionAttemptId: identity.attemptId, executionAttemptGeneration: identity.executionGeneration, executionStartedAt: new Date(), updatedAt: new Date(), }) .where(eq(schema.connectorActionRequests.id, row.id)) .returning(); if (!executing) throw new Error("Declined connector action request disappeared"); row = executing; await insertConnectorActionAudit(tx, { row, action: "connector.action.execution_started", subjectId: identity.initiator.subjectId, extra: { outcome: "decline_delivery", inputRound: row.inputRound }, }); return { allowed: true, managed: true, requestId: row.id, actionFingerprint: row.actionFingerprint, } as const; } if (row.status === "executing") { if (inserted) { return { allowed: true, managed: true, requestId: row.id, actionFingerprint: row.actionFingerprint, } as const; } const [uncertain] = await tx .update(schema.connectorActionRequests) .set({ status: "uncertain", outcome: "retry_after_execution_started", executionFinishedAt: new Date(), updatedAt: new Date(), }) .where(eq(schema.connectorActionRequests.id, row.id)) .returning(); if (!uncertain) throw new Error("Executing connector action request disappeared"); await insertConnectorActionAudit(tx, { row: uncertain, action: "connector.action.execution_uncertain", subjectId: identity.initiator.subjectId, extra: { outcome: "retry_denied" }, }); return { allowed: false, managed: true, reason: "uncertain_retry", requestId: uncertain.id, actionFingerprint: uncertain.actionFingerprint, } as const; } const reason = row.status === "pending" ? "approval_required" : row.status === "rejected" ? "rejected" : row.status === "blocked" ? "blocked" : row.status === "failed" ? "not_executed" : "already_executed"; return { allowed: false, managed: true, reason, requestId: row.id, actionFingerprint: row.actionFingerprint, ...(reason === "blocked" && row.agentRule ? { agentRule: row.agentRule } : {}), } as const; }, ); } export async function completeConnectorActionExecution( db: Database, input: { accountId: string; workspaceId: string; requestId: string; attemptId: string; /** * `input_required`: the provider stopped before finishing to ask the * person a question (MCP elicitation). The request opens its next input * round as an undecided `pending` request, so the answer is that round's * approval decision and the retry executes once under it. */ outcome: "completed" | "uncertain" | "not_executed" | "input_required"; }, ): Promise { await runConnectorActionLedgerTransaction( db, { accountId: input.accountId, workspaceId: input.workspaceId, stage: "connector_action_complete", correlationId: input.requestId, }, async (tx, lockPrefix) => { const request = () => tx .select() .from(schema.connectorActionRequests) .where( and( eq(schema.connectorActionRequests.workspaceId, input.workspaceId), eq(schema.connectorActionRequests.id, input.requestId), ), ); const [located] = await request().limit(1); // Asking the person releases the executing attempt, so a repeated // settlement of the same question finds an undecided round instead. const settledQuestion = (row: typeof located) => input.outcome === "input_required" && row?.status === "pending" && row.inputRound > 0 && row.executionAttemptId === null; if ( !located || (located.executionAttemptId !== input.attemptId && !settledQuestion(located)) ) { throw new Error("Connector action request not found for completion"); } // Settlement is not admission: it takes the canonical prefix but never the // Pause/Steer write fence, so an interrupted attempt still settles. await lockPrefix({ sessionId: located.sessionId, turnId: located.turnId, attemptId: input.attemptId, }); const [existing] = await request().for("update").limit(1); if (!existing) throw new Error("Connector action request not found for completion"); if (settledQuestion(existing)) return; if (existing.executionAttemptId !== input.attemptId) { throw new Error("Connector action request not found for completion"); } if (input.outcome === "input_required") { if (existing.status !== "executing") { throw new Error(`Connector action request cannot ask from ${existing.status}`); } const [row] = await tx .update(schema.connectorActionRequests) .set({ status: "pending", inputRound: existing.inputRound + 1, // The new question is decided and executed afresh; earlier // rounds' decisions stay in the audit log. decision: null, decisionBySubjectId: null, decisionByKind: null, decisionBySignedInPerson: false, decisionEventId: null, decidedAt: null, executionAttemptId: null, executionAttemptGeneration: null, executionStartedAt: null, updatedAt: new Date(), }) .where(eq(schema.connectorActionRequests.id, existing.id)) .returning(); if (!row) throw new Error("Connector action request disappeared while asking"); await insertConnectorActionAudit(tx, { row, action: "connector.action.approval_requested", subjectId: row.initiatorSubjectId, extra: { outcome: "input_required", inputRound: row.inputRound }, }); return; } // A not-executed completion is a terminal failure whose provider // request never happened; it keeps the existing status vocabulary. // Reaching the terminal status is idempotent even when a concurrent // begin already settled the row with a different uncertain outcome // (retry_after_execution_started). const terminalStatus = input.outcome === "not_executed" ? "failed" : input.outcome; if (existing.status === terminalStatus) return; if (existing.status !== "executing") { throw new Error(`Connector action request cannot complete from ${existing.status}`); } const [row] = await tx .update(schema.connectorActionRequests) .set({ status: terminalStatus, outcome: input.outcome, executionFinishedAt: new Date(), updatedAt: new Date(), }) .where(eq(schema.connectorActionRequests.id, existing.id)) .returning(); if (!row) throw new Error("Connector action request disappeared during completion"); await insertConnectorActionAudit(tx, { row, action: input.outcome === "completed" ? "connector.action.execution_completed" : input.outcome === "not_executed" ? "connector.action.execution_not_executed" : "connector.action.execution_uncertain", subjectId: row.initiatorSubjectId, extra: { outcome: input.outcome }, }); }, ); } type DeploymentDepthPolicy = NestedAgentDepthDeploymentPolicy; /** Read the persisted deployment fallback; process configuration is not policy authority. */ export async function getNestedAgentDepthDeploymentPolicy( db: Database, ): Promise { const [row] = await db .select({ maxNestedAgentDepth: schema.nestedAgentDepthConfiguration.maxNestedAgentDepth, policySource: schema.nestedAgentDepthConfiguration.policySource, }) .from(schema.nestedAgentDepthConfiguration) .where(eq(schema.nestedAgentDepthConfiguration.singleton, true)) .limit(1); if (!row) throw new Error("Nested-agent deployment policy is not configured"); return { maxNestedAgentDepth: row.maxNestedAgentDepth, policySource: row.policySource, }; } type AgentSessionCreationActor = Extract; /** A caller-preallocated session UUID is already owned by another session. */ export class SessionIdConflictError extends Error { constructor(readonly sessionId: string) { super(`Session id is already in use: ${sessionId}`); this.name = "SessionIdConflictError"; } } export class SessionCreateIdempotencyConflictError extends Error { constructor() { super("Session create idempotency key was reused with a different request"); this.name = "SessionCreateIdempotencyConflictError"; } } /** An idempotent INSERT lost, but RLS exposes neither its winner nor a denial. * Never probe outside the caller's visibility merely to explain the conflict. */ export class SessionCreateIdempotencyUnavailableError extends Error { readonly name = "SessionCreateIdempotencyUnavailableError"; constructor() { super("Session create idempotency result is unavailable"); } } async function frozenSessionCreatorForInsert( tx: Database, input: { workspaceId: string; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; }, ): Promise { if (!input.createdByActor) { return { initiator: input.createdBy ?? UNATTRIBUTED_LEGACY_INITIATOR, context: input.createdByContext ?? {}, }; } // A first-party worker bearer is minted per request with the exact current // turn/attempt. Freeze the creator under the same ownership locks as the // session insert so a superseded attempt cannot create a child attributed to // its former initiating subject. Session-scoped Codemode credentials remain // deliberately renewable and are a separate, non-orchestration surface. await assertAgentCommandAuthorityInTransaction(tx, { workspaceId: input.workspaceId, actor: input.createdByActor, targetSessionId: input.createdByActor.sessionId, action: "message", }); return await frozenInitiatorForCommandActor(tx, input.workspaceId, input.createdByActor); } /** * The built-in meeting summary's fence at creation. A session is one when it * carries the internal proof, or claims to be one by its creator, policy * role or metadata; then it must be exactly Opengeni's own chat for one * meeting: started by the meeting-summary service with no parent or shared * sandbox, no computer, resources, Skills or other servers, and only the * meeting_read and meeting_notes_save tools. Only me is for the owner of an * Only me meeting; a shared meeting gets a workspace chat. */ async function assertMeetingSummarySessionShape( tx: Database, input: SessionCreateInput, frozen: FrozenTurnInitiator, ): Promise { const servicePrincipal = frozen.initiator.kind === "service" && frozen.initiator.subjectId === MEETING_SUMMARY_SUBJECT_ID; const claimed = input.meetingSummary !== undefined || servicePrincipal || input.policyRole === MEETING_SUMMARY_POLICY_ROLE || Object.hasOwn(input.metadata ?? {}, MEETING_SUMMARY_RECORDING_METADATA_KEY); if (!claimed) return; const proof = input.meetingSummary; const tools = new Set(input.firstPartyMcpTools ?? []); const exact = proof !== undefined && servicePrincipal && !input.createdByActor && !input.parentSessionId && !input.sandboxGroupId && input.policyRole === MEETING_SUMMARY_POLICY_ROLE && input.metadata?.[MEETING_SUMMARY_RECORDING_METADATA_KEY] === proof.recordingId && input.createIdempotencyKey?.startsWith(`${MEETING_SUMMARY_SUBJECT_ID}:`) === true && input.sandboxBackend === "none" && input.resources.length === 0 && (input.skills ?? []).length === 0 && (input.bundledSkillIds ?? []).length === 0 && (input.selectedInstalledSkillIds ?? []).length === 0 && (input.mcpServers ?? []).length === 0 && (input.personalConnectionDelegations ?? []).length === 0 && !input.rigId && (input.tools ?? []).every((tool) => tool.kind === "mcp" && tool.id === "opengeni") && tools.size === MEETING_SUMMARY_TOOLS.length && MEETING_SUMMARY_TOOLS.every((tool) => tools.has(tool)); if (!exact) { throw new Error( "A meeting summary chat is Opengeni's own, for one meeting, with only its tools", ); } const onlyMe = input.visibility === "user_private"; if (onlyMe) await setSubjectRlsContext(tx, proof.ownerSubjectId); const [recording] = await tx .select({ id: schema.recordings.id }) .from(schema.recordings) .where( and( eq(schema.recordings.workspaceId, input.workspaceId), eq(schema.recordings.id, proof.recordingId), eq(schema.recordings.purpose, "meeting"), eq(schema.recordings.visibility, onlyMe ? "user_private" : "workspace_shared"), ...(onlyMe ? [eq(schema.recordings.ownerSubjectId, proof.ownerSubjectId)] : []), ), ) .limit(1); if (!recording) { throw new Error( onlyMe ? "An Only me meeting summary is for that meeting's owner" : "A workspace meeting summary is for a meeting shared with the workspace", ); } } /** * Who an Only me meeting summary's first turn runs for: the meeting's owner. * The meeting-summary service starts that chat, and * assertMeetingSummarySessionShape proved at creation that its owner owns the * meeting, so the turn acts for them, like their own Only me automation (their * personal learning layer, their allowance). A shared meeting's workspace chat, * and every other session, gets no one from here. */ function onlyMeMeetingSummaryOwner(session: { createdByKind: string; createdBySubjectId: string; policyRole: string | null; visibility: string; ownerSubjectId: string | null; }): string | null { return session.createdByKind === "service" && session.createdBySubjectId === MEETING_SUMMARY_SUBJECT_ID && session.policyRole === MEETING_SUMMARY_POLICY_ROLE && session.visibility === "user_private" ? session.ownerSubjectId : null; } async function setScheduledTaskAuthorityRlsContext( tx: Database, frozen: FrozenTurnInitiator, ): Promise { const subjectId = frozen.initiator.subjectId.trim(); if (!subjectId) throw new Error("scheduled task authority writer has no subject"); // frozenSessionCreatorForInsert verified the agent attempt before reading // this separate causal-human field. Keep service audit attribution intact; // never substitute the session creator or parse a caller's provenance JSON. const causalHumanSubjectId = frozen.initiatingHumanSubjectId ?? (frozen.initiator.kind === "subject" ? subjectId : ""); await tx.execute(sql`select set_config('opengeni.subject_id', ${subjectId}, true), set_config( 'opengeni.initiating_human_subject_id', ${causalHumanSubjectId}, true )`); } export type SessionCreateInput = { initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined; bundledSkillIds?: BundledSkillId[] | undefined; requestedSessionId?: string; /** Internal ordinary source-run proof; never accepted from session HTTP input. */ scheduledSourceRunId?: string; /** * Internal proof for the built-in meeting summary (recordings.ts); never * accepted from session HTTP input. Only me for the meeting's owner when * `visibility` is `user_private`. */ meetingSummary?: { recordingId: string; ownerSubjectId: string }; accountId: string; workspaceId: string; visibility?: "user_private" | "workspace_shared"; initialMessage: string; initialModelContext?: string | null; resources: ResourceRef[]; skills?: SessionSkill[]; tools?: ToolRef[]; toolPolicy?: SessionToolPolicy; mcpApprovalPolicies?: Record; metadata: Record; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; model: string; reasoningEffort: ReasoningEffort; latencyMode: LatencyMode; sandboxBackend: SandboxBackend; rigId?: string | null; rigVersionId?: string | null; channelId?: string | null; firstPartyMcpPermissions?: Permission[] | null; firstPartyMcpTools?: FirstPartyMcpToolName[]; instructions?: string | null; /** * The agent the chat is started with. It runs on the agent's current * revision (`agent_prompt_revision`); the agent must be one of this * workspace's that the creating person can see. `subjectId` names that * person when the creating subject is not one (an automation run is * created as its task; its owner's Only me agents count). */ agent?: { id: string; subjectId?: string | null } | null; /** * The organization agent version the chat runs (`agent_version`), the * version whose Instructions are in its prompt, and what the create changed. * Absent for every other chat; a child chat inherits its parent's. */ orgAgent?: { agentId: string; version: number; promptVersion: number | null; overrides: Record | null; } | null; /** * No person will see or answer a question until the task ends. Recorded only * under the reserved metadata key, which a caller-supplied value never sets. */ unattended?: boolean; /** * Changeable unattended setting (migration 1111), set only by first-party * creators such as the scheduler; omitted leaves it to the create option. */ unattendedSetting?: SessionUnattendedSetting; /** Vault narrowing for this session (0739); omission is `{ mode: "all" }`. */ vaultPolicy?: import("@opengeni/contracts").VaultPolicy | undefined; policyRole?: string | null; /** Agent-to-agent reach (migration 0427); omitted means the workspace default. */ agentAccess?: SessionAgentAccess; /** Opaque end-user label; omitted or null means none. */ scopeSubjectId?: SessionScopeSubjectId | null; /** Typed Memory selector (migration 0427); omitted means the workspace layer. */ memoryScope?: SessionMemoryScope; parentSessionId?: string | null; /** Freezes a new root session's code_search decision; omitted uses the boot-installed policy. */ codeSearchDeploymentPolicy?: CodeSearchDeploymentPolicy; /** * Frozen agent configuration (migration 0559). Omitted or null writes a * legacy session. When provided it also participates in keyed-create replay. */ agentConfig?: ResolvedAgentConfig | null; createIdempotencyKey?: string | null; /** Exact explicit installed-Skill selection used for keyed-create replay. */ selectedInstalledSkillIds?: string[]; sandboxGroupId?: string | null; sandboxOs?: SandboxOs; /** Exact accepted generated-session compaction policy; internal lifecycle callers only. */ frozenCodexCompactionMode?: Session["codexCompactionMode"]; /** Exact accepted root-session depth policy; internal lifecycle callers only. */ frozenNestedAgentDepthPolicy?: { effectiveMaxNestedAgentDepth: number; nestedAgentDepthPolicySource: NestedAgentDepthPolicySource; }; mcpServers?: CreateSessionMcpServerInput[]; personalConnectionDelegations?: McpPersonalConnectionDelegation[]; mcpAccountBindings?: McpConnectionAccountBinding[] | null; /** The creating person's account intent, copied onto the first turn. */ connectionAccountIntent?: ConnectionAccountIntent | null; initialPersonalResourceAttachmentIntent?: PersonalResourceAttachmentIntent | null; initialXaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1; initialClaudeProviderAccountAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1; maxNestedAgentDepthOverride?: number | null; allowNestedAgentDepthIncrease?: boolean; subjectId?: string | null; /** * An archived-session import: its `beforeCreateCommit` marks the session * imported, which has no accepted-authority source (0716), so the writer * copies no compatibility record for it. */ archivedImport?: true; /** Trusted, transaction-local linkage run after the exact session row and * MCP metadata exist but before either can commit. It must perform database * work only; throwing rolls the complete create/replay transaction back. */ beforeCreateCommit?: ( tx: Database, sessionId: string, context?: { created: boolean }, ) => Promise; }; type SessionDepthDecision = | ({ denied: false } & SessionDepthPolicy) | { denied: true; id: string; parentSessionId: string | null; rootSessionId: string | null; currentParentDepth: number; attemptedDepth: number; effectiveMaxNestedAgentDepth: number; requestedOverride: number | null; nestedAgentDepthPolicySource: NestedAgentDepthPolicySource; nestedAgentDepthPolicySessionId: string | null; code: SessionSpawnDenialCode; }; function nonNegativeIntegerOrNull(value: unknown): number | null { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 2_147_483_647 ? value : null; } function requireDepthInput(value: number | null | undefined, name: string): number | null { if (value === null || value === undefined) return null; const normalized = nonNegativeIntegerOrNull(value); if (normalized === null) { throw new Error(`${name} must be a non-negative 32-bit integer`); } return normalized; } function workspaceDepthPolicy( workspace: typeof schema.workspaces.$inferSelect, deploymentPolicy: DeploymentDepthPolicy, ): Pick< SessionDepthPolicy, | "effectiveMaxNestedAgentDepth" | "nestedAgentDepthPolicySource" | "nestedAgentDepthPolicySessionId" > { const workspaceValue = nonNegativeIntegerOrNull(workspace.settings?.maxNestedAgentDepth); if (workspaceValue !== null) { return { effectiveMaxNestedAgentDepth: workspaceValue, nestedAgentDepthPolicySource: "workspace", nestedAgentDepthPolicySessionId: null, }; } return { effectiveMaxNestedAgentDepth: deploymentPolicy.maxNestedAgentDepth, nestedAgentDepthPolicySource: deploymentPolicy.policySource, nestedAgentDepthPolicySessionId: null, }; } async function lockWorkspaceForSessionCreate( tx: Database, workspaceId: string, accountId: string, ): Promise<{ workspace: typeof schema.workspaces.$inferSelect; deploymentPolicy: DeploymentDepthPolicy; }> { await lockWorkspaceInferenceControl(tx, workspaceId, "share"); const [workspace] = await tx .select() .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); if (!workspace) { throw new Error(`Workspace not found: ${workspaceId}`); } if (workspace.accountId !== accountId) { throw new Error(`Workspace ${workspaceId} does not belong to account ${accountId}`); } // PostgreSQL requires UPDATE privilege for SELECT ... FOR SHARE. The app role // deliberately cannot mutate this singleton, so use the target-schema-local // SECURITY DEFINER lock/read capability; its row lock remains held by this // outer transaction. const [deploymentPolicy] = await tx.execute(sql` select max_nested_agent_depth as "maxNestedAgentDepth", policy_source as "policySource" from lock_nested_agent_depth_configuration() `); if (!deploymentPolicy) { throw new Error("Nested-agent deployment policy is not configured"); } return { workspace, deploymentPolicy }; } function mapSessionSpawnDenial( row: typeof schema.sessionSpawnDenials.$inferSelect, ): SessionSpawnDenial { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, parentSessionId: row.parentSessionId ?? null, rootSessionId: row.rootSessionId ?? null, currentDepth: row.currentDepth, attemptedDepth: row.attemptedDepth, effectiveMaxNestedAgentDepth: row.effectiveMaxNestedAgentDepth, requestedMaxNestedAgentDepthOverride: row.requestedMaxNestedAgentDepthOverride ?? null, policySource: row.policySource as NestedAgentDepthPolicySource, policySessionId: row.policySessionId ?? null, subjectId: row.subjectId ?? null, code: row.code as SessionSpawnDenialCode, idempotencyKey: row.idempotencyKey ?? null, createdAt: row.createdAt.toISOString(), }; } /** * A child inherits its parent's repository removal records, read from the * parent row the depth decision already holds FOR SHARE: a removal either * commits first and is seen here, or waits for this create and then narrows * the new child too. An agent cannot give a child a removed repository; a * person (or API caller) creating the child with one attaches it again there. */ async function childSessionRemovedRepositories( tx: Database, input: SessionCreateInput, parentSessionId: string, ): Promise { const [parent] = await tx .select({ removedRepositories: schema.sessions.removedRepositories }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, parentSessionId), ), ) .for("share") .limit(1); return admitRequestedRepositories({ removedRepositories: parseSessionRemovedRepositories(parent?.removedRepositories), requested: input.resources, requester: input.createdByActor ? "agent" : "person", }).removedRepositories; } async function parentSessionCodeSearchEnabled( tx: Database, workspaceId: string, parentSessionId: string, ): Promise { const [parent] = await tx .select({ codeSearchEnabled: schema.sessions.codeSearchEnabled }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, parentSessionId)), ) .limit(1); return parent?.codeSearchEnabled === true; } async function resolveSessionDepthDecision( tx: Database, input: SessionCreateInput, id: string, workspace: typeof schema.workspaces.$inferSelect, deploymentPolicy: DeploymentDepthPolicy, ): Promise { const parentSessionId = input.parentSessionId ?? null; const requestedOverride = requireDepthInput( input.maxNestedAgentDepthOverride, "maxNestedAgentDepthOverride", ); const explicitOverride = requestedOverride !== null; if (input.frozenNestedAgentDepthPolicy) { if (parentSessionId !== null) { throw new Error("Frozen root session depth policy cannot create a child session"); } const effectiveMaxNestedAgentDepth = requireDepthInput( input.frozenNestedAgentDepthPolicy.effectiveMaxNestedAgentDepth, "frozenNestedAgentDepthPolicy.effectiveMaxNestedAgentDepth", ); if (effectiveMaxNestedAgentDepth === null) { throw new Error("Frozen root session depth policy has no effective maximum"); } return { denied: false, rootSessionId: id, nestedAgentDepth: 0, maxNestedAgentDepthOverride: requestedOverride, effectiveMaxNestedAgentDepth, nestedAgentDepthPolicySource: input.frozenNestedAgentDepthPolicy.nestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: input.frozenNestedAgentDepthPolicy.nestedAgentDepthPolicySource === "session" ? id : null, }; } let parent: typeof schema.sessions.$inferSelect | undefined; if (parentSessionId) { [parent] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, parentSessionId), ), ) .for("share") .limit(1); if (!parent) { throw new Error(`Parent session not found: ${parentSessionId}`); } if (parent.status === "cancelled") { throw new SessionControlConflictError("Cancelled session subtree cannot create children"); } } const currentParentDepth = parent?.nestedAgentDepth ?? 0; const attemptedDepth = parent ? currentParentDepth + 1 : 0; const rootSessionId = parent?.rootSessionId ?? null; const inheritedPolicy = parent?.nestedAgentDepthPolicySource === "session" ? { effectiveMaxNestedAgentDepth: parent.effectiveMaxNestedAgentDepth, nestedAgentDepthPolicySource: parent.nestedAgentDepthPolicySource as NestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: parent.nestedAgentDepthPolicySessionId ?? null, } : workspaceDepthPolicy(workspace, deploymentPolicy); if ( explicitOverride && requestedOverride > inheritedPolicy.effectiveMaxNestedAgentDepth && input.allowNestedAgentDepthIncrease !== true ) { return { denied: true, id, parentSessionId, rootSessionId, currentParentDepth, attemptedDepth, effectiveMaxNestedAgentDepth: inheritedPolicy.effectiveMaxNestedAgentDepth, requestedOverride, nestedAgentDepthPolicySource: inheritedPolicy.nestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: inheritedPolicy.nestedAgentDepthPolicySessionId, code: "nested_agent_depth_override_forbidden", }; } const selected = explicitOverride ? { effectiveMaxNestedAgentDepth: requestedOverride, nestedAgentDepthPolicySource: "session" as const, nestedAgentDepthPolicySessionId: id, } : inheritedPolicy; if (attemptedDepth > selected.effectiveMaxNestedAgentDepth) { return { denied: true, id, parentSessionId, rootSessionId, currentParentDepth, attemptedDepth, effectiveMaxNestedAgentDepth: selected.effectiveMaxNestedAgentDepth, requestedOverride, nestedAgentDepthPolicySource: selected.nestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: selected.nestedAgentDepthPolicySource === "session" && selected.nestedAgentDepthPolicySessionId === id ? null : selected.nestedAgentDepthPolicySessionId, code: "nested_agent_depth_exceeded", }; } return { denied: false, rootSessionId: rootSessionId ?? id, nestedAgentDepth: attemptedDepth, maxNestedAgentDepthOverride: explicitOverride ? requestedOverride : null, effectiveMaxNestedAgentDepth: selected.effectiveMaxNestedAgentDepth, nestedAgentDepthPolicySource: selected.nestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: selected.nestedAgentDepthPolicySessionId, }; } async function existingSessionForCreateKey( tx: Database, workspaceId: string, createIdempotencyKey: string, ): Promise { // A replay returns the complete existing Session, so this reads its Skills too. const [existing] = await tx .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.createIdempotencyKey, createIdempotencyKey), ), ) .limit(1); return existing; } type SessionCreateReplayIdentity = { initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined; bundledSkillIds?: BundledSkillId[] | undefined; requestedSessionId?: string; visibility?: "user_private" | "workspace_shared"; selectedInstalledSkillIds: string[]; initialPersonalResourceAttachmentIntent?: PersonalResourceAttachmentIntent | null; /** Access/memory scope of the retrying request; omitted means the defaults. */ agentAccess?: SessionAgentAccess; scopeSubjectId?: SessionScopeSubjectId | null; memoryScope?: SessionMemoryScope; /** Resolved creation-time configuration; omitted and null are equivalent. */ agentConfig?: ResolvedAgentConfig | null; /** Unattended create; omitted means interactive. */ unattended?: boolean; }; // Session metadata is immutable after creation and already participates in // every historical schema fixture. Keep this reserved request-identity fact // there instead of making current code require a post-fixture sessions column. // Create admission always replaces a caller-supplied value for this key. const SESSION_CREATE_AGENT_LEARNING_METADATA_KEY = "_opengeni_session_create_agent_learning_v1"; function metadataWithAgentLearningCreateIdentity( metadata: Record, settings: import("@opengeni/contracts").AgentLearningOverrides | undefined, ): Record { const next = { ...metadata }; delete next[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY]; if (settings && Object.keys(settings).length) next[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY] = settings; return next; } const SESSION_CREATE_AGENT_CONFIG_METADATA_KEY = "_opengeni_session_create_agent_config_v1"; /** Canonical creation metadata shared with strict generated-session admission. */ export function metadataWithAgentConfigCreateIdentity( metadata: Record, config: ResolvedAgentConfig | null | undefined, ): Record { const next = { ...metadata }; delete next[SESSION_CREATE_AGENT_CONFIG_METADATA_KEY]; const identity = agentConfigReplayIdentity(config); if (identity !== null) next[SESSION_CREATE_AGENT_CONFIG_METADATA_KEY] = identity; return next; } const SESSION_CREATE_SELECTED_INSTALLED_SKILL_IDS_METADATA_KEY = "_opengeni_session_create_selected_installed_skill_ids_v1"; function metadataWithSelectedInstalledSkillCreateIdentity( metadata: Record, selectedInstalledSkillIds: string[], ): Record { const next = { ...metadata }; delete next[SESSION_CREATE_SELECTED_INSTALLED_SKILL_IDS_METADATA_KEY]; if (selectedInstalledSkillIds.length > 0) { next[SESSION_CREATE_SELECTED_INSTALLED_SKILL_IDS_METADATA_KEY] = [...selectedInstalledSkillIds]; } return next; } function selectedInstalledSkillCreateIdentity(metadata: unknown): string[] { if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return []; const value = (metadata as Record)[ SESSION_CREATE_SELECTED_INSTALLED_SKILL_IDS_METADATA_KEY ]; return Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : []; } function assertSessionCreateReplayIdentity( existing: typeof schema.sessions.$inferSelect, input: SessionCreateReplayIdentity, ): void { if ( stableJson(existing.metadata?.[SESSION_CREATE_AGENT_LEARNING_METADATA_KEY] ?? {}) !== stableJson(input.initialAgentLearning ?? {}) ) throw new SessionCreateIdempotencyConflictError(); if ( stableJson(storedBundledSkillSelectionIdentity(existing.metadata) ?? null) !== stableJson(input.bundledSkillIds ? [...input.bundledSkillIds].sort() : null) ) { throw new SessionCreateIdempotencyConflictError(); } if (input.requestedSessionId && existing.id !== input.requestedSessionId) { throw new SessionIdConflictError(input.requestedSessionId); } if ( stableJson(existing.initialPersonalResourceAttachmentIntent ?? null) !== stableJson(input.initialPersonalResourceAttachmentIntent ?? null) ) { throw new SessionCreateIdempotencyConflictError(); } if ( stableJson(selectedInstalledSkillCreateIdentity(existing.metadata)) !== stableJson(input.selectedInstalledSkillIds) ) { throw new SessionCreateIdempotencyConflictError(); } if (existing.createRequestedVisibility !== (input.visibility ?? "workspace_shared")) { throw new SessionCreateIdempotencyConflictError(); } // A keyed retry must not silently flip whether anyone answers the agent. if (sessionMetadataUnattended(existing.metadata) !== (input.unattended === true)) { throw new SessionCreateIdempotencyConflictError(); } // A keyed retry that asks for a different agent-access, end-user, or memory // scope is a different request, never a replay that silently keeps the // winner's (possibly wider) scope. if ( existing.agentAccess !== (input.agentAccess ?? "workspace") || existing.memoryScope !== (input.memoryScope ?? "workspace") || (input.scopeSubjectId !== undefined && sessionEndUserFromRow(existing) !== input.scopeSubjectId) ) { throw new SessionCreateIdempotencyConflictError(); } // Compare immutable creation truth, never the live /agent configuration. // Missing metadata denotes a legacy-null create, including later conversion. if ( stableJson(existing.metadata?.[SESSION_CREATE_AGENT_CONFIG_METADATA_KEY] ?? null) !== stableJson(agentConfigReplayIdentity(input.agentConfig)) ) { throw new SessionCreateIdempotencyConflictError(); } } /** Replay compares what the session does, not the bookkeeping `source` label. */ function agentConfigReplayIdentity(config: unknown): unknown { const parsed = parseStoredSessionAgentConfig(config); if (!parsed) return null; const { source: _source, ...identity } = parsed; return identity; } /** * Read a stored agent configuration. A value this release cannot parse (for * example written by a newer release after a rollback) projects as null. */ export function parseStoredSessionAgentConfig(value: unknown): ResolvedAgentConfig | null { if (value === null || value === undefined) return null; const parsed = ResolvedAgentConfig.safeParse(value); return parsed.success ? parsed.data : null; } async function lockSessionCreateIdempotencyKey( tx: Database, workspaceId: string, createIdempotencyKey: string, ): Promise { // Successes live in `sessions` while denials live in `session_spawn_denials`; // their separate unique indexes cannot by themselves serialize a success // racing a denial. The database guard trigger is authoritative for every // writer; this transaction-scoped advisory lock keeps application callers // on one workspace/key path without serializing unrelated workspace creates. await tx.execute( sql`select pg_advisory_xact_lock(hashtext(${`session-create:${workspaceId}:${createIdempotencyKey}`}))`, ); } async function lockAgentSessionCreate(tx: Database, input: SessionCreateInput): Promise { const actorSessionId = input.createdByActor?.sessionId; if (!actorSessionId) return; // Agent-originated child creation first reads the parent under FOR SHARE, // then verifies the live attempt under FOR UPDATE. Serialize creates from // the same parent session so concurrent tool calls cannot deadlock while // upgrading that row lock. Unrelated sessions retain full concurrency. await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`agent-session-create:${input.workspaceId}:${actorSessionId}`}, 0))`, ); } async function existingSpawnDenialForKey( tx: Database, workspaceId: string, createIdempotencyKey: string, ): Promise { const [existing] = await tx .select() .from(schema.sessionSpawnDenials) .where( and( eq(schema.sessionSpawnDenials.workspaceId, workspaceId), eq(schema.sessionSpawnDenials.idempotencyKey, createIdempotencyKey), ), ) .limit(1); return existing ? mapSessionSpawnDenial(existing) : null; } async function recordSessionSpawnDenial( tx: Database, input: SessionCreateInput, decision: Extract, ): Promise { const [inserted] = await tx .insert(schema.sessionSpawnDenials) .values({ id: decision.id, accountId: input.accountId, workspaceId: input.workspaceId, parentSessionId: decision.parentSessionId, rootSessionId: decision.rootSessionId, currentDepth: decision.currentParentDepth, attemptedDepth: decision.attemptedDepth, effectiveMaxNestedAgentDepth: decision.effectiveMaxNestedAgentDepth, requestedMaxNestedAgentDepthOverride: decision.requestedOverride, policySource: decision.nestedAgentDepthPolicySource, policySessionId: decision.nestedAgentDepthPolicySessionId, subjectId: input.subjectId ?? null, code: decision.code, idempotencyKey: input.createIdempotencyKey ?? null, }) .onConflictDoNothing({ target: [schema.sessionSpawnDenials.workspaceId, schema.sessionSpawnDenials.idempotencyKey], where: sql`${schema.sessionSpawnDenials.idempotencyKey} is not null`, }) .returning(); if (inserted) return mapSessionSpawnDenial(inserted); const key = input.createIdempotencyKey; if (key !== null && key !== undefined) { const existing = await existingSpawnDenialForKey(tx, input.workspaceId, key); if (existing) return existing; } throw new Error("Failed to record session spawn denial"); } /** * The human an agent-child create request claims: the verified initiating * human of an agent-attempt request (whose subject is a worker principal), or * the authenticated subject of a direct request. SQL compares the same claims * with the locked parent turn; this only decides whether to try the seam. */ function agentChildCreationRequestHuman(subjectId: string | null | undefined): string | null { const actorHuman = currentSessionRlsActorInitiatingHumanSubjectId(); return actorHuman !== undefined ? actorHuman : (subjectId ?? null); } /** * Encode one sessions value as the ordinary Drizzle INSERT does. The atomic * seam receives JSON for jsonb_populate_record, so custom column encodings * (lossless text) must be applied here or NUL, lone surrogates and text that * resembles the codec escape would be rejected or decoded differently. * Plain text parameters reach the ordinary INSERT UTF-8 encoded, which turns * a lone surrogate into U+FFFD; JSON would carry it as an escape PostgreSQL * rejects, so non-JSON strings are made well-formed the same way. */ function agentChildCreationColumnValue( column: { name: string; columnType: string; getSQLType(): string; mapToDriverValue(value: unknown): unknown; }, value: unknown, ): unknown { if (value === null) return value; const sqlType = column.getSQLType(); if (column.columnType !== "PgCustomColumn") { return sqlType === "json" || sqlType === "jsonb" ? value : wellFormedDriverText(value); } const encoded = column.mapToDriverValue(value); if (sqlType === "json" || sqlType === "jsonb") { return typeof encoded === "string" ? JSON.parse(encoded) : encoded; } if (typeof encoded === "string") return wellFormedText(encoded); if (typeof encoded === "number" || typeof encoded === "boolean") return encoded; throw new Error(`Agent child creation cannot encode sessions.${column.name}`); } // String.prototype.toWellFormed: each lone surrogate code unit becomes U+FFFD. const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?, ): Promise { const origin = metadata._opengeniSiteOrigin; const siteId = origin && typeof origin === "object" ? (origin as { siteId?: unknown }).siteId : undefined; if (typeof siteId !== "string" || !z.string().uuid().safeParse(siteId).success) return null; const [home] = await rawRows<{ channelId: string | null }>( tx, sql` select "channelId" from ( select 0 as rank, placement.channel_id::text as "channelId" from ${schema.siteProjectPlacements} placement where placement.workspace_id = ${workspaceId} and placement.site_id = ${siteId}::uuid union all select 1, root.channel_id::text from ${schema.workspaceArtifactVersions} version join ${schema.sessions} source on source.workspace_id = version.workspace_id and source.id = version.source_session_id join ${schema.sessions} root on root.workspace_id = source.workspace_id and root.id = source.root_session_id where version.workspace_id = ${workspaceId} and version.artifact_id = ${siteId}::uuid and version.revision = 1 and root.site_access_root_id is null ) homes order by rank limit 1`, ); return home?.channelId ?? null; } /** The agent a new chat starts with is gone, or not one its creator can see. */ export class SessionAgentNotFoundError extends Error { readonly name = "SessionAgentNotFoundError"; constructor( readonly agentId: string, readonly reason: "not_found" | "child_chat" | "requires_private_chat" = "not_found", ) { super( reason === "child_chat" ? "A chat started from another chat follows its parent; start the agent in a new chat." : reason === "requires_private_chat" ? "This agent is Only me, so its chats are Only me too. Start this chat as Only me." : "That agent is not available in this workspace.", ); } } /** * The agent and revision a new chat binds to, read in the chat's workspace. * Only me agents count only for their owner, in their Only me chats. A child * session binds too: that is an agent delegating to another agent by name, * checked against the person the creating chat acts for (`subjectId`). */ async function sessionAgentBinding( tx: Database, input: Pick, agentId: string, /** The Only me chat's owner, when it is one. */ privateOwnerSubjectId: string | null = null, ): Promise<{ agentId: string; revision: number }> { const subjectId = input.subjectId ?? null; const [row] = await rawRows<{ id: string; current_revision: number; visibility: string }>( tx, sql`select a.id::text as id, a.current_revision, a.visibility from agents a where a.workspace_id = ${input.workspaceId}::uuid and a.id = ${agentId}::uuid and (a.visibility = 'workspace' ${subjectId ? sql`or a.owner_subject_id = ${subjectId}` : sql``})`, ); if (!row) throw new SessionAgentNotFoundError(agentId); // Others in a shared chat would run on the owner's private Instructions. if (row.visibility !== "workspace" && input.visibility !== "user_private") { throw new SessionAgentNotFoundError(agentId, "requires_private_chat"); } // An Only me agent runs only in its owner's own Only me chat, whoever's // access (`agent.subjectId`, such as an Only me automation's owner) found it. if (row.visibility !== "workspace" && privateOwnerSubjectId !== subjectId) { throw new SessionAgentNotFoundError(agentId); } return { agentId: row.id, revision: Number(row.current_revision) }; } async function createSessionInTransaction( tx: SessionActivityDatabase, input: SessionCreateInput, id: string, ): Promise { const selectedInstalledSkillIds = input.selectedInstalledSkillIds ?? []; const sessionMetadata = withSessionUnattendedMetadata( metadataWithSelectedInstalledSkillCreateIdentity( withBundledSkillSelectionMetadata( metadataWithAgentConfigCreateIdentity( metadataWithAgentLearningCreateIdentity(input.metadata, input.initialAgentLearning), input.agentConfig, ), input.bundledSkillIds, ), selectedInstalledSkillIds, ), input.unattended === true, ); const createIdempotencyKey = input.createIdempotencyKey ?? null; const createRequestedVisibility = input.visibility ?? "workspace_shared"; if (createRequestedVisibility === "user_private" || sessionMetadata._opengeniSiteOrigin) { // Private creation later proves the owner's live organization membership // and, for a fresh top-level organization session, reads the mutable // owner/admin enablement setting. Serialize both checks with organization // settings changes and suspend/offboard before taking any workspace or // parent row lock, so the canonical membership -> session lifecycle cannot // form a lock cycle. A committed keyed replay is still resolved below // before the mutable enablement check opens a fresh-create capability. await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ); } const { workspace, deploymentPolicy } = await lockWorkspaceForSessionCreate( tx, input.workspaceId, input.accountId, ); if ( input.createdBy?.kind === "subject" && input.subjectId !== null && input.subjectId !== undefined ) { if (input.subjectId !== input.createdBy.subjectId) { throw new Error("Managed-human session creator does not match authenticated subject"); } await setSubjectRlsContext(tx, input.createdBy.subjectId); await assertActiveManagedHumanOrganizationMembership(tx, { accountId: input.accountId, subjectId: input.createdBy.subjectId, }); } if (createIdempotencyKey !== null) { // Keyed admission retains the control -> advisory order used by old // binaries during the rolling migration. The database depth trigger takes // the same advisory lock after its control-row prefix, so an old writer // holding control cannot deadlock a new writer holding the advisory lock. await lockSessionCreateIdempotencyKey(tx, input.workspaceId, createIdempotencyKey); // A committed success always wins over a denial on a later retry. const existing = await existingSessionForCreateKey(tx, input.workspaceId, createIdempotencyKey); if (existing) { // A keyed replay is allowed to return the original session only when a // caller-provided identity agrees with the winning request. Check this // before any first-turn repair so a retry cannot hide a requested-ID // conflict behind an apparently successful replay. assertSessionCreateReplayIdentity(existing, { initialAgentLearning: input.initialAgentLearning, bundledSkillIds: input.bundledSkillIds, ...(input.requestedSessionId ? { requestedSessionId: input.requestedSessionId } : {}), visibility: createRequestedVisibility, selectedInstalledSkillIds: input.selectedInstalledSkillIds ?? [], initialPersonalResourceAttachmentIntent: input.initialPersonalResourceAttachmentIntent ?? null, ...(input.agentAccess ? { agentAccess: input.agentAccess } : {}), ...(input.scopeSubjectId !== undefined ? { scopeSubjectId: input.scopeSubjectId } : {}), ...(input.memoryScope ? { memoryScope: input.memoryScope } : {}), ...(input.agentConfig !== undefined ? { agentConfig: input.agentConfig } : {}), ...(input.unattended ? { unattended: true } : {}), }); const grouped = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ existing.id, ]); const [canonicalExisting] = await canonicalSessionRowsFromEventCursors( tx, input.workspaceId, [existing], ); if (!canonicalExisting) { throw new Error(`Session event cursor missing for session ${existing.id}`); } if (input.scheduledSourceRunId) await bindScheduledTaskRunSessionInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, runId: input.scheduledSourceRunId, sessionId: existing.id, }); await input.beforeCreateCommit?.(tx, existing.id, { created: false }); return { session: await mapSessionWithControl(tx, canonicalExisting, grouped.get(existing.id) ?? []), created: false, denied: false, }; } const existingDenial = await existingSpawnDenialForKey( tx, input.workspaceId, createIdempotencyKey, ); if (existingDenial) { return { created: false, denied: true, denial: existingDenial, }; } } await lockAgentSessionCreate(tx, input); const decision = await resolveSessionDepthDecision(tx, input, id, workspace, deploymentPolicy); if (decision.denied) { return { created: false, denied: true, denial: await recordSessionSpawnDenial(tx, input, decision), }; } // Do not run mutable creator validation before keyed denial replay above. const frozenCreator = await frozenSessionCreatorForInsert(tx, input); await assertMeetingSummarySessionShape(tx, input, frozenCreator); // A subject creator resolves their own current pool. A creator that is not a // subject (service, organization API key, bridge) has no exact human, so it // resolves the organization or workspace pool and never a personal pool. const subjectCreatorId = frozenCreator.initiator.kind === "subject" && input.subjectId ? input.subjectId : null; // SuperGrok's v1 value is never computed from live state after its cutover: // new work writes the column default and a child copies its parent's value // (design 5.3, "v1 columns after a provider's cutover"). const initialXaiProviderAccountAuthoritySnapshot = input.initialXaiProviderAccountAuthoritySnapshot ?? WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1; // The creator's subject RLS context, which the SuperGrok acceptance // resolver used to set as a side effect when the caller supplied no // accepted snapshot (a fresh session, not a copy of a parent's). The // session insert below relies on it, so whoever retires this v1 input must // keep setting the context for that same case. if (input.initialXaiProviderAccountAuthoritySnapshot === undefined && subjectCreatorId) await setSubjectRlsContext(tx, subjectCreatorId); const initialClaudeProviderAccountAuthoritySnapshot = input.initialClaudeProviderAccountAuthoritySnapshot ?? WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1; const parentTurnId = input.parentSessionId ? input.createdByActor?.sessionId === input.parentSessionId ? input.createdByActor.turnId : null : null; // Frozen once (migration 0520). A child keeps its parent's decision, so one // session tree stays in one experiment arm; a root session decides its own. const codeSearchEnabled = input.parentSessionId ? await parentSessionCodeSearchEnabled(tx, input.workspaceId, input.parentSessionId) : resolveSessionCodeSearchEnabled( workspace.settings, input.codeSearchDeploymentPolicy ?? codeSearchDeploymentPolicyForCreate(), id, ); let insertedRows: SessionRowWithSkills[]; let privateCreateCapabilityId: string | null = null; let privateCreateOwnerMembershipId: string | null = null; let privateCreateOwnerSubjectId: string | null = null; if (createRequestedVisibility === "user_private") { if (input.parentSessionId) { if (!input.createdByActor || input.createdByActor.sessionId !== input.parentSessionId) { throw new Error("Private child session creation requires its exact parent attempt"); } // Internal-update turns retain service audit attribution. The capability // below derives the distinct causal human from the locked parent turn // and verifies that human owns the private parent, alongside the live // attempt/generation and interruption fences. Do not confuse attribution // with authority or rewrite the child's service creator as a human. const capability = await openPrivateChildSessionCreateCapability(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: id, parentSessionId: input.parentSessionId, actorTurnId: input.createdByActor.turnId, actorAttemptId: input.createdByActor.attemptId, actorExecutionGeneration: input.createdByActor.executionGeneration, }); privateCreateCapabilityId = capability.capabilityId; privateCreateOwnerMembershipId = capability.ownerMembershipId; privateCreateOwnerSubjectId = capability.ownerSubjectId; } else { let owner = input.subjectId; if (input.scheduledSourceRunId) { const accepted = await getScheduledTaskRunAcceptedExecution(tx, { workspaceId: input.workspaceId, runId: input.scheduledSourceRunId, }); // The run must be this exact accepted scheduler occurrence, creating // the chat its generated-session binding names. const acceptedRun = accepted && accepted.task.accountId === input.accountId && accepted.generatedSessionBinding?.createIdempotencyKey === input.createIdempotencyKey && frozenCreator.initiator.kind === "service" && frozenCreator.initiator.subjectId === "scheduler" && !input.sandboxGroupId ? accepted : null; let scheduledOwner: string | null = null; if (acceptedRun) { // An Only me schedule's chats belong to its owner, the human its // accepted run was admitted for. The capability below re-proves that // person may still create Only me chats here. const taskOwner = acceptedRun.task.ownerSubjectId; if ( acceptedRun.task.visibility === "private" && taskOwner && (acceptedRun.task.runMode === "new_session_per_run" || acceptedRun.task.runMode === "reusable_session") && acceptedRun.causalHumanSubjectId === taskOwner && acceptedRun.causalHumanAuthority?.subjectId === taskOwner ) scheduledOwner = taskOwner; } if (!scheduledOwner) { throw new Error("Private source session requires its accepted owning-human run"); } owner = scheduledOwner; await setSubjectRlsContext(tx, owner); } else if (input.meetingSummary) { // A meeting summary is Only me for the meeting's owner; // assertMeetingSummarySessionShape proved it is their Only me meeting. owner = input.meetingSummary.ownerSubjectId; await setSubjectRlsContext(tx, owner); } else if (frozenCreator.initiator.kind !== "subject" || !owner) { throw new Error("Private session creation requires a top-level managed human"); } else if (input.sandboxGroupId) { // An Only-me session may share an existing sandbox: who can read the // conversation and who can use the box are separate. The creator must // already see a session on that box, so a group id alone grants nothing. await setSubjectRlsContext(tx, owner); const [visibleMember] = await tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.sandboxGroupId, input.sandboxGroupId), ), ) .limit(1); if (!visibleMember) { throw new Error("Private session sandbox group is not visible to its creator"); } } if (!owner) throw new Error("Private session owner is unavailable"); const capability = await openPrivateSessionCreateCapability(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: id, actorSubjectId: owner, }); privateCreateCapabilityId = capability.capabilityId; privateCreateOwnerMembershipId = capability.ownerMembershipId; privateCreateOwnerSubjectId = owner; } } // Agent-created work copies its parent turn's accounts, which can name a // shared account disconnected or reconnected since. The new session runs // without that connector, as the parent's own turn already does, instead of // the account fence refusing the whole create. Same narrowing as an accepted // prompt: nothing is added or replaced, and the fence still checks the rest. const { bindings: acceptedMcpAccountBindings } = await withoutLapsedWorkspaceAccountBindings( tx as unknown as Database, input.workspaceId, parseAcceptedMcpAccountBindings(input.mcpAccountBindings), ); const channelId = input.channelId == null && !input.parentSessionId ? await siteHomeChannelId(tx as unknown as Database, input.workspaceId, sessionMetadata) : (input.channelId ?? null); const removedRepositories = input.parentSessionId ? await childSessionRemovedRepositories(tx as unknown as Database, input, input.parentSessionId) : []; const agentBinding = input.agent ? await sessionAgentBinding( tx as unknown as Database, input.agent.subjectId ? { ...input, subjectId: input.agent.subjectId } : input, input.agent.id, privateCreateOwnerSubjectId, ) : null; if (agentBinding && input.orgAgent) { throw new Error("A chat runs a workspace agent or an organization agent, not both"); } // An organization agent chat: named on create, or inherited by a worker chat. const orgAgentBinding = input.orgAgent ? input.orgAgent : input.parentSessionId && !agentBinding ? await inheritedSessionOrgAgentInTransaction(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, parentSessionId: input.parentSessionId, }) : null; try { const insertValues: typeof schema.sessions.$inferInsert = withLosslessContentWriteVersion( { id, accountId: input.accountId, workspaceId: input.workspaceId, ...(agentBinding ? { agentId: agentBinding.agentId, agentPromptRevision: agentBinding.revision } : {}), ...(orgAgentBinding ? { agentId: orgAgentBinding.agentId, agentVersion: orgAgentBinding.version, agentPromptVersion: orgAgentBinding.promptVersion, agentOverrides: orgAgentBinding.overrides, } : {}), initialMessage: input.initialMessage, initialModelContext: input.initialModelContext ?? null, title: AUTOMATIC_SESSION_TITLE_FALLBACK, titleSource: "agent", resources: input.resources, removedRepositories, tools: input.tools ?? [], toolPolicy: input.toolPolicy ?? { mode: "explicit", inheritedFromSessionId: input.parentSessionId ?? null, }, metadata: sessionMetadata, mcpApprovalPolicies: input.mcpApprovalPolicies ?? {}, ...creatorColumns(frozenCreator), ...(privateCreateOwnerMembershipId ? { ownerOrganizationMembershipId: privateCreateOwnerMembershipId, ownerSubjectId: privateCreateOwnerSubjectId, } : {}), model: input.model, reasoningEffort: input.reasoningEffort, latencyMode: input.latencyMode, sandboxBackend: input.sandboxBackend, sandboxOs: input.sandboxOs ?? "linux", sandboxGroupId: input.sandboxGroupId ?? id, rigId: input.rigId ?? null, rigVersionId: input.rigVersionId ?? null, channelId, firstPartyMcpPermissions: input.firstPartyMcpPermissions ? canonicalSecretPermissions(input.firstPartyMcpPermissions) : null, firstPartyMcpTools: input.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS], initialPersonalConnectionDelegations: input.personalConnectionDelegations ?? [], initialMcpAccountBindings: acceptedMcpAccountBindings, initialConnectionAccountIntent: parseConnectionAccountIntent(input.connectionAccountIntent), initialPersonalResourceAttachmentIntent: input.initialPersonalResourceAttachmentIntent ?? null, visibility: createRequestedVisibility, createRequestedVisibility, initialXaiProviderAccountAuthoritySnapshot, initialClaudeProviderAccountAuthoritySnapshot, instructions: input.instructions ?? null, ...(input.vaultPolicy !== undefined ? { vaultPolicy: input.vaultPolicy } : {}), policyRole: input.policyRole ?? null, agentAccess: input.agentAccess ?? "workspace", scopeSubjectId: input.scopeSubjectId !== undefined ? input.scopeSubjectId : frozenCreator.initiator.kind === "subject" && /^(?:user:|external_user:)/u.test(frozenCreator.initiator.subjectId) ? frozenCreator.initiator.subjectId : null, // Retained columns are historical only. Canonical scope is derived // from the creator resolved under the admission locks above. endUserSource: null, endUserId: null, memoryScope: input.memoryScope ?? "workspace", parentSessionId: input.parentSessionId ?? null, parentTurnId, createIdempotencyKey, rootSessionId: decision.rootSessionId, nestedAgentDepth: decision.nestedAgentDepth, maxNestedAgentDepthOverride: decision.maxNestedAgentDepthOverride, effectiveMaxNestedAgentDepth: decision.effectiveMaxNestedAgentDepth, nestedAgentDepthPolicySource: decision.nestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: decision.nestedAgentDepthPolicySessionId, // Freeze once at create from the effective create model + workspace // default. Later workspace setting changes never move existing sessions. codexCompactionMode: input.frozenCodexCompactionMode ?? (isCodexBilledModel(input.model) ? resolveWorkspaceCodexCompactionDefault(workspace.settings) : "portable"), codeSearchEnabled, agentConfig: input.agentConfig ?? null, ...(input.unattendedSetting ? { unattendedSetting: input.unattendedSetting } : {}), // Frozen: the chat starts unattended through its setting. The // instructions and tools follow this, never the setting's later value. ...(input.unattendedSetting === "unattended" || input.unattendedSetting === "unattended_by_default" ? { startedUnattended: true } : {}), // Creation reserves identity, not runnable work. The atomic start // transaction installs queued status together with its turn/wake. status: "idle", }, "initialMessage", "initialMessageCodecVersion", ); // Skill folders are written through `sessionSkillSets`, never as part of // the `sessions` row model (see that table's comment). const skills = input.skills ?? []; if ( input.createdByActor && parentTurnId && frozenCreator.initiatingHumanSubjectId && agentChildCreationRequestHuman(input.subjectId) ) { // The SQL creation seam inserts the row and immutable witness together. // It never upgrades a direct INSERT or an existing session's provenance. // The covered human is the parent turn's recorded initiating human, so // the owner's service-initiated turns (internal updates and goal // continuations) are included. SQL rechecks it against the locked turn // and the request's verified claims; another person never matches. const columns = getTableColumns(schema.sessions); // The creation seam's column allow-list predates removal records; the // inherited records are written right after, in this transaction. const valuesByColumn = Object.fromEntries([ ...Object.entries(insertValues) .filter(([key, value]) => value !== undefined && key !== "removedRepositories") .map(([key, value]) => { const column = columns[key as keyof typeof columns]; return [column.name, agentChildCreationColumnValue(column, value)] as const; }), [ schema.sessionSkillSets.skills.name, agentChildCreationColumnValue(schema.sessionSkillSets.skills, skills), ] as const, ]); const actor = input.createdByActor; const created = await tx.execute<{ id: string; }>(sql`select id from create_agent_child_session( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${actor.sessionId}::uuid, ${actor.turnId}::uuid, ${actor.attemptId}::uuid, ${actor.executionGeneration}::integer, ${JSON.stringify(valuesByColumn)}::jsonb )`); insertedRows = !created.length ? [] : removedRepositories.length > 0 ? await tx .update(schema.sessions) .set({ removedRepositories }) .where(eq(schema.sessions.id, created[0]!.id)) .returning(sessionRowWithSkillsColumns) : await tx .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where(eq(schema.sessions.id, created[0]!.id)); } else { // Non-agent creates, unscoped legacy creates and turns with no initiating // human retain their original path. Never infer the request subject from // readable parent IDs: these creates gain no machine-tree witness. const [insertedRow] = await tx .insert(schema.sessions) .values(insertValues) .onConflictDoNothing() .returning(); insertedRows = !insertedRow ? [] : skills.length === 0 ? [{ ...insertedRow, skills: [] }] : await tx .update(schema.sessionSkillSets) .set({ skills }) .where( and( eq(schema.sessionSkillSets.workspaceId, input.workspaceId), eq(schema.sessionSkillSets.id, insertedRow.id), ), ) .returning({ skills: schema.sessionSkillSets.skills }) .then((rows) => rows.map((row) => ({ ...insertedRow, skills: row.skills }))); } if (privateCreateCapabilityId) { await closePrivateSessionCreateCapability(tx, privateCreateCapabilityId); privateCreateCapabilityId = null; } } catch (error) { // The caller validated the channel workspace-scoped, but a concurrent // channel delete can still race the insert; keep the typed 422 path. if (input.channelId && isSessionChannelFkViolation(error)) { throw new ChannelNotFoundError(input.channelId); } throw error; } const [inserted] = insertedRows; if (inserted && !input.archivedImport) { await copySubscriptionAuthorityCompatInTransaction(tx, [ { kind: "session_initial", workspaceId: input.workspaceId, id: inserted.id }, ]); } if (!inserted) { if (createIdempotencyKey) { const existing = await existingSessionForCreateKey( tx, input.workspaceId, createIdempotencyKey, ); if (existing) { assertSessionCreateReplayIdentity(existing, { initialAgentLearning: input.initialAgentLearning, bundledSkillIds: input.bundledSkillIds, ...(input.requestedSessionId ? { requestedSessionId: input.requestedSessionId } : {}), visibility: createRequestedVisibility, selectedInstalledSkillIds: input.selectedInstalledSkillIds ?? [], initialPersonalResourceAttachmentIntent: input.initialPersonalResourceAttachmentIntent ?? null, ...(input.agentAccess ? { agentAccess: input.agentAccess } : {}), ...(input.scopeSubjectId !== undefined ? { scopeSubjectId: input.scopeSubjectId } : {}), ...(input.memoryScope ? { memoryScope: input.memoryScope } : {}), ...(input.agentConfig !== undefined ? { agentConfig: input.agentConfig } : {}), ...(input.unattended ? { unattended: true } : {}), }); const grouped = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ existing.id, ]); const [canonicalExisting] = await canonicalSessionRowsFromEventCursors( tx, input.workspaceId, [existing], ); if (!canonicalExisting) { throw new Error(`Session event cursor missing for session ${existing.id}`); } if (input.scheduledSourceRunId) await bindScheduledTaskRunSessionInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, runId: input.scheduledSourceRunId, sessionId: existing.id, }); await input.beforeCreateCommit?.(tx, existing.id, { created: false }); return { session: await mapSessionWithControl( tx, canonicalExisting, grouped.get(existing.id) ?? [], ), created: false, denied: false, }; } // A BEFORE guard trigger suppresses a losing source row instead of // aborting the transaction with 23505. The durable cross-outcome ledger // may therefore have selected a denial; replay it just as the initial // admission check does, rather than reporting a phantom create failure. const existingDenial = await existingSpawnDenialForKey( tx, input.workspaceId, createIdempotencyKey, ); if (existingDenial) { return { created: false, denied: true, denial: existingDenial, }; } if (input.requestedSessionId) throw new SessionIdConflictError(input.requestedSessionId); throw new SessionCreateIdempotencyUnavailableError(); } if (input.requestedSessionId) throw new SessionIdConflictError(input.requestedSessionId); throw new Error("Failed to create session"); } const mcpServers = await insertSessionMcpServers(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: inserted.id, servers: input.mcpServers ?? [], }); if (input.scheduledSourceRunId) await bindScheduledTaskRunSessionInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, runId: input.scheduledSourceRunId, sessionId: inserted.id, }); await input.beforeCreateCommit?.(tx, inserted.id, { created: true }); return { session: await mapSessionWithControl(tx, inserted, mcpServers), created: true, denied: false, }; } export async function createSession(db: Database, input: SessionCreateInput): Promise { // Generate the id up front so the same uuid can seed sandbox_group_id for a // singleton group (sandbox_group_id cannot SQL-default to id). const id = input.requestedSessionId ?? crypto.randomUUID(); let result: SessionCreateResult; try { result = await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint( scopedDb, async (tx) => await createSessionInTransaction(tx, input, id), ), ); } catch (error) { return translateSessionCreateError(error); } if (result.denied) { // Throw only after withRlsContext's outer transaction commits the denial. throw new SessionSpawnDeniedDbError(result.denial); } return result.session; } /** * Inserts a session under a workspace-scoped CREATE idempotency key, collapsing * a concurrent race on the same key to a single row. A losing source insert * is either handled by `onConflictDoNothing` on the partial unique index or * suppressed by the database BEFORE guard, and the durable winner is fetched * and returned. Two near-simultaneous creates with the same key therefore * yield ONE session and both callers see the same id. `created` distinguishes * the winner (true: this call inserted and must run the rest of the start flow) * from the loser/dup (false: the row already existed and must be returned as-is). */ export async function createSessionWithIdempotencyKeyResult( db: Database, input: SessionCreateInput & { createIdempotencyKey: string }, ): Promise { // Generate the id up front so the same uuid can seed sandbox_group_id for a // singleton group (sandbox_group_id cannot SQL-default to id). const id = input.requestedSessionId ?? crypto.randomUUID(); try { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint( scopedDb, async (tx) => await createSessionInTransaction(tx, input, id), ), ); } catch (error) { return translateSessionCreateError(error); } } /** * Backward-compatible keyed create API. Denials are committed by the * admission transaction and then surfaced as SessionSpawnDeniedDbError; * callers that need a structured result use createSessionWithIdempotencyKeyResult. */ export async function createSessionWithIdempotencyKey( db: Database, input: SessionCreateInput & { createIdempotencyKey: string }, ): Promise { const result = await createSessionWithIdempotencyKeyResult(db, input); if (result.denied) { throw new SessionSpawnDeniedDbError(result.denial); } return result; } export async function getSessionByCreateIdempotencyKey( db: Database, workspaceId: string, createIdempotencyKey: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.createIdempotencyKey, createIdempotencyKey), ), ) .limit(1); if (!row) return null; const [session] = await canonicalSessionRowsFromEventCursors(scopedDb, workspaceId, [row]); if (!session) throw new Error(`Session event cursor missing for session ${row.id}`); const grouped = await sessionMcpServerMetadataForSessions(scopedDb, workspaceId, [row.id]); return await mapSessionWithControl(scopedDb, session, grouped.get(row.id) ?? []); }); } /** * Recover a keyed create before mutable create dependencies (notably the * current model catalog) are consulted. A fully initialized queued turn gets a * fresh durable wake revision from persisted state only; an uninitialized shell * returns its persisted model so the caller can reopen it strictly as retained * while the canonical keyed transaction repairs initialization. The same * request-identity checks as transactional create replay run before any session * or committed denial is returned. */ export type InitializedSessionCreateReplay = | { outcome: "session"; session: Session & { initialTurnId: string | null }; temporalWorkflowId: string; workflowWakeRevision: number | null; changed: boolean; } | { outcome: "pending"; session: Session; } | { outcome: "denied"; denial: SessionSpawnDenial }; export async function getInitializedSessionCreateReplay( db: Database, input: { initialAgentLearning?: import("@opengeni/contracts").AgentLearningOverrides | undefined; agentAccess?: SessionAgentAccess; scopeSubjectId?: SessionScopeSubjectId | null; memoryScope?: SessionMemoryScope; bundledSkillIds?: BundledSkillId[] | undefined; accountId: string; workspaceId: string; subjectId: string; activeManagedHumanSubjectId?: string; createIdempotencyKey: string; requestedSessionId?: string; visibility?: "user_private" | "workspace_shared"; selectedInstalledSkillIds: string[]; initialPersonalResourceAttachmentIntent?: PersonalResourceAttachmentIntent | null; deferInitialTurn?: boolean; /** Resolved agent configuration of the retry; omitted skips the comparison. */ agentConfig?: ResolvedAgentConfig | null; /** The retry's `unattended: true`; a keyed replay must agree with the winner. */ unattended?: boolean; }, ): Promise { return await withWorkspaceSubjectSessionActivityRls( db, input.workspaceId, input.subjectId, async (scopedDb) => { if (input.visibility === "user_private") { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ); } await lockWorkspaceForSessionCreate(scopedDb, input.workspaceId, input.accountId); if (input.activeManagedHumanSubjectId) { await setSubjectRlsContext(scopedDb, input.activeManagedHumanSubjectId); await assertActiveManagedHumanOrganizationMembership(scopedDb, { accountId: input.accountId, subjectId: input.activeManagedHumanSubjectId, }); } await lockSessionCreateIdempotencyKey( scopedDb, input.workspaceId, input.createIdempotencyKey, ); const existing = await existingSessionForCreateKey( scopedDb, input.workspaceId, input.createIdempotencyKey, ); if (!existing) { const denial = await existingSpawnDenialForKey( scopedDb, input.workspaceId, input.createIdempotencyKey, ); return denial ? { outcome: "denied", denial } : null; } assertSessionCreateReplayIdentity(existing, input); const startEvents = await scopedDb .select({ id: schema.sessionEvents.id, type: schema.sessionEvents.type }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, existing.id), inArray(schema.sessionEvents.type, ["session.created", "user.message"]), ), ) .orderBy(asc(schema.sessionEvents.sequence)) .limit(2); const createdEvent = startEvents.find((event) => event.type === "session.created"); const initialUserEvent = startEvents.find((event) => event.type === "user.message"); const grouped = await sessionMcpServerMetadataForSessions(scopedDb, input.workspaceId, [ existing.id, ]); const session = await mapSessionWithControl( scopedDb, existing, grouped.get(existing.id) ?? [], ); if (!createdEvent) { return { outcome: "pending", session }; } const [initialTurn] = await scopedDb .select({ id: schema.sessionTurns.id, status: schema.sessionTurns.status, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, existing.id), initialUserEvent ? eq(schema.sessionTurns.triggerEventId, initialUserEvent.id) : sql`false`, ), ) .limit(1); const temporalWorkflowId = existing.temporalWorkflowId ?? `session-${existing.id}`; if (existing.status === "cancelled") { return { outcome: "session", session: { ...session, initialTurnId: initialTurn?.id ?? null }, temporalWorkflowId, workflowWakeRevision: null, changed: false, }; } if (input.deferInitialTurn === true) { return { outcome: "session", session: { ...session, initialTurnId: initialTurn?.id ?? null }, temporalWorkflowId, workflowWakeRevision: null, changed: false, }; } if (!initialTurn) return null; const workflowWakeRevision = initialTurn.status === "queued" && session.effectiveControl.state === "active" ? await registerSessionWorkflowWakeInTransaction(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: existing.id, temporalWorkflowId, reason: "initial_session", }) : null; return { outcome: "session", session: { ...session, initialTurnId: initialTurn.id }, temporalWorkflowId, workflowWakeRevision, changed: workflowWakeRevision !== null, }; }, ); } /** Read the canonical sequence without materializing the session presentation. */ export async function getSessionEventSequence( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ compatibilitySequence: schema.sessions.lastSequence, lastSequence: schema.sessionEventCursors.lastSequence, }) .from(schema.sessions) .leftJoin( schema.sessionEventCursors, and( eq(schema.sessionEventCursors.sessionId, schema.sessions.id), eq(schema.sessionEventCursors.accountId, schema.sessions.accountId), eq(schema.sessionEventCursors.workspaceId, schema.sessions.workspaceId), ), ) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!row) return null; if (row.lastSequence === null || row.lastSequence < row.compatibilitySequence) { throw new Error(`Session event cursor invariant failed for session ${sessionId}`); } return row.lastSequence; }); } /** Who can open a chat: the workspace, or only its owner. Null when it does not exist. */ export async function getSessionVisibility( db: Database, workspaceId: string, sessionId: string, ): Promise<"workspace_shared" | "user_private" | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ visibility: schema.sessions.visibility }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); const visibility = row?.visibility ?? null; return visibility === "workspace_shared" || visibility === "user_private" ? visibility : null; }); } export async function getSession( db: Database, workspaceId: string, sessionId: string, ): Promise { return readSession(db, workspaceId, sessionId, "full"); } /** Fresh admission read; retain canonical control/policy/row validation without UI decorations. */ export async function getSessionModelGate( db: Database, workspaceId: string, sessionId: string, ): Promise | null> { const session = await readSession(db, workspaceId, sessionId, "model_gate"); return session ? { model: session.model, codexCompactionMode: session.codexCompactionMode } : null; } async function readSession( db: Database, workspaceId: string, sessionId: string, presentation: "full" | "model_gate", ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { // The model gate returns only the model fields, so it leaves the Skill // folders unread; a full read takes them from the same statement. const sessionWhere = and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ); const [row] = presentation === "full" ? await scopedDb .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where(sessionWhere) .limit(1) : await scopedDb .select() .from(schema.sessions) .where(sessionWhere) .limit(1) .then((rows) => rows.map((sessionRow) => ({ ...sessionRow, skills: [] }))); if (!row) return null; // mapSessionWithControl applies the effective policy after loading control. // Do not perform the same policy projection twice in this scoped read. const [session] = await canonicalSessionRowsFromEventCursors( scopedDb, workspaceId, [row], false, ); if (!session) throw new Error(`Session event cursor missing for session ${row.id}`); const grouped = presentation === "full" ? await sessionMcpServerMetadataForSessions(scopedDb, workspaceId, [row.id]) : null; return await mapSessionWithControl( scopedDb, session, grouped?.get(row.id) ?? [], undefined, undefined, undefined, undefined, undefined, presentation, ); }); } export type DiscardUninitializedSessionShellResult = | "discarded" | "initialized" | "keyed" | "not_found" | "referenced"; /** * Remove a just-created session shell whose start failed before the atomic * initializer committed its first event or turn. * * Session creation commits the shell first and initializes it in a later * transaction. When that second step fails for a create without an * idempotency key, the caller receives an error and has no way to resume * that session, so the bare row must not stay visible as a queued session * that nothing will ever run. A keyed shell is kept, because a retry with the * same key repairs it with the parameters it was first accepted with, unless * `discardKeyed` says the server refused its start: then there is nothing to * repair, and 1501's definer deletes it together with the key's guard row, so * a retry with that key evaluates the request again. Until that definer is * granted a refused keyed shell is kept too. The row lock serializes with the * initializer, so a shell that gained any event or turn (including an * outcome-unknown initializer commit) is left untouched. */ export async function discardUninitializedSessionShell( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; discardKeyed?: boolean }, ): Promise { try { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockWorkspaceInferenceControl(tx, input.workspaceId, "share"); // Read the key without a row lock: a keyed shell is locked only // after its key's admission lock, as keyed creates take them. const [keyed] = await tx .select({ createIdempotencyKey: schema.sessions.createIdempotencyKey }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!keyed) return "not_found" as const; if (keyed.createIdempotencyKey !== null) { if (input.discardKeyed !== true) return "keyed" as const; return await discardRefusedKeyedSessionShell(tx, input); } const [shell] = await tx .select({ id: schema.sessions.id, lastSequence: schema.sessions.lastSequence, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("update") .limit(1); if (!shell) return "not_found" as const; if (shell.lastSequence !== 0) return "initialized" as const; const [[event], [turn], [child]] = await Promise.all([ tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), ), ) .limit(1), tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), ), ) .limit(1), tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.parentSessionId, input.sessionId), ), ) .limit(1), ]); if (event || turn || child) return "initialized" as const; const deleted = await tx .delete(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .returning({ id: schema.sessions.id }); return deleted.length === 1 ? ("discarded" as const) : ("not_found" as const); }), ); } catch (error) { // A durable reference that deliberately restricts deletion (for example a // scheduled run bound to this session) keeps the shell; its owner settles it. const code = typeof error === "object" && error && "code" in error ? (error as { code?: unknown }).code : undefined; const causeCode = typeof error === "object" && error && "cause" in error ? ((error as { cause?: { code?: unknown } }).cause?.code ?? undefined) : undefined; if (code === "23503" || causeCode === "23503") return "referenced"; throw error; } } const DISCARD_REFUSED_SESSION_CREATE_ROUTINE = "opengeni_private.discard_refused_session_create_v1(uuid, uuid)"; /** * Delete a refused keyed shell and release its key through 1501's definer (the * runtime cannot write the key's guard row). While the definer is withheld the * shell is kept, as before. */ async function discardRefusedKeyedSessionShell( tx: Database, input: { workspaceId: string; sessionId: string }, ): Promise { const [privilege] = await rawRows<{ granted: boolean | null }>( tx, sql`select has_function_privilege( to_regprocedure(${DISCARD_REFUSED_SESSION_CREATE_ROUTINE})::oid, 'EXECUTE') as granted`, ); if (privilege?.granted !== true) return "keyed"; const [row] = await rawRows<{ result: string }>( tx, sql`select opengeni_private.discard_refused_session_create_v1( ${input.workspaceId}::uuid, ${input.sessionId}::uuid) as result`, ); switch (row?.result) { case "discarded": case "initialized": case "not_found": return row.result; default: throw new Error(`unexpected refused session create discard result: ${row?.result}`); } } export type DeleteSessionTreeIfQuiescentResult = | { status: "deleted"; deletedSessionCount: number } | { status: | "not_found" | "not_root" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes" | "externally_referenced"; }; /** * Permanently delete one complete root session tree after proving that no * runtime or provider-side owner can still act on it. * * The workspace-control and tree row locks fence new sessions and concurrent * lifecycle changes. Session-owned evidence follows the migration-owned * cascade; immutable workspace-level provenance and independent forks * deliberately retain RESTRICT and surface `externally_referenced` instead of * being orphaned. */ export async function deleteSessionTreeIfQuiescent( db: Database, input: { workspaceId: string; subjectId: string; sessionId: string; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. * Exceeding it throws `WorkspaceControlBusyError` before any row is read. */ controlLockTimeoutMs?: number; }, ): Promise { try { return await withWorkspaceSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Match the canonical session-control lock prefix. Session creation // takes this row FOR SHARE, so the update lock also fences a new // descendant or shared-sandbox peer from appearing after our tree // and group checks. await lockWorkspaceInferenceControl(tx, input.workspaceId, "update", { ...(input.controlLockTimeoutMs !== undefined ? { lockTimeoutMs: input.controlLockTimeoutMs } : {}), }); const [root] = await tx .select({ id: schema.sessions.id, parentSessionId: schema.sessions.parentSessionId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("update", { noWait: true }) .limit(1); if (!root) return { status: "not_found" as const }; if (root.parentSessionId !== null) return { status: "not_root" as const }; const tree = await tx .select({ id: schema.sessions.id, status: schema.sessions.status, sandboxGroupId: schema.sessions.sandboxGroupId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.rootSessionId, input.sessionId), ), ) .for("update", { noWait: true }); const sessionIds = tree.map((session) => session.id); const groupIds = [...new Set(tree.map((session) => session.sandboxGroupId))]; if ( tree.some((session) => ["queued", "running", "requires_action", "recovering", "waiting_capacity"].includes( session.status, ), ) ) { return { status: "active_sessions" as const }; } const [liveAttempts, activeVideoGenerations, externalForks, sharedGroups] = await Promise.all([ tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), inArray(schema.sessionTurnAttempts.sessionId, sessionIds), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .for("update", { noWait: true }), tx .select({ id: schema.videoGenerationOperations.id }) .from(schema.videoGenerationOperations) .where( and( eq(schema.videoGenerationOperations.workspaceId, input.workspaceId), inArray(schema.videoGenerationOperations.sessionId, sessionIds), inArray(schema.videoGenerationOperations.status, [ "preparing", "prepared", "accepted", "submission_uncertain", "provider_started", "retaining", ]), ), ) .for("update", { noWait: true }), tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), inArray(schema.sessions.forkedFromSessionId, sessionIds), notInArray(schema.sessions.id, sessionIds), ), ) .limit(1), tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), inArray(schema.sessions.sandboxGroupId, groupIds), notInArray(schema.sessions.id, sessionIds), ), ) .limit(1), ]); if (liveAttempts.length > 0) return { status: "active_sessions" as const }; if (activeVideoGenerations.length > 0) { return { status: "active_video_generations" as const }; } if (externalForks.length > 0 || sharedGroups.length > 0) { return { status: "externally_referenced" as const }; } // A command already asked to stop on one of this tree's own compute // sandboxes does not hold the deletion: ending the group deletes // that sandbox, which ends the command physically, and the lease // checks below keep the tree until the sandbox is gone. const ownComputeEnrollments = tx .select({ id: schema.enrollments.id }) .from(schema.enrollments) .where( and( eq(schema.enrollments.kind, "sandbox"), inArray(schema.enrollments.sandboxGroupId, groupIds), ), ); const activeBackgroundCommands = await tx .select({ id: schema.sessionBackgroundCommands.id }) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), inArray(schema.sessionBackgroundCommands.sessionId, sessionIds), or( eq(schema.sessionBackgroundCommands.state, "running"), and( eq(schema.sessionBackgroundCommands.state, "stopping"), or( isNull(schema.sessionBackgroundCommands.enrollmentId), notInArray( schema.sessionBackgroundCommands.enrollmentId, ownComputeEnrollments, ), ), ), ), ), ) .for("update", { noWait: true }); if (activeBackgroundCommands.length > 0) { return { status: "active_background_commands" as const }; } const leases = await tx .select({ id: schema.sandboxLeases.id, liveness: schema.sandboxLeases.liveness, refcount: schema.sandboxLeases.refcount, turnHolders: schema.sandboxLeases.turnHolders, viewerHolders: schema.sandboxLeases.viewerHolders, instanceId: schema.sandboxLeases.instanceId, archiveCaptureId: schema.sandboxLeases.archiveCaptureId, reaperHoldId: schema.sandboxLeases.reaperHoldId, rotationRequestedAt: schema.sandboxLeases.rotationRequestedAt, providerDeadlineAt: schema.sandboxLeases.providerDeadlineAt, }) .from(schema.sandboxLeases) .where( and( eq(schema.sandboxLeases.workspaceId, input.workspaceId), inArray(schema.sandboxLeases.sandboxGroupId, groupIds), ), ) .for("update", { noWait: true }); // A compute sandbox stays warm while idle; deleting the chat ends its // group, so ask the reaper to tear it down now. The caller retries // while it shuts down, as for any live sandbox. await requestComputeGroupEndTx(tx, { workspaceId: input.workspaceId, sandboxGroupIds: groupIds, }); if ( leases.some( (lease) => lease.liveness !== "cold" || lease.refcount !== 0 || lease.turnHolders !== 0 || lease.viewerHolders !== 0 || lease.instanceId !== null || lease.archiveCaptureId !== null || lease.reaperHoldId !== null || lease.rotationRequestedAt !== null || lease.providerDeadlineAt !== null, ) ) { return { status: "live_sandboxes" as const }; } const leaseIds = leases.map((lease) => lease.id); if (leaseIds.length > 0) { const [holders, unsettledAdmissions, activeProcesses, openPtys] = await Promise.all([ tx .select({ id: schema.sandboxLeaseHolders.id }) .from(schema.sandboxLeaseHolders) .where(inArray(schema.sandboxLeaseHolders.leaseId, leaseIds)) .for("update", { noWait: true }), tx .select({ id: schema.sandboxWorkspaceMutationAdmissions.id }) .from(schema.sandboxWorkspaceMutationAdmissions) .where( and( inArray(schema.sandboxWorkspaceMutationAdmissions.leaseId, leaseIds), isNull(schema.sandboxWorkspaceMutationAdmissions.settledAt), ), ) .for("update", { noWait: true }), tx .select({ id: schema.sandboxRetainedProcesses.id }) .from(schema.sandboxRetainedProcesses) .where( and( inArray(schema.sandboxRetainedProcesses.leaseId, leaseIds), retainedProcessEvidenceKeptSql(sql`sandbox_retained_processes`), ), ) .for("update", { noWait: true }), tx .select({ id: schema.sandboxPtySessions.id }) .from(schema.sandboxPtySessions) .where( and( inArray(schema.sandboxPtySessions.sessionId, sessionIds), eq(schema.sandboxPtySessions.status, "open"), ), ) .for("update", { noWait: true }), ]); if ( holders.length > 0 || unsettledAdmissions.length > 0 || activeProcesses.length > 0 || openPtys.length > 0 ) { return { status: "live_sandboxes" as const }; } await deleteSettledRetainedProcessesOfLeasesTx( tx, sql`(${sql.join( leaseIds.map((id) => sql`${id}::uuid`), sql`, `, )})`, ); await tx.delete(schema.sandboxLeases).where(inArray(schema.sandboxLeases.id, leaseIds)); } const deleted = await tx .delete(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .returning({ id: schema.sessions.id }); if (deleted.length !== 1) return { status: "not_found" as const }; return { status: "deleted" as const, deletedSessionCount: sessionIds.length, }; }), ); } catch (error) { let current: unknown = error; const visited = new Set(); for (let depth = 0; depth < 8 && current && !visited.has(current); depth += 1) { visited.add(current); const code = typeof current === "object" && "code" in current ? (current as { code?: unknown }).code : undefined; // A bounded control-prefix wait surfaces as `WorkspaceControlBusyError` // (code WORKSPACE_CONTROL_BUSY) with no `cause`, so the only 55P03 that // reaches this chain is the NOWAIT tree lock below: live sandbox activity. if (code === "55P03") return { status: "live_sandboxes" }; if (code === "23503" || code === "42501" || code === "55000") { return { status: "externally_referenced" }; } current = typeof current === "object" && "cause" in current ? (current as { cause?: unknown }).cause : undefined; } throw error; } } /** * The frozen agent-access facts of one session (migration 0427). Together * with `rootSessionId` these are everything the core seam needs to decide * whether one live agent attempt may reach another session. */ export type SessionAccessProjection = { sessionId: string; rootSessionId: string; agentAccess: SessionAgentAccess; scopeSubjectId: SessionScopeSubjectId | null; memoryScope: SessionMemoryScope; }; export type SessionAuthorityProjection = SessionAccessProjection & { authorityEpoch: number; visibility: "user_private" | "workspace_shared"; ownerSubjectId: string | null; siteId: string | null; siteAccessRootId: string | null; siteViewerPrincipal: string | null; siteOwnerSubjectId: string | null; }; type SessionAccessRow = Pick< typeof schema.sessions.$inferSelect, "agentAccess" | "scopeSubjectId" | "memoryScope" >; function sessionAgentAccessFromRow(row: Pick): SessionAgentAccess { return row.agentAccess === "session" || row.agentAccess === "user" ? row.agentAccess : "workspace"; } function sessionEndUserFromRow( row: Pick, ): SessionScopeSubjectId | null { return typeof row.scopeSubjectId === "string" && /^(?:user:|external_user:)/u.test(row.scopeSubjectId) ? row.scopeSubjectId : null; } function sessionMemoryScopeFromRow(row: Pick): SessionMemoryScope { // Legacy task-local Memory is no longer active. Never widen it to workspace. if (row.memoryScope === "session") return "off"; return row.memoryScope === "user" || row.memoryScope === "off" ? row.memoryScope : "workspace"; } export async function getSessionAuthorityProjection( db: Database, workspaceId: string, sessionId: string, ): Promise { return ( (await getSessionAuthorityProjections(db, workspaceId, [sessionId])).values().next().value ?? null ); } /** One live RLS read for a response window; absent and hidden rows stay absent. */ export async function getSessionAuthorityProjections( db: Database, workspaceId: string, sessionIds: readonly string[], ): Promise> { if (sessionIds.length === 0) return new Map(); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ sessionId: schema.sessions.id, rootSessionId: schema.sessions.rootSessionId, visibility: schema.sessions.visibility, authorityEpoch: schema.sessions.authorityEpoch, ownerSubjectId: schema.sessions.ownerSubjectId, siteId: schema.sessions.siteId, siteAccessRootId: schema.sessions.siteAccessRootId, siteViewerPrincipal: schema.sessions.siteViewerPrincipal, siteOwnerSubjectId: schema.sessions.siteOwnerSubjectId, agentAccess: schema.sessions.agentAccess, scopeSubjectId: schema.sessions.scopeSubjectId, memoryScope: schema.sessions.memoryScope, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), inArray(schema.sessions.id, [...new Set(sessionIds)]), ), ); return new Map( rows.map((row) => [ row.sessionId, { sessionId: row.sessionId, authorityEpoch: row.authorityEpoch, rootSessionId: row.rootSessionId, visibility: row.visibility as SessionAuthorityProjection["visibility"], ownerSubjectId: row.ownerSubjectId ?? null, siteId: row.siteId ?? null, siteAccessRootId: row.siteAccessRootId ?? null, siteViewerPrincipal: row.siteViewerPrincipal ?? null, siteOwnerSubjectId: row.siteOwnerSubjectId ?? null, agentAccess: sessionAgentAccessFromRow(row), scopeSubjectId: sessionEndUserFromRow(row), memoryScope: sessionMemoryScopeFromRow(row), }, ]), ); }); } /** Workspace-RLS read of one session's frozen agent-access and memory scope. */ export async function getSessionAccessProjection( db: Database, workspaceId: string, sessionId: string, ): Promise { const authority = await getSessionAuthorityProjection(db, workspaceId, sessionId); if (!authority) return null; return { sessionId: authority.sessionId, rootSessionId: authority.rootSessionId, agentAccess: authority.agentAccess, scopeSubjectId: authority.scopeSubjectId, memoryScope: authority.memoryScope, }; } /** The caller session and live turn behind one agent attempt's authority. */ export type SessionAuthorizationCallerFacts = { session: { accountId: string; rootSessionId: string; parentSessionId: string | null; agentAccess: SessionAgentAccess; scopeSubjectId: SessionScopeSubjectId | null; } | null; /** * The turn this exact attempt is live on: a claimed or running attempt that * is its turn's active attempt, on the session's active turn, with no * pending interruption and (for a linked external turn) live link * authority. The same fence as `getLiveSessionAttemptTurn`. */ turn: { id: string; executionGeneration: number; initiator: TurnInitiator; initiatorContext: TurnInitiatorContext; initiatingHumanSubjectId: string | null; } | null; }; export type SessionAuthorizationFacts = { /** Null when the target does not exist or the caller's RLS context hides it. */ target: | (SessionAuthorityProjection & { accountId: string; /** The Slack interaction that owns the target's root, when one does. */ slackAccess: { owningSubjectId: string; visibility: SlackInteraction["visibility"] } | null; }) | null; /** Present only when a caller attempt was named. */ caller: SessionAuthorizationCallerFacts | null; }; /** * Everything session authorization reads, in one scoped statement: the target * session's authority projection and Slack ownership, and (for an agent * attempt) the caller session and its live attempt turn. Authorization used to * make five sequential scoped reads (plus the full caller-session projection); * this is one round trip inside one RLS scope, so every fact is read under the * same visibility and the same snapshot. A linked external turn additionally * proves its link is still live, in the same scope. */ export async function getSessionAuthorizationFacts( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; caller?: { sessionId: string; attemptId: string } | undefined; }, ): Promise { const results = await getSessionAuthorizationFactsBatch(db, { ...input, sessionIds: [input.sessionId], }); return results.get(input.sessionId)!; } /** Canonical authorization facts for one bounded response window, not an authority cache. */ export async function getSessionAuthorizationFactsBatch( db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[]; caller?: { sessionId: string; attemptId: string } | undefined; }, ): Promise> { if (input.sessionIds.length === 0) return new Map(); // Parse UUIDs before the RLS relation join. Casting a text anchor in the // join itself prevents keyed access under the security barrier. Ordinality // preserves the caller's original spelling for the result map. const requestedSessionIds = [...new Set(input.sessionIds)]; const callerSessionId = input.caller?.sessionId ?? null; const attemptId = input.caller?.attemptId ?? null; return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await rawRows<{ requested_session_index: number | string; target_id: string | null; target_account_id: string | null; target_root_session_id: string | null; target_visibility: string | null; target_authority_epoch: number | null; target_owner_subject_id: string | null; target_site_id: string | null; target_site_access_root_id: string | null; target_site_viewer_principal: string | null; target_site_owner_subject_id: string | null; target_agent_access: string | null; target_scope_subject_id: string | null; target_memory_scope: string | null; slack_owning_subject_id: string | null; slack_visibility: SlackInteraction["visibility"] | null; caller_account_id: string | null; caller_root_session_id: string | null; caller_parent_session_id: string | null; caller_agent_access: string | null; caller_scope_subject_id: string | null; turn_id: string | null; turn_account_id: string | null; turn_execution_generation: number | null; turn_initiator_kind: string | null; turn_initiator_subject_id: string | null; turn_initiator_context: TurnInitiatorContext | null; turn_initiating_human_subject_id: string | null; turn_link_snapshot: unknown; }>( scopedDb, sql` select anchor.ordinality as requested_session_index, target.id as target_id, target.account_id as target_account_id, target.root_session_id as target_root_session_id, target.visibility as target_visibility, target.authority_epoch as target_authority_epoch, target.owner_subject_id as target_owner_subject_id, target.site_id as target_site_id, target.site_access_root_id as target_site_access_root_id, target.site_viewer_principal as target_site_viewer_principal, target.site_owner_subject_id as target_site_owner_subject_id, target.agent_access as target_agent_access, target.scope_subject_id as target_scope_subject_id, target.memory_scope as target_memory_scope, slack.owning_subject_id as slack_owning_subject_id, slack.visibility as slack_visibility, caller.account_id as caller_account_id, caller.root_session_id as caller_root_session_id, caller.parent_session_id as caller_parent_session_id, caller.agent_access as caller_agent_access, caller.scope_subject_id as caller_scope_subject_id, turn.id as turn_id, turn.account_id as turn_account_id, turn.execution_generation as turn_execution_generation, turn.initiator_kind as turn_initiator_kind, turn.initiator_subject_id as turn_initiator_subject_id, turn.initiator_context as turn_initiator_context, turn.initiating_human_subject_id as turn_initiating_human_subject_id, link.canonical_snapshot as turn_link_snapshot from unnest(array[${sql.join( requestedSessionIds.map((id) => sql`${id}`), sql`, `, )}]::uuid[]) with ordinality as anchor(session_id, ordinality) left join ${schema.sessions} target on target.workspace_id = ${input.workspaceId} and target.id = anchor.session_id left join ${schema.slackInteractions} slack on slack.account_id = ${input.accountId} and slack.workspace_id = ${input.workspaceId} and slack.session_reservation_id = target.root_session_id and target.account_id = ${input.accountId} left join ${schema.sessions} caller on ${callerSessionId}::uuid is not null and caller.workspace_id = ${input.workspaceId} and caller.id = ${callerSessionId}::uuid left join ${schema.sessionTurnAttempts} attempt on attempt.workspace_id = ${input.workspaceId} and attempt.session_id = caller.id and attempt.id = ${attemptId}::uuid and attempt.state in ('claimed', 'running') and not exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = ${input.workspaceId} and interruption.attempt_id = ${attemptId}::uuid and interruption.state in ('pending', 'delivered', 'acknowledged') ) left join ${schema.sessionTurns} turn on turn.workspace_id = attempt.workspace_id and turn.id = attempt.turn_id and turn.active_attempt_id = attempt.id and turn.id = caller.active_turn_id and turn.status in ('running', 'requires_action', 'recovering', 'waiting_capacity') left join external_link_turn_authorities link on link.account_id = turn.account_id and link.workspace_id = turn.workspace_id and link.turn_id = turn.id `, ); const results = new Map(); // Linked-identity checks may create savepoints on this same scoped handle. // Never overlap them, and keep each check live rather than caching it. for (const row of rows) { const requestedSessionId = requestedSessionIds[Number(row.requested_session_index) - 1]!; const target: SessionAuthorizationFacts["target"] = row?.target_id && row.target_account_id && row.target_root_session_id ? { sessionId: row.target_id, accountId: row.target_account_id, authorityEpoch: Number(row.target_authority_epoch), rootSessionId: row.target_root_session_id, visibility: row.target_visibility as SessionAuthorityProjection["visibility"], ownerSubjectId: row.target_owner_subject_id ?? null, siteId: row.target_site_id ?? null, siteAccessRootId: row.target_site_access_root_id ?? null, siteViewerPrincipal: row.target_site_viewer_principal ?? null, siteOwnerSubjectId: row.target_site_owner_subject_id ?? null, agentAccess: sessionAgentAccessFromRow({ agentAccess: row.target_agent_access ?? "", }), scopeSubjectId: sessionEndUserFromRow({ scopeSubjectId: row.target_scope_subject_id, }), memoryScope: sessionMemoryScopeFromRow({ memoryScope: row.target_memory_scope ?? "", }), slackAccess: row.slack_owning_subject_id && row.slack_visibility ? { owningSubjectId: row.slack_owning_subject_id, visibility: row.slack_visibility, } : null, } : null; if (!input.caller) { results.set(requestedSessionId, { target, caller: null }); continue; } const session: SessionAuthorizationCallerFacts["session"] = row?.caller_account_id && row.caller_root_session_id ? { accountId: row.caller_account_id, rootSessionId: row.caller_root_session_id, parentSessionId: row.caller_parent_session_id ?? null, agentAccess: sessionAgentAccessFromRow({ agentAccess: row.caller_agent_access ?? "", }), scopeSubjectId: sessionEndUserFromRow({ scopeSubjectId: row.caller_scope_subject_id, }), } : null; let turn: SessionAuthorizationCallerFacts["turn"] = null; if ( row?.turn_id && row.turn_execution_generation !== null && row.turn_initiator_kind !== null && row.turn_initiator_subject_id !== null && // A linked external turn keeps its authority only while the link is live. (row.turn_link_snapshot === null || (await externalLinkWorkSnapshotIsLive(scopedDb, row.turn_link_snapshot))) ) { const initiatorContext = row.turn_initiator_context ?? {}; turn = { id: row.turn_id, executionGeneration: Number(row.turn_execution_generation), initiator: initiatorFromStorage( row.turn_initiator_kind, row.turn_initiator_subject_id, initiatorContext, ), initiatorContext, initiatingHumanSubjectId: row.turn_initiating_human_subject_id ?? null, }; } results.set(requestedSessionId, { target, caller: { session, turn } }); } return results; }); } /** * The typed Memory selector an agent on this session reads and writes. The * user subject comes from the verified active execution, not a conversation * label or its original creator. Task notes own temporary tree-local data. * Null when the session does not exist in the workspace. */ export async function resolveSessionMemoryAgentScope( db: Database, workspaceId: string, sessionId: string, caller?: { turnId?: unknown; attemptId?: unknown; executionGeneration?: unknown }, ): Promise { const access = await getSessionAccessProjection(db, workspaceId, sessionId); if (!access) return null; if (access.memoryScope === "user") { const turn = await getActiveSessionTurnForExecution(db, workspaceId, sessionId); const subjectId = turn?.initiatingHumanSubjectId ?? (turn?.initiator.kind === "subject" ? turn.initiator.subjectId : null); if ( !turn || !caller || turn.id !== caller.turnId || turn.activeAttemptId !== caller.attemptId || turn.executionGeneration !== caller.executionGeneration || !subjectId || !/^(?:user:|external_user:)/u.test(subjectId) ) { return { mode: "off", userSubjectId: null, rootSessionId: access.rootSessionId }; } return memoryAgentScopeForSessionAccess({ ...access, scopeSubjectId: subjectId }); } return memoryAgentScopeForSessionAccess(access); } export function memoryAgentScopeForSessionAccess( access: Pick, ): MemoryAgentScope { return { mode: access.memoryScope, userSubjectId: access.scopeSubjectId, rootSessionId: access.rootSessionId, }; } async function personalConnectionDelegationsForTurnInTransaction( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { const [row] = await db .select({ delegations: schema.sessionTurns.personalConnectionDelegations }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, turnId), ), ) .limit(1); return row ? parsedPersonalConnectionDelegations( row.delegations, `session_turns:${workspaceId}:${sessionId}:${turnId}`, ) : []; } async function mcpAccountBindingsForTurnInTransaction( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { const [row] = await db .select({ bindings: schema.sessionTurns.mcpAccountBindings }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, turnId), ), ) .limit(1); if (!row) { throw new SessionControlInvariantError( `Accepted MCP account authority turn not found: ${sessionId}/${turnId}`, ); } return parseAcceptedMcpAccountBindings(row.bindings); } export async function getSessionTurnMcpAccountBindings( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls( db, workspaceId, async (scopedDb) => await mcpAccountBindingsForTurnInTransaction(scopedDb, workspaceId, sessionId, turnId), ); } /** The exact turn's account intent; null for a turn accepted before intent existed. */ export async function getSessionTurnConnectionAccountIntent( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ intent: schema.sessionTurns.connectionAccountIntent }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, turnId), ), ) .limit(1); if (!row) { throw new SessionControlInvariantError( `Accepted connection account intent turn not found: ${sessionId}/${turnId}`, ); } return parseConnectionAccountIntent(row.intent); }); } export async function getSessionParentMcpAccountBindings( db: Database, workspaceId: string, childSessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [child] = await scopedDb .select({ parentSessionId: schema.sessions.parentSessionId, parentTurnId: schema.sessions.parentTurnId, }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, childSessionId)), ) .limit(1); if (!child?.parentSessionId || !child.parentTurnId) return null; return await mcpAccountBindingsForTurnInTransaction( scopedDb, workspaceId, child.parentSessionId, child.parentTurnId, ); }); } export async function getSessionTurnXaiProviderAccountAuthoritySnapshot( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return getAcceptedSubscriptionTurnAuthority(db, "xai", workspaceId, sessionId, turnId); } export async function getSessionTurnPersonalConnectionDelegations( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls( db, workspaceId, async (scopedDb) => await personalConnectionDelegationsForTurnInTransaction( scopedDb, workspaceId, sessionId, turnId, ), ); } export async function getSessionParentPersonalConnectionDelegations( db: Database, workspaceId: string, childSessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [child] = await scopedDb .select({ parentSessionId: schema.sessions.parentSessionId, parentTurnId: schema.sessions.parentTurnId, }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, childSessionId)), ) .limit(1); if (!child?.parentSessionId || !child.parentTurnId) return []; return await personalConnectionDelegationsForTurnInTransaction( scopedDb, workspaceId, child.parentSessionId, child.parentTurnId, ); }); } export async function getSessionParentXaiProviderAccountAuthority( db: Database, workspaceId: string, childSessionId: string, ): Promise { return getAcceptedSubscriptionParentAuthority(db, "xai", workspaceId, childSessionId); } /** The top of a worker chain, as it runs now. */ export type SessionChainRoot = { rootSessionId: string; /** Whether no person answers in the root chat right now. */ rootUnattended: boolean; /** * Metadata of the exact root turn that started this chain, through each * child's immutable parent turn. Null when that lineage is not recorded * (legacy children) or the turn is gone. */ rootTurnMetadata: Record | null; }; const SESSION_CHAIN_MAX_HOPS = 64; /** * The root chat of a worker session and the root turn that started its chain, * following `parentSessionId`/`parentTurnId`. Null for a top-level session. * Lets a worker act as attended or not the way the chat it works for does: a * worker spawned by a scheduled or unattended run has nobody to answer it. */ export async function getSessionChainRoot( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { let currentId = sessionId; let rootTurnId: string | null = null; for (let hop = 0; hop <= SESSION_CHAIN_MAX_HOPS; hop += 1) { const [row] = await scopedDb .select({ parentSessionId: schema.sessions.parentSessionId, parentTurnId: schema.sessions.parentTurnId, unattendedSetting: schema.sessions.unattendedSetting, metadata: schema.sessions.metadata, forkedFromSessionId: schema.sessions.forkedFromSessionId, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, currentId))) .limit(1); if (!row) { if (currentId === sessionId) return null; throw new Error("session chain root is unavailable"); } if (row.parentSessionId) { rootTurnId = row.parentTurnId; currentId = row.parentSessionId; continue; } if (currentId === sessionId) return null; const [turn] = rootTurnId ? await scopedDb .select({ metadata: schema.sessionTurns.metadata }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, currentId), eq(schema.sessionTurns.id, rootTurnId), ), ) .limit(1) : []; return { rootSessionId: currentId, rootUnattended: resolveSessionUnattended({ setting: (row.unattendedSetting as SessionUnattendedSetting | null) ?? null, createdUnattended: sessionMetadataUnattended(row.metadata), forked: row.forkedFromSessionId !== null, }), rootTurnMetadata: turn?.metadata ?? null, }; } throw new Error("session chain is deeper than any admitted worker chain"); }); } export async function getSessionSpawnDenial( db: Database, workspaceId: string, denialId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionSpawnDenials) .where( and( eq(schema.sessionSpawnDenials.workspaceId, workspaceId), eq(schema.sessionSpawnDenials.id, denialId), ), ) .limit(1); return row ? mapSessionSpawnDenial(row) : null; }); } export async function getSessionSpawnDenialByIdempotencyKey( db: Database, workspaceId: string, createIdempotencyKey: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionSpawnDenials) .where( and( eq(schema.sessionSpawnDenials.workspaceId, workspaceId), eq(schema.sessionSpawnDenials.idempotencyKey, createIdempotencyKey), ), ) .limit(1); return row ? mapSessionSpawnDenial(row) : null; }); } export async function listSessionSpawnDenials( db: Database, workspaceId: string, options: { limit?: number; parentSessionId?: string | null } = {}, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionSpawnDenials) .where( and( eq(schema.sessionSpawnDenials.workspaceId, workspaceId), options.parentSessionId === undefined ? undefined : options.parentSessionId === null ? isNull(schema.sessionSpawnDenials.parentSessionId) : eq(schema.sessionSpawnDenials.parentSessionId, options.parentSessionId), ), ) .orderBy(desc(schema.sessionSpawnDenials.createdAt), desc(schema.sessionSpawnDenials.id)) .limit(Math.max(1, Math.min(options.limit ?? 100, 1000))); return rows.map(mapSessionSpawnDenial); }); } /** * Resolve ANY session that belongs to a shared-sandbox group (addendum 05 §D.3, * stress (e)). Used by the create-session `sandbox:{groupId}` join path to (1) * prove the group exists and (2) inherit its box's (backend, os). * * `workspaceId` is a MANDATORY access boundary, NOT optional: the group uuid is * caller-supplied, so the workspace filter (inside RLS) is what forbids a * cross-workspace join — a foreign group returns null → the caller 404s. The * group uuid itself is never an authorization boundary. Returns the first member * session (any one suffices to read the shared box's backend/os); null when the * group has no session in this workspace. */ export async function getAnySessionInGroup( db: Database, workspaceId: string, sandboxGroupId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.sandboxGroupId, sandboxGroupId), ), ) .limit(1); if (!row) return null; const [session] = await canonicalSessionRowsFromEventCursors(scopedDb, workspaceId, [row]); return session ? await mapSessionWithControl(scopedDb, session) : null; }); } // M3 rig sharing gate: the distinct frozen rig_version_ids across a group's // sessions. The box's rig-baked // setup is fixed at cold-create, so a session joining a group must carry the // SAME rig_version_id (or the join is a genuine shared-state conflict). A null // entry means a rig-less member (compatible only with another rig-less join). export async function listDistinctRigVersionIdsInGroup( db: Database, workspaceId: string, sandboxGroupId: string, ): Promise> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .selectDistinct({ rigVersionId: schema.sessions.rigVersionId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.sandboxGroupId, sandboxGroupId), ), ); return rows.map((r) => r.rigVersionId ?? null); }); } // M3 default-rig fallback: the workspace's default rig id (workspaces.default_rig_id), // read WITHOUT surfacing it through the Workspace contract (a workspace-settings // UI concern deferred to M5). A create with no explicit rigId falls back to this. // Not RLS-scoped for the same reason getWorkspace is not: the workspace row is // addressed by its primary key and the caller already holds the workspace grant. export async function getWorkspaceDefaultRigId( db: Database, workspaceId: string, ): Promise { const [row] = await db .select({ defaultRigId: schema.workspaces.defaultRigId }) .from(schema.workspaces) .where(eq(schema.workspaces.id, workspaceId)) .limit(1); return row?.defaultRigId ?? null; } export type ListSessionsOptions = { limit?: number; parentSessionId?: string | null; }; export type SessionListSnapshotCursor = { kind: "snapshot"; snapshotId: string; offset: number; parentSessionFilter: string; search: string | null; archiveMode: "active" | "archived" | "all"; /** Additive filter identity; absent on legacy snapshot cursors. */ filter?: string; }; export type SessionListKeysetCursor = { /** Xid key for updated ordering, independent of the displayed timestamp. */ sortXid?: string; kind: "keyset"; /** Absent on v2 cursors, which always used session updatedAt. */ sortBy?: "updatedAt" | "archivedAt" | "createdAt" | "name"; /** Decimal cursor generation marker; legacy values restart conservatively. */ snapshotRevision: string; /** Exact PostgreSQL timestamp (including microseconds), or normalized name for name order. */ sortAt: string; id: string; parentSessionFilter: string; search: string | null; archiveMode: "active" | "archived" | "all"; /** Canonical identity for channel, creator, and time-bound filters. */ filter?: string; }; export type SessionListCursor = SessionListSnapshotCursor | SessionListKeysetCursor; export type SessionListFilterOptions = { /** Sessions this viewer may use from this private console Site. */ siteAccessId?: string; /** Sessions created through this published Site, independent of project. */ originSiteId?: string; /** * Ordinary discovery omits conversations that run inside a Site. `include` * lists them as ordinary rows (search, pins, branches); `group` keeps them * out of root rows but counts them in totals and returns `siteGroups`. * Presentation only: native ownership and Site RLS still decide access. */ siteConversations?: "include" | "group"; /** Exact workspace project; null selects unfiled sessions. */ channelId?: string | null; /** Exact frozen creator identity; without a kind, every session the subject created. */ createdBy?: { kind?: "subject" | "service"; subjectId: string }; /** Inclusive activity lower bound. */ updatedFrom?: Date; /** Exclusive activity upper bound. */ updatedBefore?: Date; /** Inclusive creation lower bound. */ createdFrom?: Date; /** Exclusive creation upper bound. */ createdBefore?: Date; /** Restrict root pages to workstreams requiring human attention. */ needsYouOnly?: boolean; /** Only sessions moved to the idle-session archive (read-only). */ contentArchivedOnly?: boolean; /** * Only workstreams the listing subject started or messaged: a session in * the tree was created by them, or they prompted a turn in it directly. */ mineOnly?: boolean; /** Exact opaque end-user label pair (both parts). */ scopeSubjectId?: SessionScopeSubjectId; /** * Only these sessions (at most {@link SESSION_LIST_MAX_SESSION_IDS}). It * narrows the caller's ordinary authorized list and never widens it. */ sessionIds?: readonly string[]; }; /** Upper bound for the session-list `sessionIds` filter. */ export const SESSION_LIST_MAX_SESSION_IDS = 200; export type ListSessionsForSubjectOptions = ListSessionsOptions & SessionListFilterOptions & { subjectId: string; /** Complete metadata totals, independent of pagination. Root or global pin pages. */ includeTotals?: boolean; cursor?: SessionListCursor | undefined; search?: string | undefined; /** Return only the complete personal pin projection; never scan/snapshot ordinary rows. */ pinsOnly?: boolean | undefined; /** Skip pin hydration when the caller reads the pinned section separately. */ includePinned?: boolean | undefined; /** List archived chats instead of active chats. */ archivedOnly?: boolean | undefined; sortBy?: "updatedAt" | "createdAt" | "name" | "archivedAt" | undefined; archiveStatus?: "active" | "archived" | "all" | undefined; /** Return a continuation cursor. Disable for legacy one-page array reads. */ materializeSnapshot?: boolean | undefined; authorizationScope?: SessionAuthorizationListScope | undefined; /** See {@link PersonalWorkspaceOwnerException}. Absent means "no exception". */ personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }; /** * Whether the caller may use the owner-only managed personal-workspace * exception on this request. * * A managed human's personal workspace has NO `workspace_memberships` row * (migration 0219 raises on one), so a bare membership fence denies the one * human who always belongs. The `organization_memberships.personal_workspace_id` * pointer is their whole grant, and * {@link subjectHasLiveWorkspaceAuthorityInScope} is the single resolver for it. * * **This flag is the authorization.** The resolver it gates is not: it answers * "does subject X hold authority here" and establishes nothing about who the * caller is. The exception requires verified native-cookie or dedicated * external owning-user provenance. Unscoped service keys and account or * organization administrators receive no Personal access through it. * A host-signed delegated bearer chooses its own `subjectId`, * `principalKind`, `metadata.delegated`, and `serviceInitiator` claims, so no * inspection of the grant can carry that distinction. Set this ONLY from * `hasVerifiedOwningUserAuthorization` (`@opengeni/core`), * which reflects HOW the request authenticated. Omitted/false keeps the * historical bare-membership fence exactly. */ export type PersonalWorkspaceOwnerException = boolean; export class SessionPinVersionConflictError extends Error { constructor(readonly current: Pick) { super("session pin version conflict"); this.name = "SessionPinVersionConflictError"; } } /** Archived chats leave the Pinned list with every other list, so they cannot be pinned. */ export class SessionArchivedPinError extends Error { readonly code = "session_archived_pin"; constructor() { super("Archived chats can't be pinned."); this.name = "SessionArchivedPinError"; } } export class SessionAttentionVersionConflictError extends Error { constructor(readonly current: Pick) { super("session attention version conflict"); this.name = "SessionAttentionVersionConflictError"; } } export class SessionListCursorError extends Error { constructor(message = "session list cursor is invalid") { super(message); this.name = "SessionListCursorError"; } } export class SessionListCursorExpiredError extends Error { constructor(message = "session list cursor snapshot is missing or expired") { super(message); this.name = "SessionListCursorExpiredError"; } } export class SessionListAccessError extends Error { constructor(message = "workspace access denied") { super(message); this.name = "SessionListAccessError"; } } export class SessionPinAccessError extends Error { constructor(message = "workspace access denied") { super(message); this.name = "SessionPinAccessError"; } } function isPostgresSerializationFailure(error: unknown): boolean { const seen = new Set(); let candidate: unknown = error; while (typeof candidate === "object" && candidate !== null && !seen.has(candidate)) { seen.add(candidate); if ("code" in candidate && (candidate as { code?: unknown }).code === "40001") { return true; } candidate = "cause" in candidate ? (candidate as { cause?: unknown }).cause : undefined; } return false; } function sessionPersonalStateLockKey(workspaceId: string, subjectId: string): string { return `session-personal-state:${workspaceId}:${subjectId}`; } async function lockSessionPersonalStateShared( db: Database, workspaceId: string, subjectId: string, ): Promise { await db.execute( sql`select pg_advisory_xact_lock_shared(hashtextextended(${sessionPersonalStateLockKey(workspaceId, subjectId)}, 0))`, ); } async function lockSessionPersonalStateExclusive( db: Database, workspaceId: string, subjectId: string, ): Promise { await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${sessionPersonalStateLockKey(workspaceId, subjectId)}, 0))`, ); } async function requireSessionPersonalStateWriteAuthority( db: Database, input: { workspaceId: string; subjectId: string; personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }, ): Promise { const [membership] = await db .select({ id: schema.workspaceMemberships.id }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, input.workspaceId), eq(schema.workspaceMemberships.subjectId, input.subjectId), membershipOutsidePersonalWorkspace(), ), ) .limit(1); // Managed personal-workspace owners intentionally have no membership row. // The caller may assert this exception only from canonical managed-cookie // authentication; the live organization-membership pointer remains the // database authority and keeps suspended/foreign subjects denied. if ( !membership && !( input.personalWorkspaceOwnerException === true && (await subjectHasLiveWorkspaceAuthorityInScope(db, { accountId: await accountIdInRlsScope(db), workspaceId: input.workspaceId, subjectId: input.subjectId, })) ) ) { throw new SessionPinAccessError(); } } /** * Archive is for everyone, but like the personal state it replaced only a * workspace member, or a Personal workspace's verified owner, may start or * undo one: a token that merely names someone gets no further. Throws * {@link SessionPinAccessError}. */ export async function requireSessionArchiveMemberAuthority( db: Database, input: { workspaceId: string; subjectId: string; personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }, ): Promise { await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (scopedDb) => requireSessionPersonalStateWriteAuthority(scopedDb as unknown as Database, input), ); } type SessionPinRow = Pick< typeof schema.sessionPins.$inferSelect, | "pinned" | "pinnedAt" | "version" | "acknowledgedSequence" | "manuallyUnreadThrough" | "activelyWorking" | "attentionVersion" | "archived" | "archivedAt" | "archiveVersion" >; function mapSessionPin( row: SessionPinRow | null | undefined, ): Pick { return row ? { pinned: row.pinned, pinnedAt: row.pinnedAt?.toISOString() ?? null, pinVersion: Number(row.version), } : { pinned: false, pinnedAt: null, pinVersion: 0 }; } type SessionRow = typeof schema.sessions.$inferSelect & { currentInputWait?: Session["inputWait"]; /** Who the chat waits on now; see {@link withCurrentSessionWaitingOn}. */ currentWaitingOn?: SessionWaitingOn | null; meaningfulSequence?: number; /** See sessionFailureHandledByParentSql. */ failureHandled?: boolean; /** See sessionQuestionsWithAgentSql. */ questionWithAgent?: boolean; }; /** A session row with its Skill folders, which a complete `Session` carries. */ type SessionRowWithSkills = SessionRow & { skills: unknown[] }; /** * Every `sessions` row column plus the Skill folders, for readers that return * a complete `Session` and must read both in one statement. Every other reader * selects the row without them; see `schema.sessionSkillSets`. */ const sessionRowWithSkillsColumns = { ...getTableColumns(schema.sessions), skills: schema.sessionSkillSets.skills, }; /** * A Session for a response that never carries its Skill folders, such as the * compact chat projection. Its readers leave the folders unread. */ export type SessionWithoutSkills = Omit; /** Whether a complete-Session reader also reads the Skill folders. */ export type SessionSkillsRead = "read" | "omit"; /** * The columns of a complete-Session read. Without the Skill folders, SQL * substitutes an empty set before transfer, so mapping is unchanged and the * stored folders are never detoasted; `omitSessionSkills` then removes the key. */ function sessionReadColumns(skills: SessionSkillsRead) { return skills === "read" ? sessionRowWithSkillsColumns : { ...getTableColumns(schema.sessions), skills: sql`'[]'::jsonb`, }; } function omitSessionSkills(session: S): Omit { const { skills: _unread, ...rest } = session; return rest; } /** * The Skill folders of sessions whose rows the caller already holds locked, so * they match the rows it read without them. Unlocked readers of a complete * Session select `sessionRowWithSkillsColumns` in one statement instead. */ async function readSessionSkills( db: Database, workspaceId: string, sessionIds: readonly string[], ): Promise> { if (sessionIds.length === 0) return new Map(); const rows = await db .select({ id: schema.sessionSkillSets.id, skills: schema.sessionSkillSets.skills }) .from(schema.sessionSkillSets) .where( and( eq(schema.sessionSkillSets.workspaceId, workspaceId), anyOf(schema.sessionSkillSets.id, [...new Set(sessionIds)]), ), ); return new Map(rows.map((row) => [row.id, row.skills])); } /** * Turn sources a person starts: a human or API message, or an operator's * manual `/compact`. Such a turn brings no machine input the agent is waiting * for, so unless it declares its own wait or consumes awaited machine input, * it does not retire the held session wait. Every wait reader filters through * `sessionInputWaitDecidingTurnSql`. */ const SESSION_INPUT_WAIT_PERSON_TURN_SOURCES = [ "user", "api", "compaction", ] as const satisfies readonly SessionTurnSource[]; /** * Machine input a held wait is waiting for: every `immediate` kind. A person's * queued turn claims pending machine input as coalesced context, so a delivered * member of one of these kinds makes that turn retire the wait exactly like the * system turn it replaced. Deferred child notices never end a wait, so a * person's turn that coalesced only those leaves it held. */ const SESSION_INPUT_WAIT_RETIRING_UPDATE_KINDS = ( Object.entries(SESSION_SYSTEM_UPDATE_WAKE_CLASS) as Array<[SessionSystemUpdateKind, string]> ) .filter(([, wakeClass]) => wakeClass === "immediate") .map(([kind]) => kind); /** * The one predicate for "finished turns that decide the session wait": the * declaring turn itself, every turn a person did not start, and a person's turn * that consumed awaited machine input. The newest finished turn matching it * decides the disposition; if that is not the declaring turn, the wait is * superseded. Worker settlement, peek/claim/wake admission, public projections, * and descendant counts all use this so they cannot drift apart. * * A person's turn consumes awaited machine input in two ways: its claim * delivered a pending immediate-class update to it, or its model read a * child's complete answer (`CONSUMED_CHILD_ANSWERS_METADATA_KEY`, or * `CODEMODE_CHILD_ANSWER_READS_METADATA_KEY` for a Codemode read) that is a * part of a child result then superseded as `consumed_by_parent_read`: the * answer, a goal continuation, or an omitted earlier part (see * `childTerminalResultFinalAnswerSequences`). That result never wakes the * parent, so without the second rule the wait would stay held until its * deadline. A part that a completed attempt had already read by the time the * declaring turn finished is not what the wait is for, so re-reading only such * parts leaves the wait held; reading a newer continuation of an answer read * before the wait still retires it. Turns are compared by `finished_at`, the * same order that picks the deciding turn. Only a turn that finished at or * after the declaring turn can outrank it, so the read check runs for those * alone: every wait reader evaluates this for each finished turn, and checking * the whole history would cost a scan of the session per earlier turn. */ function sessionInputWaitDecidingTurnSql( turn: { id: SQLWrapper; source: SQLWrapper; workspaceId: SQLWrapper; sessionId: SQLWrapper; finishedAt: SQLWrapper; metadata: SQLWrapper; }, waitTurnId: SQLWrapper | string, ): SQL { const consumedAnswersKey = CONSUMED_CHILD_ANSWERS_METADATA_KEY; const codemodeReadsKey = CODEMODE_CHILD_ANSWER_READS_METADATA_KEY; const consumedAnswers = (metadata: SQLWrapper) => sql`jsonb_array_elements(case when jsonb_typeof(${metadata} -> ${consumedAnswersKey}) = 'array' then ${metadata} -> ${consumedAnswersKey} else '[]'::jsonb end || case when jsonb_typeof(${metadata} -> ${codemodeReadsKey}) = 'array' then ${metadata} -> ${codemodeReadsKey} else '[]'::jsonb end)`; // By its unique (workspace, id) key: the declaring turn is this session's. const waitDeclaredAt = sql`(select declaring.finished_at from ${schema.sessionTurns} declaring where declaring.workspace_id = ${turn.workspaceId} and declaring.id = ${waitTurnId})`; return sql`(${turn.id} = ${waitTurnId} or ${turn.source} not in (${sql.join( SESSION_INPUT_WAIT_PERSON_TURN_SOURCES.map((source) => sql`${source}`), sql`, `, )}) or exists ( select 1 from ${schema.sessionSystemUpdates} consumed where consumed.workspace_id = ${turn.workspaceId} and consumed.session_id = ${turn.sessionId} and consumed.state = 'delivered' and consumed.delivered_turn_id = ${turn.id} and consumed.kind in (${sql.join( SESSION_INPUT_WAIT_RETIRING_UPDATE_KINDS.map((kind) => sql`${kind}`), sql`, `, )}) ) or ( ${turn.finishedAt} >= ${waitDeclaredAt} and exists ( select 1 from ${schema.sessionSystemUpdates} consumed_read cross join lateral ${consumedAnswers(turn.metadata)} consumed_answer where consumed_read.workspace_id = ${turn.workspaceId} and consumed_read.session_id = ${turn.sessionId} and consumed_read.state = 'superseded' and consumed_read.kind = 'child_terminal_result' and consumed_answer ->> 'childSessionId' = consumed_read.payload ->> 'childSessionId' and ( consumed_answer -> 'sequence' = consumed_read.payload -> 'finalAnswer' -> 'sequence' or consumed_read.payload -> 'finalAnswer' -> 'goalContinuations' @> jsonb_build_array(jsonb_build_object('sequence', consumed_answer -> 'sequence')) or consumed_read.payload -> 'finalAnswer' -> 'omittedSequences' @> jsonb_build_array(consumed_answer -> 'sequence') ) and not exists ( select 1 from ${schema.sessionTurns} earlier cross join lateral ${consumedAnswers(sql`earlier.metadata`)} earlier_answer where earlier.workspace_id = ${turn.workspaceId} and earlier.session_id = ${turn.sessionId} and earlier.finished_at <= ${waitDeclaredAt} and earlier_answer ->> 'childSessionId' = consumed_answer ->> 'childSessionId' and earlier_answer -> 'sequence' = consumed_answer -> 'sequence' and exists ( select 1 from ${schema.sessionTurnAttempts} earlier_attempt where earlier_attempt.workspace_id = earlier.workspace_id and earlier_attempt.id = case when earlier_answer ->> 'attemptId' ~ ${UUID_TEXT_PATTERN_SQL} then (earlier_answer ->> 'attemptId')::uuid end and earlier_attempt.session_id = earlier.session_id and earlier_attempt.turn_id = earlier.id and earlier_attempt.outcome = 'completed' ) ) ) ))`; } /** One bounded query in the caller's RLS scope; never infer waits from history text. */ async function withCurrentSessionInputWait( db: Database, workspaceId: string, rows: readonly Row[], ): Promise { return await withCurrentSessionWaitingOn( db, workspaceId, await withCurrentSessionInputWaitOnly(db, workspaceId, rows), ); } /** * Who each chat waits on now. An open question or approval waits on the * person its turn works for; otherwise the agent's own `set_waiting_on` holds * while the chat is idle and the turn that said it is still its latest, so a * reply, an approval or the agent continuing clears it without a write. Two * bounded queries, only for rows that could be waiting. */ async function withCurrentSessionWaitingOn( db: Database, workspaceId: string, rows: readonly Row[], ): Promise { const inputTurnIds = rows .filter((row) => row.status === "requires_action" && row.activeTurnId) .map((row) => row.activeTurnId!); const agentCandidates = rows.filter( (row) => row.status === "idle" && !row.activeTurnId && row.waitingOn?.turnId, ); if (inputTurnIds.length === 0 && agentCandidates.length === 0) { return rows.map((row) => ({ ...row, currentWaitingOn: null })); } const initiators = new Map(); if (inputTurnIds.length > 0) { const turns = await db .select({ id: schema.sessionTurns.id, subjectId: schema.sessionTurns.initiatingHumanSubjectId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), anyOf(schema.sessionTurns.id, [...new Set(inputTurnIds)]), ), ); for (const turn of turns) initiators.set(turn.id, turn.subjectId ?? null); } const latestTurnBySession = new Map(); if (agentCandidates.length > 0) { const latest = db .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, schema.sessions.id), ), ) .orderBy(desc(schema.sessionTurns.position)) .limit(1) .as("latest_waiting_turn"); const matches = await db .select({ id: schema.sessions.id, turnId: latest.id }) .from(schema.sessions) .leftJoinLateral(latest, sql`true`) .where( and( eq(schema.sessions.workspaceId, workspaceId), anyOf( schema.sessions.id, agentCandidates.map((row) => row.id), ), ), ); for (const match of matches) if (match.turnId) latestTurnBySession.set(match.id, match.turnId); } return rows.map((row) => ({ ...row, currentWaitingOn: currentSessionWaitingOn(row, { initiatorSubjectId: row.activeTurnId ? (initiators.get(row.activeTurnId) ?? null) : null, latestTurnId: latestTurnBySession.get(row.id) ?? null, }), })); } /** * Who one chat waits on, from its row and two facts read for it: the subject * its active turn works for and its latest turn. Exported for tests. */ export function currentSessionWaitingOn( row: Pick, facts: { initiatorSubjectId: string | null; latestTurnId: string | null }, ): SessionWaitingOn | null { if (row.status === "requires_action" && row.activeTurnId) { return { source: "input", person: null, subjectId: facts.initiatorSubjectId, reason: null, since: row.updatedAt.toISOString(), }; } const stored = row.waitingOn; if ( stored?.turnId && row.status === "idle" && !row.activeTurnId && facts.latestTurnId === stored.turnId ) { const { turnId: _turnId, ...waitingOn } = stored; return waitingOn; } return null; } async function withCurrentSessionInputWaitOnly( db: Database, workspaceId: string, rows: readonly Row[], ): Promise { const candidates = rows.filter( (row) => row.status === "idle" && !row.activeTurnId && row.inputWaitTurnId && row.inputWaitUntil, ); if (!candidates.length) return rows.map((row) => ({ ...row, currentInputWait: null })); const matches = await currentSessionInputWaitTurnsQuery( db, workspaceId, candidates.map((row) => row.id), ); const byId = new Map(matches.map((row) => [row.id, row.turnId])); return rows.map((row) => ({ ...row, currentInputWait: row.status === "idle" && !row.activeTurnId && row.inputWaitUntil && row.inputWaitReason && row.inputWaitTurnId && byId.get(row.id) === row.inputWaitTurnId ? { deadlineAt: row.inputWaitUntil.toISOString(), reason: row.inputWaitReason } : null, })); } /** * Each listed session's newest finished turn that decides its held wait. The * lateral walks `session_turns_finished_order_idx` newest-first and stops at * the first match, and probes consumed machine input through * `session_system_updates_delivered_turn_idx`, so a long session costs about * the same as a new one. Call inside the caller's RLS scope. */ export function currentSessionInputWaitTurnsQuery( db: Database, workspaceId: string, sessionIds: readonly string[], ) { const latest = db .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, schema.sessions.id), isNotNull(schema.sessionTurns.finishedAt), sessionInputWaitDecidingTurnSql(schema.sessionTurns, schema.sessions.inputWaitTurnId), ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), ) .limit(1) .as("latest_wait_turn"); return db .select({ id: schema.sessions.id, turnId: latest.id }) .from(schema.sessions) .leftJoinLateral(latest, sql`true`) .where( and(eq(schema.sessions.workspaceId, workspaceId), anyOf(schema.sessions.id, [...sessionIds])), ); } /** * Public sequence remains cursor-authoritative. Attention has its own derived * meaningful frontier; raw deltas and housekeeping must not create unread dots. * The compatibility column may lag raw deltas but cannot lead the durable cursor. */ async function canonicalSessionRowsFromEventCursors( db: Database, workspaceId: string, rows: readonly Row[], includeEffectivePolicy = true, ): Promise { if (rows.length === 0) return []; const sessionIds = [...new Set(rows.map((row) => row.id))]; const cursors = await db .select({ accountId: schema.sessionEventCursors.accountId, workspaceId: schema.sessionEventCursors.workspaceId, sessionId: schema.sessionEventCursors.sessionId, lastSequence: schema.sessionEventCursors.lastSequence, meaningfulSequence: schema.sessionEventCursors.lastMeaningfulSequence, }) .from(schema.sessionEventCursors) .where( and( eq(schema.sessionEventCursors.workspaceId, workspaceId), anyOf(schema.sessionEventCursors.sessionId, sessionIds), ), ); const cursorBySessionId = new Map(cursors.map((cursor) => [cursor.sessionId, cursor])); const handledFailures = await sessionIdsWithHandledFailure(db, workspaceId, rows); const questionsWithAgent = await sessionIdsWithQuestionsWithAgent(db, workspaceId, rows); const canonical = (await withCurrentSessionInputWait(db, workspaceId, rows)).map((row) => { const cursor = cursorBySessionId.get(row.id); if ( !cursor || cursor.accountId !== row.accountId || cursor.workspaceId !== row.workspaceId || cursor.lastSequence < row.lastSequence ) { throw new Error(`Session event cursor invariant failed for session ${row.id}`); } return { ...row, lastSequence: cursor.lastSequence, meaningfulSequence: cursor.meaningfulSequence, ...(handledFailures.has(row.id) ? { failureHandled: true } : {}), ...(questionsWithAgent.has(row.id) ? { questionWithAgent: true } : {}), }; }); return includeEffectivePolicy ? withEffectiveSessionPolicy(db, workspaceId, canonical) : canonical; } function mapSessionAttention( session: Pick, row: SessionPinRow | null | undefined, ): Pick { return row ? { unread: row.manuallyUnreadThrough != null || (session.meaningfulSequence ?? session.lastSequence) > row.acknowledgedSequence, activelyWorking: row.activelyWorking, attentionVersion: Number(row.attentionVersion), } : { // An absent personal row means this subject has never acknowledged a // completion. Existing and newly discovered finished work therefore // remains visible until the member explicitly marks it read. unread: (session.meaningfulSequence ?? session.lastSequence) > 0, activelyWorking: false, attentionVersion: 0, }; } /** * Whether a session row is archived for everyone: archived through the chat's * Archive action (or since migration 1213 by the idle archiver), or stored by * the idle archiver before archived_at existed. */ function sessionArchivedSql(alias: SQL): SQL { return sql`(${alias}.archived_at is not null or ${alias}.content_archive_state is not null)`; } /** When a session row was archived, by {@link sessionArchivedSql}'s rule. */ function sessionArchivedAtSql(alias: SQL): SQL { return sql`coalesce(${alias}.archived_at, ${alias}.content_archived_at, ${alias}.content_archive_started_at)`; } /** * The archive fields a session row does not carry itself: the version of the * retired personal archive (kept for clients that still send it) and, from a * list page, the exact archive time of its keyset. `archived` and `archivedAt` * come from the session row (see mapSession). */ function mapSessionArchive( row: SessionPinRow | null | undefined, ): Pick & Partial> { return { archiveVersion: row ? Number(row.archiveVersion) : 0 }; } /** A session row's archive fields, for everyone (migration 1213). */ function sessionRowArchive( row: Pick< typeof schema.sessions.$inferSelect, "archivedAt" | "contentArchiveState" | "contentArchivedAt" | "contentArchiveStartedAt" >, ): Pick { const archivedAt = row.archivedAt ?? row.contentArchivedAt ?? row.contentArchiveStartedAt; return { archived: row.archivedAt !== null || row.contentArchiveState !== null, archivedAt: archivedAt?.toISOString() ?? null, }; } type SessionTreeStats = NonNullable; type SessionTreeStatsRow = { rootId: string; directChildren: number | string; totalDescendants: number | string; runningDescendants: number | string; queuedDescendants: number | string; waitingDescendants: number | string; attentionDescendants: number | string; pausedDescendants: number | string; pausedWorkDescendants: number | string; failedDescendants: number | string; unreadFailedDescendants: number | string; unreadDescendants: number | string; activelyWorkingDescendants: number | string; attentionSince: Date | string | null; truncated: boolean; }; const SESSION_TREE_STATS_MAX_DESCENDANTS = 1_000; const SESSION_TREE_STATS_MAX_DEPTH = 32; const SESSION_TREE_STATS_MAX_ROOTS = 600; const SESSION_LIST_MAX_PINNED = 100; const EMPTY_SESSION_TREE_STATS: SessionTreeStats = { directChildren: 0, totalDescendants: 0, runningDescendants: 0, queuedDescendants: 0, waitingDescendants: 0, attentionDescendants: 0, pausedDescendants: 0, pausedWorkDescendants: 0, failedDescendants: 0, unreadFailedDescendants: 0, unreadDescendants: 0, activelyWorkingDescendants: 0, attentionSince: null, truncated: false, }; /** * Whether a failed session's failure already belongs to an agent rather than a * person. The check is bound to the failure episode itself: the newest terminal * outbox row the child wrote for its parent (committed in the same transaction * as the failure) must be a failure, and the parent's copy of that exact notice * (same dedupe key) must have been claimed into a parent turn (`delivered`). * The parent agent then owns the follow-up (retry, restart or replace), so the * rail does not ask a person to review it. * * Everything else stays unhandled, so a failure nobody took on keeps its red * marker: a root session; a notice not yet delivered, still pending (parent * paused or not yet run), dropped because the parent was cancelled or archived, * or settled without the parent seeing it (`superseded`, `cancelled`, * `failed`); and a child that finished another turn after that notice (for * example one retired without a new notice), whose newer failure is not the * one the parent saw. Viewer-independent by design. */ function sessionFailureHandledByParentSql( workspaceId: string, sessionId: SQL, parentSessionId: SQL, ): SQL { return sql`(${parentSessionId} is not null and coalesce(( select episode.classification = 'failure' and exists ( select 1 from ${schema.sessionSystemUpdates} notice where notice.workspace_id = ${workspaceId} and notice.session_id = ${parentSessionId} and notice.dedupe_key = episode.dedupe_key and notice.state = 'delivered' ) and not exists ( select 1 from ${schema.sessionTurns} later where later.workspace_id = ${workspaceId} and later.session_id = ${sessionId} and later.finished_at is not null and later.finished_at > episode.created_at -- The failed turn's own notice is keyed by that turn; any other -- turn is newer work. and episode.dedupe_key <> ${childFailedTurnDedupeKeySql(sessionId, sql`later.id`)} ) from ${schema.sessionSystemUpdateOutbox} episode where episode.workspace_id = ${workspaceId} and episode.source_session_id = ${sessionId} and episode.target_session_id = ${parentSessionId} and episode.kind = 'child_terminal_result' order by episode.created_at desc, episode.id desc limit 1 ), false))`; } /** Failed sessions among `rows` whose failure their parent agent consumed. */ async function sessionIdsWithHandledFailure( db: Database, workspaceId: string, rows: readonly Pick[], ): Promise> { const failedChildIds = [ ...new Set( rows.filter((row) => row.status === "failed" && row.parentSessionId).map((row) => row.id), ), ]; if (failedChildIds.length === 0) return new Set(); const handled = await rawRows<{ id: string }>( db, sql` select child.id from ${schema.sessions} child where child.workspace_id = ${workspaceId} and ${anyOf(sql`child.id`, failedChildIds, "uuid")} and child.status = 'failed' and ${sessionFailureHandledByParentSql( workspaceId, sql`child.id`, sql`child.parent_session_id`, )} `, ); return new Set(handled.map((row) => row.id)); } /** * Whether a session waits only on questions still with the agent that * started it (`held_for_agent`, see migration 1553): their notice is on its * way, queued, or in a turn that has not ended, and that agent can act. * Person-facing attention leaves such a session out. */ function sessionQuestionsWithAgentSql(workspaceId: string | SQL, sessionId: SQL): SQL { return sql`(exists ( select 1 from ${schema.sessionHumanInputRequests} asked where asked.workspace_id = ${workspaceId} and asked.session_id = ${sessionId} and asked.status = 'pending' ) and not exists ( select 1 from ${schema.sessionHumanInputRequests} asked where asked.workspace_id = ${workspaceId} and asked.session_id = ${sessionId} and asked.status = 'pending' and not (asked.held_for_agent and exists ( select 1 from ${schema.sessionSystemUpdateOutbox} notice join ${schema.sessions} agent on agent.workspace_id = notice.workspace_id and agent.id = notice.target_session_id left join ${schema.sessionSystemUpdates} received on received.workspace_id = notice.workspace_id and received.session_id = notice.target_session_id and received.dedupe_key = notice.dedupe_key where notice.workspace_id = ${workspaceId} and notice.dedupe_key = ${childRequiresActionDedupeKeySql( sql`asked.session_id`, sql`asked.turn_id`, sql`asked.turn_generation`, )} and agent.status not in ('failed', 'cancelled', 'waiting_capacity') and ( received.state = 'pending' or (received.id is null and notice.status = 'pending') or (received.state = 'delivered' and exists ( select 1 from ${schema.sessionTurns} answering where answering.workspace_id = ${workspaceId} and answering.session_id = notice.target_session_id and answering.id = received.delivered_turn_id and answering.finished_at is null )) ) )) ))`; } /** `requires_action` sessions among `rows` whose questions are with their agent. */ async function sessionIdsWithQuestionsWithAgent( db: Database, workspaceId: string, rows: readonly Pick[], ): Promise> { const waitingChildIds = [ ...new Set( rows .filter((row) => row.status === "requires_action" && row.parentSessionId) .map((row) => row.id), ), ]; if (waitingChildIds.length === 0) return new Set(); const withAgent = await rawRows<{ id: string }>( db, sql` select child.id from ${schema.sessions} child where child.workspace_id = ${workspaceId} and ${anyOf(sql`child.id`, waitingChildIds, "uuid")} and child.status = 'requires_action' and ${sessionQuestionsWithAgentSql(workspaceId, sql`child.id`)} `, ); return new Set(withAgent.map((row) => row.id)); } /** * Remove control metadata derived from sessions other than the exact target. * Effective state and the opaque OCC etag remain usable without exposing * ancestor ids/titles/actors/reasons or descendant settlement facts. */ export function projectEffectiveControlForRelatedAccess( control: Session["effectiveControl"], sessionId: string, access: "target" | "root", ): Session["effectiveControl"] { if (access === "root") return control; const hasHiddenAncestorBlocker = control.blockers.some( (blocker) => blocker.kind === "session" && blocker.sessionId !== sessionId, ); const hiddenAncestorBlocker = hasHiddenAncestorBlocker ? { kind: "session" as const, displayName: "An ancestor session", actor: null, reason: null, changedAt: null, revision: 0, } : null; let includedHiddenAncestor = false; const blockers = control.blockers.flatMap((blocker) => { if (blocker.kind !== "session" || blocker.sessionId === sessionId) return [blocker]; if (!hiddenAncestorBlocker || includedHiddenAncestor) return []; includedHiddenAncestor = true; return [hiddenAncestorBlocker]; }); const primary = control.primaryBlocker; const primaryBlocker = primary?.kind === "session" && primary.sessionId !== sessionId ? hiddenAncestorBlocker : primary; return { ...control, primaryBlocker, blockers, additionalBlockerCount: Math.max(0, blockers.length - 1), resumeOptions: control.state === "paused" ? [ { scope: "selected", targetId: sessionId, selectedStateAfter: "active", impactCopy: "Resume this session without changing other workstreams.", }, ] : [], override: control.override?.rootSessionId === sessionId ? control.override : null, settlement: null, }; } /** * Remove metadata derived from sessions other than the exact authorized * target, including parent identity, policy provenance, and descendant counts. */ export function projectSessionForRelatedAccess( session: Session, access: "target" | "root", ): Session { if (access === "root") return session; // Effective policy can be assembled either before or after this projection. // Hide both provenance carriers so later policy assembly cannot restore an // unauthorized ancestor id. Policy mode/selection/counts remain exact; this // changes only the read projection, never persisted policy or enforcement. const projectPolicyLineage = ( policy: T, ): T => policy.inheritedFromSessionId !== null && policy.inheritedFromSessionId !== session.id ? { ...policy, inheritedFromSessionId: null } : policy; return { ...session, parentSessionId: null, toolPolicy: projectPolicyLineage(session.toolPolicy), ...(session.effectiveToolPolicy === undefined ? {} : { effectiveToolPolicy: projectPolicyLineage(session.effectiveToolPolicy) }), treeStats: EMPTY_SESSION_TREE_STATS, effectiveControl: projectEffectiveControlForRelatedAccess( session.effectiveControl, session.id, access, ), }; } /** * Return bounded descendant aggregates for the bounded set of rows being * painted in the session rail. Each selected root receives an independent * fixed node/depth budget. `truncated=true` makes every count an explicit lower * bound when a deep, wide, overlapping, or cyclic graph reaches that budget. */ export async function sessionTreeStatsForSessions( db: Database, workspaceId: string, rootIds: string[], subjectId?: string, ): Promise> { const uniqueRootIds = [...new Set(rootIds)]; if (uniqueRootIds.length === 0) return new Map(); if (uniqueRootIds.length > SESSION_TREE_STATS_MAX_ROOTS) { throw new RangeError( `Session tree stats projection exceeds ${SESSION_TREE_STATS_MAX_ROOTS} roots`, ); } const rows = await rawRows( db, sql` select root.id as "rootId", stats."directChildren", stats."totalDescendants", stats."runningDescendants", stats."queuedDescendants", stats."waitingDescendants", stats."attentionDescendants", stats."pausedDescendants", stats."pausedWorkDescendants", stats."failedDescendants", stats."unreadFailedDescendants", stats."unreadDescendants", stats."activelyWorkingDescendants", stats."attentionSince", stats.truncated from ${schema.sessions} root join ${schema.sessionEventCursors} root_cursor on root_cursor.account_id = root.account_id and root_cursor.workspace_id = root.workspace_id and root_cursor.session_id = root.id join ${schema.workspaceInferenceControls} workspace_control on workspace_control.workspace_id = root.workspace_id cross join lateral ( -- A sub-chat root inherits its ancestors' pauses. An ancestor's pause -- reaches it unless a subtree resume newer than that pause sits below -- the ancestor; the workspace pause unless one sits anywhere above. with recursive ancestors(id, parent_session_id, override_revision, pause_revision, below, depth) as ( select parent.id, parent.parent_session_id, parent.subtree_run_override_revision, case when parent.direct_control_state = 'paused' then parent.direct_pause_revision end, coalesce(root.subtree_run_override_revision, 0), 1 from ${schema.sessions} parent where parent.workspace_id = ${workspaceId} and parent.id = root.parent_session_id and parent.id <> root.id union all select parent.id, parent.parent_session_id, parent.subtree_run_override_revision, case when parent.direct_control_state = 'paused' then parent.direct_pause_revision end, greatest(ancestors.below, coalesce(ancestors.override_revision, 0)), ancestors.depth + 1 from ancestors join ${schema.sessions} parent on parent.workspace_id = ${workspaceId} and parent.id = ancestors.parent_session_id where ancestors.depth < ${SESSION_TREE_STATS_MAX_DEPTH} and parent.id <> root.id ) select max(pause_revision) filter (where pause_revision >= below) as pause_revision, coalesce(max(coalesce(override_revision, 0)), 0) as override_revision from ancestors ) root_lineage cross join lateral ( -- Every node has exactly one parent, so a walk down child links can -- only revisit its own start node (when that start sits on a legacy -- parent cycle). Excluding the start therefore keeps the walk acyclic -- without carrying a path, and the depth bound caps the work. with recursive descendants( id, parent_session_id, status, active_turn_id, input_wait_until, input_wait_turn_id, awaiting_connection_since, last_sequence, effective_pause_revision, depth ) as ( select root.id, root.parent_session_id, root.status, root.active_turn_id, root.input_wait_until, root.input_wait_turn_id, root.awaiting_connection_since, root_cursor.last_meaningful_sequence, greatest( case when workspace_control.workspace_state = 'paused' and workspace_control.workspace_pause_revision is not null and greatest( coalesce(root.subtree_run_override_revision, 0), root_lineage.override_revision ) <= workspace_control.workspace_pause_revision then workspace_control.workspace_pause_revision else null end, root_lineage.pause_revision, case when root.direct_control_state = 'paused' then root.direct_pause_revision else null end ), 0 union all select child.id, child.parent_session_id, child.status, child.active_turn_id, child.input_wait_until, child.input_wait_turn_id, child.awaiting_connection_since, child_cursor.last_meaningful_sequence, greatest( case -- A subtree resume defeats every inherited pause older than it. -- Preserve only the strongest still-undefeated blocker, then -- apply the child's own pause (which its own override cannot defeat). when descendants.effective_pause_revision is not null and ( child.subtree_run_override_revision is null or child.subtree_run_override_revision <= descendants.effective_pause_revision ) then descendants.effective_pause_revision else null end, case when child.direct_control_state = 'paused' then child.direct_pause_revision else null end ), descendants.depth + 1 from descendants join ${schema.sessions} child on child.workspace_id = ${workspaceId} and child.parent_session_id = descendants.id join ${schema.sessionEventCursors} child_cursor on child_cursor.account_id = child.account_id and child_cursor.workspace_id = child.workspace_id and child_cursor.session_id = child.id where descendants.depth < ${SESSION_TREE_STATS_MAX_DEPTH} and child.id <> root.id ), bounded as materialized ( -- PostgreSQL evaluates the recursive producer only as far as this -- unsorted LIMIT is consumed. One extra descendant is lookahead. select id, parent_session_id, status, active_turn_id, input_wait_until, input_wait_turn_id, awaiting_connection_since, last_sequence, effective_pause_revision, depth from descendants limit ${SESSION_TREE_STATS_MAX_DESCENDANTS + 2} ), numbered as ( select bounded.*, row_number() over () as ordinal from bounded ), counted as ( -- The subject's personal state is read once per counted descendant. select numbered.*, personal.session_id is not null and personal.actively_working as actively_working, ${subjectId ?? null}::text is not null and numbered.last_sequence > coalesce( case when personal.manually_unread_through is not null then -1 else personal.acknowledged_sequence end, 0 ) as unread, -- Probed only for unread failed descendants, the only ones a -- handled verdict changes; see sessionFailureHandledByParentSql. case when numbered.status = 'failed' and ${subjectId ?? null}::text is not null and numbered.last_sequence > coalesce( case when personal.manually_unread_through is not null then -1 else personal.acknowledged_sequence end, 0 ) then ${sessionFailureHandledByParentSql( workspaceId, sql`numbered.id`, sql`numbered.parent_session_id`, )} else false end as failure_handled, case when numbered.status = 'requires_action' then not ${sessionQuestionsWithAgentSql( workspaceId, sql`numbered.id`, )} else false end as awaits_person from numbered left join ${schema.sessionPins} personal on ${subjectId ?? null}::text is not null and personal.workspace_id = ${workspaceId} and personal.subject_id = ${subjectId ?? null} and personal.session_id = numbered.id where numbered.ordinal <= ${SESSION_TREE_STATS_MAX_DESCENDANTS + 1} and numbered.depth > 0 ) select count(*) filter (where depth = 1)::int as "directChildren", count(*)::int as "totalDescendants", count(*) filter ( where effective_pause_revision is null and status in ('running', 'recovering') )::int as "runningDescendants", count(*) filter ( where effective_pause_revision is null and status in ('queued', 'waiting_capacity') )::int as "queuedDescendants", count(*) filter ( where status = 'idle' and effective_pause_revision is null and active_turn_id is null and input_wait_until is not null and input_wait_turn_id = ( select finished.id from ${schema.sessionTurns} finished where finished.workspace_id = ${workspaceId} and finished.session_id = counted.id and finished.finished_at is not null and ${sessionInputWaitDecidingTurnSql( { id: sql`finished.id`, source: sql`finished.source`, workspaceId: sql`finished.workspace_id`, sessionId: sql`finished.session_id`, finishedAt: sql`finished.finished_at`, metadata: sql`finished.metadata`, }, sql`counted.input_wait_turn_id`, )} order by finished.finished_at desc, finished.position desc, finished.created_at desc limit 1 ) )::int as "waitingDescendants", count(*) filter ( where awaits_person or ${sessionAwaitsConnectionSql(sql`status`, sql`awaiting_connection_since`)} )::int as "attentionDescendants", count(*) filter (where effective_pause_revision is not null)::int as "pausedDescendants", count(*) filter ( where effective_pause_revision is not null and status not in ('requires_action', 'cancelled', 'failed') and ( active_turn_id is not null or status in ('running', 'recovering', 'queued', 'waiting_capacity') ) )::int as "pausedWorkDescendants", count(*) filter (where status = 'failed')::int as "failedDescendants", -- A failure its parent agent already consumed is that agent's to handle, -- including anything the failed session logs after it (for example a -- late workspace capture): neither asks the person through an ancestor. count(*) filter ( where status = 'failed' and unread and not failure_handled )::int as "unreadFailedDescendants", count(*) filter (where unread and not failure_handled)::int as "unreadDescendants", count(*) filter (where actively_working)::int as "activelyWorkingDescendants", -- Oldest still-open requires_action turn, or connection card wait, -- among the counted attention descendants. The correlated lookup -- runs only for rows passing the FILTER and walks -- session_turns_workspace_queue_idx (workspace_id, session_id, status, position). least( min(( select min(waiting_turn.updated_at) from ${schema.sessionTurns} waiting_turn where waiting_turn.workspace_id = ${workspaceId} and waiting_turn.session_id = counted.id and waiting_turn.status = 'requires_action' )) filter (where awaits_person), min(awaiting_connection_since) filter ( where ${sessionAwaitsConnectionSql(sql`status`, sql`awaiting_connection_since`)} ) ) as "attentionSince", ( -- The lookahead row proves more descendants than the budget. exists ( select 1 from numbered where numbered.ordinal > ${SESSION_TREE_STATS_MAX_DESCENDANTS + 1} ) -- A start node on a legacy parent cycle has an edge back to it -- from one of its descendants, which the walk refuses to follow. or ( root.parent_session_id is not null and exists ( select 1 from numbered where numbered.ordinal <= ${SESSION_TREE_STATS_MAX_DESCENDANTS + 1} and numbered.id = root.parent_session_id ) ) or exists ( select 1 from numbered join ${schema.sessions} deeper on deeper.workspace_id = ${workspaceId} and deeper.parent_session_id = numbered.id where numbered.ordinal <= ${SESSION_TREE_STATS_MAX_DESCENDANTS + 1} and numbered.depth = ${SESSION_TREE_STATS_MAX_DEPTH} ) ) as truncated from counted ) stats where root.workspace_id = ${workspaceId} and ${anyOf(sql`root.id`, uniqueRootIds, "uuid")} `, ); return new Map( rows.map((row) => [ row.rootId, { directChildren: Number(row.directChildren), totalDescendants: Number(row.totalDescendants), runningDescendants: Number(row.runningDescendants), queuedDescendants: Number(row.queuedDescendants), waitingDescendants: Number(row.waitingDescendants), attentionDescendants: Number(row.attentionDescendants), pausedDescendants: Number(row.pausedDescendants), pausedWorkDescendants: Number(row.pausedWorkDescendants), failedDescendants: Number(row.failedDescendants), unreadFailedDescendants: Number(row.unreadFailedDescendants), unreadDescendants: Number(row.unreadDescendants), activelyWorkingDescendants: Number(row.activelyWorkingDescendants), attentionSince: row.attentionSince ? new Date(row.attentionSince).toISOString() : null, truncated: row.truncated, }, ]), ); } /** * When each given `requires_action` session's own open turn entered that * state: the oldest still-open `requires_action` turn per session. Only the * ids whose current status is `requires_action` should be passed; the lookup * walks `session_turns_workspace_queue_idx` per session and returns no row * for sessions with no such turn. */ export async function sessionRequiresActionSinceForSessions( db: Database, workspaceId: string, sessionIds: readonly string[], ): Promise> { const uniqueIds = [...new Set(sessionIds)]; if (uniqueIds.length === 0) return new Map(); const rows = await rawRows<{ sessionId: string; since: Date | string }>( db, sql` select ${schema.sessionTurns.sessionId} as "sessionId", min(${schema.sessionTurns.updatedAt}) as "since" from ${schema.sessionTurns} where ${schema.sessionTurns.workspaceId} = ${workspaceId} and ${inArray(schema.sessionTurns.sessionId, uniqueIds)} and ${schema.sessionTurns.status} = 'requires_action' group by ${schema.sessionTurns.sessionId} `, ); return new Map(rows.map((row) => [row.sessionId, new Date(row.since).toISOString()])); } /** * Each listed session's newest turn in execution order: the last queued turn, * else the turn currently executing, else the most recently finished turn. * Three bounded backward probes of existing partial indexes per session * (prompt queue, one current inference, finished order), so a long session * costs the same as a new one. Sessions without turns are absent. */ export async function sessionLatestTurnsForSessions( db: Database, workspaceId: string, sessionIds: readonly string[], ): Promise> { const uniqueIds = [...new Set(sessionIds)]; if (uniqueIds.length === 0) return new Map(); const rows = await rawRows<{ sessionId: string; id: string; status: SessionListLatestTurn["status"]; startedAt: Date | string | null; finishedAt: Date | string | null; }>( db, sql` select listed.session_id as "sessionId", latest.id, latest.status, latest.started_at as "startedAt", latest.finished_at as "finishedAt" from unnest(${`{${uniqueIds.join(",")}}`}::uuid[]) as listed(session_id) cross join lateral ( select candidate.id, candidate.status, candidate.started_at, candidate.finished_at from ( (select queued.id, queued.status, queued.started_at, queued.finished_at, 0 as rank from ${schema.sessionTurns} queued where queued.workspace_id = ${workspaceId}::uuid and queued.session_id = listed.session_id and queued.status = 'queued' order by queued.position desc limit 1) union all (select current_turn.id, current_turn.status, current_turn.started_at, current_turn.finished_at, 1 as rank from ${schema.sessionTurns} current_turn where current_turn.workspace_id = ${workspaceId}::uuid and current_turn.session_id = listed.session_id and current_turn.status in ('running', 'requires_action', 'recovering', 'waiting_capacity') limit 1) union all (select finished.id, finished.status, finished.started_at, finished.finished_at, 2 as rank from ${schema.sessionTurns} finished where finished.workspace_id = ${workspaceId}::uuid and finished.session_id = listed.session_id and finished.finished_at is not null order by finished.finished_at desc, finished.position desc, finished.created_at desc limit 1) ) candidate order by candidate.rank limit 1 ) latest `, ); const iso = (value: Date | string | null) => value === null ? null : new Date(value).toISOString(); return new Map( rows.map((row) => [ row.sessionId, { id: row.id, status: row.status, startedAt: iso(row.startedAt), finishedAt: iso(row.finishedAt), }, ]), ); } function withRequiresActionSince>( session: T, since: ReadonlyMap, ): T { return { ...session, requiresActionSince: session.status === "requires_action" ? (since.get(session.id) ?? null) : null, }; } function sessionRelatedListScope(scope: SessionAuthorizationListScope | undefined): SQL { if (!scope) return sql`true`; // Used only for parentless roots: target-only grants never admit relatives. return sessionAuthorizationRootScopeFilter(scope, false); } /** Exact target grants never imply visibility of relatives. */ function sessionNeedsYouSql(scope: SessionAuthorizationListScope | undefined): SQL { return sql`( ${schema.sessions.status} = 'failed' or ( ${schema.sessions.status} = 'requires_action' and not ${sessionQuestionsWithAgentSql(sql`${schema.sessions.workspaceId}`, sql`${schema.sessions.id}`)} ) or ${sessionAwaitsConnectionSql(schema.sessions.status, schema.sessions.awaitingConnectionSince)} or ( ${schema.sessions.parentSessionId} is null and ${sessionRelatedListScope(scope)} and exists ( with recursive attention_tree(id, status, awaiting_connection_since) as ( select child.id, child.status, child.awaiting_connection_since from ${schema.sessions} child where child.workspace_id = ${schema.sessions.workspaceId} and child.parent_session_id = ${schema.sessions.id} union select child.id, child.status, child.awaiting_connection_since from attention_tree parent join ${schema.sessions} child on child.parent_session_id = parent.id where child.workspace_id = ${schema.sessions.workspaceId} ) select 1 from attention_tree where (status = 'requires_action' and not ${sessionQuestionsWithAgentSql(sql`${schema.sessions.workspaceId}`, sql`attention_tree.id`)}) or ${sessionAwaitsConnectionSql(sql`status`, sql`awaiting_connection_since`)} ) ) )`; } /** * An idle session whose agent waits on a connection card (connect, reconnect * or more access) needs the person, as an approval does. Its status stays * idle: nothing runs and new messages are admitted as usual. */ function sessionAwaitsConnectionSql(status: SQLWrapper, awaitingSince: SQLWrapper): SQL { return sql`(${status} = 'idle' and ${awaitingSince} is not null)`; } /** * A workstream is the subject's when any session in its tree was created by * them or received a prompt they sent directly. Agent-relayed and service * turns do not count, even when they carry the human's causal authority. * Applies to every row through its root, so a root page and its children * agree. Keep the existential turn probe keyed by session: pulling it into a * workspace-wide hashed subplan reads a person's entire prompt history, and * repeats turn RLS checks, even when the page contains only a few roots. * OFFSET 0 preserves the correlated index probes without changing predicates. */ function sessionMineSql(subjectId: string): SQL { return sql`( exists ( select 1 from ${schema.sessions} mine_created where mine_created.workspace_id = ${schema.sessions.workspaceId} and mine_created.root_session_id = ${schema.sessions.rootSessionId} and mine_created.created_by_kind = 'subject' and mine_created.created_by_subject_id = ${subjectId} ) or exists ( select 1 from ${schema.sessions} mine_tree where mine_tree.workspace_id = ${schema.sessions.workspaceId} and mine_tree.root_session_id = ${schema.sessions.rootSessionId} and exists ( select 1 from ${schema.sessionTurns} mine_turn where mine_turn.workspace_id = mine_tree.workspace_id and mine_turn.session_id = mine_tree.id and ${sessionTurnHumanPromptSql(sql`mine_turn`)} and mine_turn.initiator_subject_id = ${subjectId} offset 0 ) offset 0 ) )`; } /** Exact partial-index predicate for a prompt a person sent directly. */ function sessionTurnHumanPromptSql(turn: SQL): SQL { return sql`${turn}.initiator_kind = 'subject' and ${turn}.source in ('user', 'api') and ${turn}.surface is distinct from 'agent'`; } /** * One content-free graph aggregation, before pagination. Each root owns a * disjoint tree: a single-parent cycle cannot be reachable from a parentless * root, and a single-parent row has only one path from that root, so UNION ALL * needs no duplicate elimination. Exact target scopes * seed only their own row; pinned paths leave the ordinary project summaries. * Materialize narrow RLS-authorized rows before recursion so tree depth cannot * multiply base-table permission checks or personal-state scans. */ async function sessionListTotalsInScope( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, withSiteRows = false, ): Promise { const archiveStatus = options.archiveStatus ?? (options.archivedOnly ? "archived" : "active"); // A grouped rail counts Site conversations in its project totals and gets // their Site rows here; its ordinary rows still omit them. const siteConversations = options.siteConversations ? "include" : undefined; // Sites this person opened or pinned join the rows only in the plain view: a root // filter (Mine, search, creator, dates, archived content, another person's // scope) or an agent caller lists only Sites its listed chats created. const withOpenedSites = withSiteRows && !options.needsYouOnly && !options.mineOnly && !options.search?.trim() && !options.contentArchivedOnly && !options.scopeSubjectId && !options.createdBy && !options.updatedFrom && !options.updatedBefore && !options.createdFrom && !options.createdBefore && !options.sessionIds && !options.authorizationScope?.agentAccessViewer; const rootFilters = and( eq(schema.sessions.workspaceId, workspaceId), ...sessionFilters({ ...options, ...(siteConversations ? { siteConversations } : {}), parentSessionId: null, needsYouOnly: false, archiveStatus: "all", }), ...(archiveStatus === "all" ? [] : [ archiveStatus === "archived" ? sessionArchivedSql(sql`${schema.sessions}`) : sql`not (${sessionArchivedSql(sql`${schema.sessions}`)})`, ]), // A Site this person archived from their sidebar hides its conversations // with its row, as an archived chat hides its tree. ...(archiveStatus === "active" && siteConversations ? archivedSiteConversationFilters({ ...options, siteConversations }) : []), ); const rows = await rawRows<{ needsYouCount: number; groups: SessionListTotals["groups"]; sites: Array | null; }>( db, sql` -- Inline this subject's state so each lateral lookup can use the session -- key. A materialized workspace range has no index: generic estimates can -- choose to rescan the whole range once per root or descendant. with recursive personal_state as not materialized ( select workspace_id, subject_id, session_id, pinned, archived, acknowledged_sequence, manually_unread_through, actively_working from ${schema.sessionPins} where workspace_id = ${workspaceId} and subject_id = ${options.subjectId} ), roots as materialized ( select ${schema.sessions.id} as id, ${schema.sessions.channelId} as channel_id, ${schema.sessions.accountId} as account_id, ${schema.sessions.status} as status, ${schema.sessions.directControlState} as direct_control_state, ${schema.sessions.directPauseRevision} as direct_pause_revision, ${schema.sessions.subtreeRunOverrideRevision} as subtree_run_override_revision, ${schema.sessions.activeTurnId} as active_turn_id, ${schema.sessions.inputWaitUntil} as input_wait_until, ${schema.sessions.inputWaitTurnId} as input_wait_turn_id, ${schema.sessions.awaitingConnectionSince} as awaiting_connection_since, ${schema.sessions.siteId} as site_id, ${schema.sessions.siteAccessRootId} is not null as site_conversation, ${schema.sessions.updatedAt} as updated_at, ${schema.sessions.createdAt} as created_at, ${schema.sessions.metadata}->'_opengeniSiteOrigin'->>'title' as origin_title, ${sessionRelatedListScope(options.authorizationScope)} as related, ${sessionArchivedSql(sql`${schema.sessions}`)} as archived, coalesce(root_personal.pinned, false) as pinned, coalesce(case when root_personal.manually_unread_through is not null then -1 else root_personal.acknowledged_sequence end, 0) as acknowledged_sequence, coalesce(root_personal.actively_working, false) as actively_working from ${schema.sessions} left join lateral ( select * from personal_state where session_id = ${schema.sessions.id} offset 0 ) root_personal on true where ${rootFilters} ), visible_children as materialized ( -- Immutable root lineage excludes trees that cannot enter this recursion. -- Retain each child's RLS check and materialize once, so depth cannot -- multiply base-table or personal-state scans. select child.id, child.parent_session_id, child.account_id, child.status, child.active_turn_id, child.input_wait_until, child.input_wait_turn_id, child.awaiting_connection_since, child.subtree_run_override_revision, child.direct_control_state, child.direct_pause_revision, coalesce(personal.pinned, false) as pinned, coalesce(case when personal.manually_unread_through is not null then -1 else personal.acknowledged_sequence end, 0) as acknowledged_sequence, coalesce(personal.actively_working, false) as actively_working from ${schema.sessions} child left join lateral ( select * from personal_state where session_id = child.id offset 0 ) personal on true where child.workspace_id = ${workspaceId} and child.parent_session_id is not null and exists (select 1 from roots root where root.related and root.id = child.root_session_id) ), nodes(root_id, channel_id, id, parent_session_id, account_id, status, active_turn_id, input_wait_until, input_wait_turn_id, awaiting_connection_since, pause_revision, pinned_path, related, acknowledged_sequence, actively_working) as ( select root.id, root.channel_id, root.id, null::uuid, root.account_id, root.status, root.active_turn_id, root.input_wait_until, root.input_wait_turn_id, root.awaiting_connection_since, greatest( case when control.workspace_state = 'paused' and (root.subtree_run_override_revision is null or root.subtree_run_override_revision <= control.workspace_pause_revision) then control.workspace_pause_revision end, case when root.direct_control_state = 'paused' then root.direct_pause_revision end ), root.pinned, root.related, root.acknowledged_sequence, root.actively_working from roots root join ${schema.workspaceInferenceControls} control on control.workspace_id = ${workspaceId} union all select parent.root_id, parent.channel_id, child.id, child.parent_session_id, child.account_id, child.status, child.active_turn_id, child.input_wait_until, child.input_wait_turn_id, child.awaiting_connection_since, greatest( case when child.subtree_run_override_revision is null or child.subtree_run_override_revision <= parent.pause_revision then parent.pause_revision end, case when child.direct_control_state = 'paused' then child.direct_pause_revision end ), parent.pinned_path or child.pinned, parent.related, child.acknowledged_sequence, child.actively_working from nodes parent join visible_children child on child.parent_session_id = parent.id where parent.related ), attention_roots as ( select root_id, bool_or(case when status = 'requires_action' then not ${sessionQuestionsWithAgentSql(workspaceId, sql`nodes.id`)} else ${sessionAwaitsConnectionSql(sql`status`, sql`awaiting_connection_since`)} end) as attention from nodes group by root_id ), root_attention as materialized ( select root.id, not root.archived and ( root.status in ('requires_action', 'failed') or ${sessionAwaitsConnectionSql(sql`root.status`, sql`root.awaiting_connection_since`)} or coalesce(attention.attention, false) ) as needs_you from roots root left join attention_roots attention on attention.root_id = root.id ), measured as ( select nodes.*, root.site_conversation as root_site_conversation, root.site_id as root_site_id, root.updated_at as root_updated_at, root.created_at as root_created_at, root.origin_title as root_origin_title, cursor.last_meaningful_sequence > nodes.acknowledged_sequence as unread, -- Probed only for unread failures, the only ones it changes. case when nodes.status = 'failed' and cursor.last_meaningful_sequence > nodes.acknowledged_sequence then ${sessionFailureHandledByParentSql( workspaceId, sql`nodes.id`, sql`nodes.parent_session_id`, )} else false end as failure_handled, nodes.actively_working as active_work, case when nodes.status = 'requires_action' then ( select min(turn.updated_at) from ${schema.sessionTurns} turn where turn.workspace_id = ${workspaceId} and turn.session_id = nodes.id and turn.status = 'requires_action' ) when ${sessionAwaitsConnectionSql(sql`nodes.status`, sql`nodes.awaiting_connection_since`)} then nodes.awaiting_connection_since end as attention_since, case when nodes.status = 'requires_action' then not ${sessionQuestionsWithAgentSql(workspaceId, sql`nodes.id`)} else ${sessionAwaitsConnectionSql(sql`nodes.status`, sql`nodes.awaiting_connection_since`)} end as needs_person, nodes.status = 'idle' and nodes.active_turn_id is null and nodes.input_wait_until is not null and nodes.input_wait_turn_id = ( select finished.id from ${schema.sessionTurns} finished where finished.workspace_id = ${workspaceId} and finished.session_id = nodes.id and finished.finished_at is not null and ${sessionInputWaitDecidingTurnSql( { id: sql`finished.id`, source: sql`finished.source`, workspaceId: sql`finished.workspace_id`, sessionId: sql`finished.session_id`, finishedAt: sql`finished.finished_at`, metadata: sql`finished.metadata`, }, sql`nodes.input_wait_turn_id`, )} order by finished.finished_at desc, finished.position desc, finished.created_at desc limit 1 ) as input_wait from nodes -- Probe only contributing nodes. A workspace-wide cursor scan evaluates -- its session visibility policy even for archived/pinned trees discarded -- by this query. Keep all RLS checks, but key them after node filtering. join lateral ( select last_meaningful_sequence from ${schema.sessionEventCursors} cursor where cursor.workspace_id = ${workspaceId} and cursor.session_id = nodes.id and cursor.account_id = nodes.account_id offset 0 ) cursor on true join roots root on root.id = nodes.root_id where not root.archived and not nodes.pinned_path ${ options.needsYouOnly ? sql`and nodes.root_id in (select id from root_attention where needs_you)` : sql`` } ), grouped as ( select channel_id as "channelId", count(*)::int as total, count(*) filter (where needs_person)::int as attention, min(attention_since) filter (where needs_person) as "attentionSince", count(*) filter (where status = 'failed' and unread and not failure_handled)::int as failed, count(*) filter (where pause_revision is null and (status in ('running', 'recovering') or input_wait))::int as active, count(*) filter (where pause_revision is null and status in ('queued', 'waiting_capacity'))::int as queued, count(*) filter (where pause_revision is null and input_wait)::int as waiting, count(*) filter (where unread and not failure_handled)::int as unread, count(*) filter (where active_work)::int as "activeWork" from measured group by channel_id ), site_conv as ( -- Site conversations nest under their Site's row in their own project. -- Pinned ones live with pins. select root.*, root.channel_id as row_channel_id from roots root where ${ withSiteRows ? sql`root.site_conversation and root.site_id is not null and not root.pinned ${ options.needsYouOnly ? sql`and root.id in (select id from root_attention where needs_you)` : sql`` }` : sql`false` } ), site_conv_totals as ( select site_id, row_channel_id as channel_id, count(*)::int as conversations, min(created_at) as first_created_at, max(created_at) as created_at, (array_agg(origin_title order by updated_at desc, id desc) filter (where origin_title is not null))[1] as origin_title, max(updated_at) as activity_at from site_conv group by site_id, row_channel_id ), site_home as ( -- A Site sits in the project of the chat that created it (the tree of -- its first version's session), as far as this viewer can see that -- chat, unless someone moved it to a project (or Default) since; new -- Site conversations are filed there too. Conversations in other -- projects never take the Site out of its own: a Site without -- conversations here is still listed here when this viewer lists its -- creating chat, or opened it. Candidates are the live Sites in this -- viewer's audience (one row each); revision 1 is a unique-index lookup. select artifact.id as site_id, case when placement.site_id is not null then placement.channel_id else creator.channel_id end as channel_id from ${schema.workspaceArtifacts} artifact join lateral ( select version.source_session_id from ${schema.workspaceArtifactVersions} version where version.workspace_id = ${workspaceId} and version.artifact_id = artifact.id and version.revision = 1 ) first_version on true left join ${schema.sessions} source on source.workspace_id = ${workspaceId} and source.id = first_version.source_session_id left join ${schema.sessions} creator on creator.workspace_id = ${workspaceId} and creator.id = source.root_session_id and creator.site_access_root_id is null left join ${schema.siteProjectPlacements} placement on placement.workspace_id = ${workspaceId} and placement.site_id = artifact.id where ${withSiteRows && !options.needsYouOnly ? sql`true` : sql`false`} and artifact.workspace_id = ${workspaceId} and artifact.status = 'active' and (artifact.visibility = 'workspace_shared' or artifact.owner_subject_id = ${options.subjectId}) and not exists ( select 1 from site_conv_totals filed where filed.site_id = artifact.id and filed.channel_id is not distinct from (case when placement.site_id is not null then placement.channel_id else creator.channel_id end)) and (exists (select 1 from roots listed where listed.id = creator.id) ${ // Opens and pins are this person's own plain-view state: a root // filter or an agent caller lists only Sites its chats created. withOpenedSites ? sql`or exists ( select 1 from ${schema.siteOpens} opened where opened.workspace_id = ${workspaceId} and opened.subject_id = ${options.subjectId} and opened.site_id = artifact.id) or exists ( select 1 from ${schema.siteSidebarStates} pin where pin.workspace_id = ${workspaceId} and pin.subject_id = ${options.subjectId} and pin.site_id = artifact.id and pin.pinned_at is not null)` : sql`` }) ), site_keys as ( select * from site_conv_totals union all select site_id, channel_id, 0, null, null, null, null from site_home ), site_rows as ( -- One row per Site and project. The title is the Site's current one when -- its audience includes this viewer (the catalog's rule; RLS only -- isolates the workspace), else the creation-time label. A row without -- conversations needs a live Site the viewer can see. A row's time is -- the Site's newest published version (creation is version 1) and -- nothing else: messages and turns in its conversations, or in the chat -- that created or published it, never move it, nor does opening it (an -- open only lists it). Archive, restore, rollback (Undo) and other -- updates to the Site's record add no version, so they never lift it -- either. A viewer who cannot read the Site sees no publishes, so its -- row keeps the time its first conversation here started, which -- messages do not change. Which rows the bound keeps is a separate -- question: pinned rows first, then the later of the newest publish and -- conversation activity, so a Site whose conversation runs or needs this -- person is never cut for an old publish. One extra row reports -- truncation. select key.site_id as "siteId", key.channel_id as "channelId", coalesce(site.title, key.origin_title, '') as title, key.conversations, coalesce(site.published_at, key.first_created_at) as "updatedAt", coalesce(key.created_at, site.created_at) as "createdAt", sidebar.pinned_at is not null as pinned, sidebar.pinned_at as "pinnedAt", greatest(site.published_at, key.activity_at, key.first_created_at) as "rankAt" from site_keys key left join lateral ( select artifact.title, artifact.status, artifact.created_at, (select version.created_at from ${schema.workspaceArtifactVersions} version where version.workspace_id = ${workspaceId} and version.artifact_id = artifact.id order by version.revision desc limit 1) as published_at from ${schema.workspaceArtifacts} artifact where artifact.workspace_id = ${workspaceId} and artifact.id = key.site_id and (artifact.visibility = 'workspace_shared' or artifact.owner_subject_id = ${options.subjectId}) ) site on true left join lateral ( select state.pinned_at, state.archived_at from ${schema.siteSidebarStates} state where state.workspace_id = ${workspaceId} and state.subject_id = ${options.subjectId} and state.site_id = key.site_id ) sidebar on true -- This person's archived Sites leave their sidebar; pinned ones lead. where (key.conversations > 0 or site.status = 'active') and sidebar.archived_at is null ${options.channelId !== undefined ? sql`and key.channel_id is not distinct from ${options.channelId}::uuid` : sql``} order by 7 desc, 9 desc nulls last, 1, 2 limit ${SITE_CONVERSATION_GROUP_LIMIT + 1} ), site_status as ( -- Status counts follow project totals: active, unpinned trees only. select conv.site_id, conv.row_channel_id, count(*)::int as total, count(*) filter (where node.needs_person)::int as attention, min(node.attention_since) filter (where node.needs_person) as "attentionSince", count(*) filter (where node.status = 'failed' and node.unread and not node.failure_handled)::int as failed, count(*) filter (where node.pause_revision is null and (node.status in ('running', 'recovering') or node.input_wait))::int as active, count(*) filter (where node.pause_revision is null and node.status in ('queued', 'waiting_capacity'))::int as queued, count(*) filter (where node.pause_revision is null and node.input_wait)::int as waiting, count(*) filter (where node.unread and not node.failure_handled)::int as unread, count(*) filter (where node.active_work)::int as "activeWork" from measured node join site_conv conv on conv.id = node.root_id group by conv.site_id, conv.row_channel_id ), site_grouped as ( select site_rows.*, coalesce(status.total, 0) as total, coalesce(status.attention, 0) as attention, status."attentionSince", coalesce(status.failed, 0) as failed, coalesce(status.active, 0) as active, coalesce(status.queued, 0) as queued, coalesce(status.waiting, 0) as waiting, coalesce(status.unread, 0) as unread, coalesce(status."activeWork", 0) as "activeWork" from site_rows left join site_status status on status.site_id = site_rows."siteId" and status.row_channel_id is not distinct from site_rows."channelId" ) select (select count(*)::int from root_attention where needs_you) as "needsYouCount", coalesce((select jsonb_agg(to_jsonb(grouped)) from grouped), '[]'::jsonb) as groups, coalesce((select jsonb_agg(to_jsonb(site_grouped) order by site_grouped.pinned desc, site_grouped."rankAt" desc nulls last, site_grouped."siteId", site_grouped."channelId") from site_grouped), '[]'::jsonb) as sites `, ); const result = rows[0]; const iso = (value: string | null) => (value ? new Date(value).toISOString() : null); const sites = result?.sites ?? []; return { needsYouCount: Number(result?.needsYouCount ?? 0), groups: (result?.groups ?? []).map((group) => ({ ...group, attentionSince: iso(group.attentionSince), })), // The bound keeps rows in rank order; the kept rows then sort by their // time, the newest publish. sites: sites .slice(0, SITE_CONVERSATION_GROUP_LIMIT) .map(({ pinned, pinnedAt, rankAt: _rankAt, ...site }) => ({ ...site, updatedAt: iso(site.updatedAt)!, createdAt: iso(site.createdAt)!, attentionSince: iso(site.attentionSince), // Only a pinned row carries pin fields, so unpinned rows keep their shape. ...(pinned ? { pinned: true as const, pinnedAt: iso(pinnedAt ?? null) } : {}), })) .sort( (a, b) => compareCodePoints(b.updatedAt, a.updatedAt) || compareCodePoints(a.siteId, b.siteId) || // As SQL orders it: a Site's Default row (no project) last. compareCodePoints(a.channelId ?? "\uffff", b.channelId ?? "\uffff"), ), sitesTruncated: sites.length > SITE_CONVERSATION_GROUP_LIMIT, }; } function compareCodePoints(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } /** * Bound on Site rows per read. Pinned rows are kept first, then by the later of * the newest publish and conversation activity, so Sites nobody touched for a * long time fall past it; the Artifacts page lists every Site. */ export const SITE_CONVERSATION_GROUP_LIMIT = 200; /** * A Site this person archived from their sidebar hides its conversations from * every view of their sidebar (grouped, flat and search), as an archived chat * hides its tree. Only the console's opt-in listing of Site conversations is * affected; a Site's own conversation list and agent callers are not. */ function archivedSiteConversationFilters( options: Pick< ListSessionsForSubjectOptions, "authorizationScope" | "subjectId" | "originSiteId" | "siteAccessId" | "siteConversations" >, ): SQL[] { if ( !options.siteConversations || options.originSiteId || options.siteAccessId || options.authorizationScope?.agentAccessViewer ) return []; return [ sql`not (${schema.sessions.siteAccessRootId} is not null and exists ( select 1 from ${schema.siteSidebarStates} hidden where hidden.workspace_id = ${schema.sessions.workspaceId} and hidden.subject_id = ${options.subjectId} and hidden.site_id = ${schema.sessions.siteId} and hidden.archived_at is not null))`, ]; } function sessionFilters( options: Pick< ListSessionsForSubjectOptions, | "authorizationScope" | "parentSessionId" | "search" | "subjectId" | "archivedOnly" | "archiveStatus" | "channelId" | "originSiteId" | "siteAccessId" | "siteConversations" | "createdBy" | "updatedFrom" | "updatedBefore" | "createdFrom" | "createdBefore" | "scopeSubjectId" | "needsYouOnly" | "contentArchivedOnly" | "mineOnly" | "sessionIds" >, ): SQL[] { const filters: SQL[] = [ sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' and private_slack_interaction.owning_subject_id <> ${options.subjectId} )`, ]; if (options.needsYouOnly) filters.push(sessionNeedsYouSql(options.authorizationScope)); if (options.contentArchivedOnly) { filters.push(sql`${schema.sessions.contentArchiveState} = 'archived'`); } if (options.mineOnly) filters.push(sessionMineSql(options.subjectId)); if (options.siteAccessId) { filters.push(siteSessionAccessFilter(options.siteAccessId, options.subjectId)); } else if (options.originSiteId) { filters.push( eq(schema.sessions.siteId, options.originSiteId), sql`${schema.sessions.siteAccessRootId} is not null`, ); } else if ( options.siteConversations !== "include" || options.authorizationScope?.agentAccessViewer ) { // App-internal execution is not ordinary workspace conversation discovery. // This is presentation scope only: native ownership and Site RLS still apply. // The console rail opts in explicitly (`include` or `group`); agent // callers keep their own-root bound so the option never widens discovery. const ownRoot = options.authorizationScope?.agentAccessViewer?.callerRootSessionId; filters.push( ownRoot ? sql`(${schema.sessions.siteAccessRootId} is null OR ${schema.sessions.rootSessionId} = ${ownRoot}::uuid)` : sql`${schema.sessions.siteAccessRootId} is null`, ); } // A chat is archived for everyone, and its sub-chats with it. const archivedRoot = sql`exists ( select 1 from ${schema.sessions} archive_root where archive_root.workspace_id = ${schema.sessions.workspaceId} and archive_root.id = ${schema.sessions.rootSessionId} and ${sessionArchivedSql(sql`archive_root`)} )`; const archiveStatus = options.archiveStatus ?? (options.archivedOnly ? "archived" : "active"); if (archiveStatus !== "all") { filters.push(archiveStatus === "archived" ? archivedRoot : sql`not (${archivedRoot})`); } if (archiveStatus === "active") filters.push(...archivedSiteConversationFilters(options)); if (options.authorizationScope) { filters.push( options.parentSessionId === null ? sessionAuthorizationRootScopeFilter(options.authorizationScope) : sessionAuthorizationScopeFilter(options.authorizationScope), ); } if (Object.prototype.hasOwnProperty.call(options, "parentSessionId")) { const parentSessionId = options.parentSessionId; if (parentSessionId === null) { filters.push(isNull(schema.sessions.parentSessionId)); } else if (parentSessionId !== undefined) { filters.push(eq(schema.sessions.parentSessionId, parentSessionId)); } } // Every word must appear in the title or the first message, in any order, so // "deploy fix" finds "Fix the deploy script". Words are literal, // case-insensitive substrings rather than user-authored SQL globbing. for (const word of sessionSearchWords(options.search)) { // PostgreSQL LIKE uses backslash as its default escape. Escape it first so // a literal trailing slash cannot consume our surrounding wildcard; then // escape the two wildcard metacharacters. const pattern = `%${word .replaceAll("\\", "\\\\") .replaceAll("%", "\\%") .replaceAll("_", "\\_")}%`; filters.push( or(ilike(schema.sessions.title, pattern), ilike(schema.sessions.initialMessage, pattern))!, ); } if (options.channelId !== undefined) { filters.push( options.channelId === null ? isNull(schema.sessions.channelId) : eq(schema.sessions.channelId, options.channelId!), ); } if (options.createdBy) { filters.push( // Without a kind, keep both kinds explicit so the creator index's // leading kind column still bounds the scan. options.createdBy.kind ? eq(schema.sessions.createdByKind, options.createdBy.kind) : inArray(schema.sessions.createdByKind, ["subject", "service"]), eq(schema.sessions.createdBySubjectId, options.createdBy.subjectId), ); } if (options.updatedFrom) filters.push(gte(schema.sessions.updatedAt, options.updatedFrom)); if (options.updatedBefore) filters.push(lt(schema.sessions.updatedAt, options.updatedBefore)); if (options.createdFrom) filters.push(gte(schema.sessions.createdAt, options.createdFrom)); if (options.createdBefore) filters.push(lt(schema.sessions.createdAt, options.createdBefore)); if (options.scopeSubjectId) { filters.push(eq(schema.sessions.scopeSubjectId, options.scopeSubjectId)); } if (options.sessionIds) { if (options.sessionIds.length > SESSION_LIST_MAX_SESSION_IDS) throw new SessionListCursorError( `sessionIds accepts at most ${SESSION_LIST_MAX_SESSION_IDS} ids`, ); // An empty selection matches nothing, never everything. filters.push(anyOf(schema.sessions.id, [...new Set(options.sessionIds)])); } return filters; } /** * The agent-access predicate for one calling attempt (migration 0427). It * mirrors outgoing reach in the core seam: own tree, same canonical user, or * workspace. Target task scope never hides the conversation. This predicate * remains intersected with host scope and ordinary private-session visibility. */ export function sessionAgentAccessViewerFilter(viewer: SessionAgentAccessViewer): SQL { const ownTree = eq(schema.sessions.rootSessionId, viewer.callerRootSessionId); const sameUser = viewer.scopeSubjectId ? and(eq(schema.sessions.scopeSubjectId, viewer.scopeSubjectId))! : sql`false`; switch (viewer.agentAccess) { case "session": return ownTree; case "user": return or(ownTree, sameUser)!; case "workspace": return sql`true`; } } /** * Convert the embedding host's complete list scope into a workspace-bound SQL * predicate. Root scopes include every descendant through the durable parent * graph; exact ids never imply access to related sessions. `UNION` (rather than * `UNION ALL`) makes legacy cycles terminate without a caller-sized path array. */ export function sessionAuthorizationScopeFilter(scope: SessionAuthorizationListScope): SQL { const hostScope = sessionAuthorizationHostScopeFilter(scope); return scope.agentAccessViewer ? and(hostScope, sessionAgentAccessViewerFilter(scope.agentAccessViewer))! : hostScope; } /** A parentless root cannot be another granted root's descendant. */ function sessionAuthorizationRootScopeFilter( scope: SessionAuthorizationListScope, includeExact = true, ): SQL { let hostScope: SQL = sql`true`; if (scope.kind === "scoped") { if ( scope.rootSessionIds.length > SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS || scope.sessionIds.length > SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS ) { throw new RangeError( `Session authorization scope exceeds ${SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS} ids per field`, ); } const ids = [...new Set([...scope.rootSessionIds, ...(includeExact ? scope.sessionIds : [])])]; hostScope = ids.length > 0 ? inArray(schema.sessions.id, ids) : sql`false`; } return scope.agentAccessViewer ? and(hostScope, sessionAgentAccessViewerFilter(scope.agentAccessViewer))! : hostScope; } function sessionAuthorizationHostScopeFilter(scope: SessionAuthorizationListScope): SQL { if (scope.kind === "all") return sql`true`; if ( scope.rootSessionIds.length > SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS || scope.sessionIds.length > SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS ) { throw new RangeError( `Session authorization scope exceeds ${SESSION_AUTHORIZATION_LIST_SCOPE_MAX_IDS} ids per field`, ); } const rootIds = [...new Set(scope.rootSessionIds)]; const sessionIds = [...new Set(scope.sessionIds)]; if (rootIds.length === 0 && sessionIds.length === 0) return sql`false`; const exact = sessionIds.length > 0 ? inArray(schema.sessions.id, sessionIds) : sql`false`; const descendants = rootIds.length > 0 ? sql`${schema.sessions.id} in ( with recursive authorized_sessions(id) as ( select root.id from ${schema.sessions} root where root.workspace_id = ${schema.sessions.workspaceId} and ${inArray(sql`root.id`, rootIds)} union select child.id from authorized_sessions parent join ${schema.sessions} child on child.workspace_id = ${schema.sessions.workspaceId} and child.parent_session_id = parent.id ) select id from authorized_sessions )` : sql`false`; return or(exact, descendants)!; } async function sessionIdsCoveredByAuthorizationRoots( db: Database, workspaceId: string, sessionIds: string[], scope: SessionAuthorizationListScope | undefined, ): Promise> { if (sessionIds.length === 0) return new Set(); if (!scope) return new Set(sessionIds); if (scope.kind === "all" && !scope.agentAccessViewer) return new Set(sessionIds); if (scope.kind === "scoped" && scope.rootSessionIds.length === 0) return new Set(); const rows = await db .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), anyOf(schema.sessions.id, sessionIds), sessionAuthorizationScopeFilter( scope.kind === "all" ? scope : { kind: "scoped", rootSessionIds: scope.rootSessionIds, sessionIds: [], ...(scope.agentAccessViewer ? { agentAccessViewer: scope.agentAccessViewer } : {}), }, ), ), ); return new Set(rows.map((row) => row.id)); } /** * The reserved slot a session-visibility transition leaves behind when it strips * a now-`user_private` session identity out of another subject's cached page * (migration 0301). Replacing rather than removing the slot keeps snapshot * cardinality and every in-flight cursor offset byte-stable; `gen_random_uuid()` * never emits the nil UUID, so the slot resolves to no session and the hydration * below drops it exactly as it already drops a row RLS hid between pages. */ export const SESSION_LIST_SNAPSHOT_REDACTED_SESSION_ID = "00000000-0000-0000-0000-000000000000"; const SESSION_LIST_SERIALIZATION_MAX_ATTEMPTS = 3; const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; // A v2 keyset cursor also carries this reserved, never-materialized // compatibility snapshot identity. An old API replica ignores the unknown v2 // fields, accepts the legacy envelope, and returns the existing typed 410. The // SDK/browser then rebases instead of surfacing an unrecoverable 400 during a // rolling deploy. const SESSION_LIST_KEYSET_LEGACY_SNAPSHOT_ID = "00000000-0000-4000-8000-000000000000"; const SESSION_LIST_CURSOR_TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{6})Z$/; function isSessionListCursorTimestamp(value: string): boolean { const match = SESSION_LIST_CURSOR_TIMESTAMP_PATTERN.exec(value); if (!match || match[1] === "0000") return false; const millisecondTimestamp = `${match[1]}-${match[2]}-${match[3]}T${match[4]}:${match[5]}:${match[6]}.${match[7]!.slice(0, 3)}Z`; const parsed = Date.parse(millisecondTimestamp); return Number.isFinite(parsed) && new Date(parsed).toISOString() === millisecondTimestamp; } function sessionParentFilter(parentSessionId: string | null | undefined): string { return parentSessionId === undefined ? "all" : parentSessionId === null ? "null" : parentSessionId; } /** The words of a chat title search; a long query keeps its first eight words. */ function sessionSearchWords(search: string | undefined): string[] { return [...new Set((search ?? "").trim().split(/\s+/).filter(Boolean))].slice(0, 8); } function sessionSearchFilter(search: string | undefined): string | null { const trimmed = search?.trim(); return trimmed ? trimmed : null; } function sessionListFilterIdentity(options: SessionListFilterOptions): string { const hasChannel = options.channelId !== undefined; if ( !hasChannel && !options.originSiteId && !options.siteAccessId && options.siteConversations !== "include" && !options.createdBy && !options.updatedFrom && !options.updatedBefore && !options.createdFrom && !options.createdBefore && !options.scopeSubjectId && !options.needsYouOnly && !options.contentArchivedOnly && !options.mineOnly && !options.sessionIds ) { return "all"; } return JSON.stringify([ ...(options.siteAccessId ? [["siteAccess", options.siteAccessId]] : []), ...(options.originSiteId ? [["originSite", options.originSiteId]] : []), // `group` returns the same rows as the default; only `include` changes them. ...(options.siteConversations === "include" ? [["siteConversations", "include"]] : []), hasChannel ? ["channel", options.channelId] : null, options.createdBy ? ["creator", options.createdBy.kind ?? null, options.createdBy.subjectId] : null, options.updatedFrom ? ["updatedFrom", options.updatedFrom.toISOString()] : null, options.updatedBefore ? ["updatedBefore", options.updatedBefore.toISOString()] : null, options.createdFrom ? ["createdFrom", options.createdFrom.toISOString()] : null, options.createdBefore ? ["createdBefore", options.createdBefore.toISOString()] : null, options.scopeSubjectId ? ["scopeSubjectId", options.scopeSubjectId] : null, ...(options.needsYouOnly ? [["needsYouOnly", true]] : []), ...(options.contentArchivedOnly ? [["contentArchivedOnly", true]] : []), ...(options.mineOnly ? [["mineOnly", true]] : []), // A digest keeps continuation cursors short for a 200-id selection. ...(options.sessionIds ? [ [ "sessionIds", createHash("sha256") .update([...new Set(options.sessionIds)].sort().join(",")) .digest("hex"), ], ] : []), ]); } /** Opaque, URL-safe cursor encoding for bounded session-list pagination. */ export function encodeSessionListCursor(cursor: SessionListCursor): string { return Buffer.from( JSON.stringify( cursor.kind === "keyset" ? { version: 4, sortBy: cursor.sortBy ?? "updatedAt", // Preserve the old cursor envelope until every pre-v2 replica has // rolled away. It resolves only to the typed expiry/rebase path. snapshotId: SESSION_LIST_KEYSET_LEGACY_SNAPSHOT_ID, offset: 0, snapshotRevision: cursor.snapshotRevision, ...(cursor.sortXid !== undefined ? { sortXid: cursor.sortXid } : {}), sortAt: cursor.sortAt, id: cursor.id, parentSessionFilter: cursor.parentSessionFilter, search: cursor.search, archiveMode: cursor.archiveMode, filter: cursor.filter ?? "all", } : { snapshotId: cursor.snapshotId, offset: cursor.offset, parentSessionFilter: cursor.parentSessionFilter, search: cursor.search, archiveMode: cursor.archiveMode, ...(cursor.filter ? { filter: cursor.filter } : {}), }, ), ).toString("base64url"); } /** Decode and validate a cursor before it reaches any SQL predicate. */ export function decodeSessionListCursor(value: string): SessionListCursor | null { try { const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as { version?: unknown; sortBy?: unknown; snapshotId?: unknown; offset?: unknown; snapshotRevision?: unknown; sortXid?: unknown; sortAt?: unknown; id?: unknown; parentSessionFilter?: unknown; search?: unknown; archiveMode?: unknown; filter?: unknown; }; const parentSessionFilter = parsed.parentSessionFilter; const search = parsed.search; const archiveMode = parsed.archiveMode ?? "active"; const filter = parsed.filter ?? "all"; const filtersAreValid = (parentSessionFilter === "all" || parentSessionFilter === "null" || (typeof parentSessionFilter === "string" && UUID_PATTERN.test(parentSessionFilter))) && (search === null || (typeof search === "string" && search.length <= 200)) && (archiveMode === "active" || archiveMode === "archived" || (parsed.version === 4 && archiveMode === "all")) && typeof filter === "string" && filter.length <= 2_048; if (!filtersAreValid) return null; if (parsed.version === 2 || parsed.version === 3 || parsed.version === 4) { const sortBy = parsed.version === 4 ? parsed.sortBy : parsed.version === 3 ? "archivedAt" : "updatedAt"; if ( !["updatedAt", "createdAt", "name", "archivedAt"].includes(sortBy as string) || (sortBy === "archivedAt" && archiveMode !== "archived") || typeof parsed.snapshotRevision !== "string" || typeof parsed.sortAt !== "string" || (sortBy !== "name" && !isSessionListCursorTimestamp(parsed.sortAt)) || (sortBy === "name" && (parsed.sortAt.length > 10_000 || parsed.sortAt.includes("\u0000"))) || typeof parsed.id !== "string" || !UUID_PATTERN.test(parsed.id) ) { return null; } if ( parsed.sortXid !== undefined && (typeof parsed.sortXid !== "string" || BigInt(normalizeActivityToken(parsed.sortXid, "cursor sort xid")) >= 1n << 64n) ) return null; if ( isActivityXidToken(parsed.snapshotRevision) && sortBy === "updatedAt" && parsed.sortXid === undefined ) return null; return { kind: "keyset", ...(parsed.version !== 2 ? { sortBy: sortBy as NonNullable } : {}), snapshotRevision: normalizeSessionActivityRevision( parsed.snapshotRevision, "cursor snapshot revision", ), ...(parsed.sortXid !== undefined ? { sortXid: normalizeActivityToken(String(parsed.sortXid), "cursor sort xid") } : {}), sortAt: parsed.sortAt, id: parsed.id, parentSessionFilter: parentSessionFilter as string, search: search as string | null, archiveMode, filter, }; } if (parsed.version !== undefined) return null; const offset = parsed.offset; if ( typeof parsed.snapshotId !== "string" || !UUID_PATTERN.test(parsed.snapshotId) || typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 ) { return null; } return { kind: "snapshot", snapshotId: parsed.snapshotId, offset, parentSessionFilter: parentSessionFilter as string, search: search as string | null, archiveMode, filter, }; } catch { return null; } } /** Bounded global TTL cleanup, isolated from serializable member list reads. */ export async function reapExpiredSessionListSnapshots(db: Database, limit = 500): Promise { const rows = await rawRows<{ deleted_count: number | string }>( db, sql`select opengeni_private.reap_expired_session_list_snapshots(${limit}) as deleted_count`, ); return Number(rows[0]?.deleted_count ?? 0); } /** Cursor-binding identity for a resolved list scope. A host may return the * same semantic scope with ids in any order across pages; sorting makes the * binding canonical so only a real scope change invalidates a continuation. * Applied ONLY to the binding hash input — the authorization filter itself * always uses the live resolved scope. */ function canonicalSearchScopeIdentity( scope: SessionAuthorizationListScope | undefined, ): SessionAuthorizationListScope | null { if (!scope) return null; if (scope.kind === "all") return scope; return { ...scope, rootSessionIds: [...new Set(scope.rootSessionIds)].sort(), sessionIds: [...new Set(scope.sessionIds)].sort(), }; } /** Bounded full-history message search. The caller must authorize a live grant * and its complete host/agent list scope before entering this RLS projection. */ export async function searchSessionMessagesForSubject( db: Database, workspaceId: string, request: SessionMessageSearchRequest, authority: Pick< ListSessionsForSubjectOptions, "subjectId" | "authorizationScope" | "personalWorkspaceOwnerException" >, options: { signal?: AbortSignal | undefined } = {}, ): Promise { const parsed = SessionMessageSearchRequest.parse(request); options.signal?.throwIfAborted(); // Same session-tenancy, subject RLS and member-removal fence as session lists. // The API must resolve its live grant and complete host/agent list scope first. return withDatabaseStatementTimeout(db, 5_000, (boundedDb) => withWorkspaceSubjectRls(boundedDb, workspaceId, authority.subjectId, async (tx) => { await lockSessionPersonalStateShared(tx, workspaceId, authority.subjectId); const [membership] = await tx .select({ id: schema.workspaceMemberships.id }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, workspaceId), eq(schema.workspaceMemberships.subjectId, authority.subjectId), membershipOutsidePersonalWorkspace(), ), ) .limit(1); if ( !membership && authority.subjectId.startsWith("user:") && !( authority.personalWorkspaceOwnerException === true && (await subjectHasLiveWorkspaceAuthorityInScope(tx, { accountId: await accountIdInRlsScope(tx), workspaceId, subjectId: authority.subjectId, })) ) ) throw new SessionListAccessError(); return scanSessionMessages( tx, workspaceId, parsed, sessionFilters({ ...authority, archiveStatus: parsed.archiveStatus }), [authority.subjectId, canonicalSearchScopeIdentity(authority.authorizationScope)], options.signal, ); }), ); } /** Console projection over live commands, with the same membership and audience * boundary as ordinary chat discovery. Archived chats may still own live work. */ export async function listWorkspaceBackgroundCommandsForSubject( db: Database, workspaceId: string, authority: Pick< ListSessionsForSubjectOptions, "subjectId" | "authorizationScope" | "personalWorkspaceOwnerException" >, afterId?: string, ) { return withWorkspaceSubjectRls(db, workspaceId, authority.subjectId, async (tx) => { await lockSessionPersonalStateShared(tx, workspaceId, authority.subjectId); const [membership] = await tx .select({ id: schema.workspaceMemberships.id }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, workspaceId), eq(schema.workspaceMemberships.subjectId, authority.subjectId), membershipOutsidePersonalWorkspace(), ), ) .limit(1); if ( !membership && authority.subjectId.startsWith("user:") && !( authority.personalWorkspaceOwnerException === true && (await subjectHasLiveWorkspaceAuthorityInScope(tx, { accountId: await accountIdInRlsScope(tx), workspaceId, subjectId: authority.subjectId, })) ) ) throw new SessionListAccessError(); return listWorkspaceBackgroundCommandsInScope( tx, workspaceId, sessionFilters({ ...authority, archiveStatus: "all" }), afterId, ); }); } /** * Server-authoritative member-specific page. Pinned rows are returned separately * and omitted from ordinary pages, so list pagination cannot duplicate a * session. New pages use a bounded activity-revision keyset: page one freezes * the committed workspace revision and every continuation reads only `limit + * 1` candidate ids. Legacy short-lived snapshot cursors remain readable during * rolling upgrades, while hydration always joins live rows for current * lifecycle/title and authorization data. A response that never carries the * Skill folders passes `skills: "omit"`. */ export async function listSessionsForSubject( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, skills: SessionSkillsRead, ): Promise; export async function listSessionsForSubject( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, skills?: "read", ): Promise; export async function listSessionsForSubject( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, skills: SessionSkillsRead = "read", ): Promise { const page = await readSessionListForSubject(db, workspaceId, options, false, skills); if ("projection" in page) throw new Error("Unexpected compact session projection"); if (skills === "read") return page; return { ...page, pinned: page.pinned.map(omitSessionSkills), sessions: page.sessions.map(omitSessionSkills), }; } /** A session-list page whose sessions were read without their Skill folders. */ export type SessionListWithoutSkillsResponse = Omit & { pinned: SessionWithoutSkills[]; sessions: SessionWithoutSkills[]; }; /** Same subject, paging and authorization fences, without execution configuration. */ export async function listSessionEntriesForSubject( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, ): Promise { const page = await readSessionListForSubject(db, workspaceId, options, true); if (!("projection" in page)) throw new Error("Missing compact session projection"); return page; } type SessionListReadAuthority = Pick< ListSessionsForSubjectOptions, "subjectId" | "authorizationScope" | "personalWorkspaceOwnerException" >; /** Apply the same removal fence to pages and their transient invalidation hints. */ async function requireSessionListReadAuthorityInScope( tx: Database, workspaceId: string, options: SessionListReadAuthority, ): Promise { // READ COMMITTED observes a removal that held the exclusive fence first. await lockSessionPersonalStateShared(tx, workspaceId, options.subjectId); const [membership] = await tx .select({ id: schema.workspaceMemberships.id }) .from(schema.workspaceMemberships) .where( and( eq(schema.workspaceMemberships.workspaceId, workspaceId), eq(schema.workspaceMemberships.subjectId, options.subjectId), membershipOutsidePersonalWorkspace(), ), ) .limit(1); // Non-user credentials legitimately have no membership. Managed personal // owners require the route's verified provenance AND current canonical grant. if ( !membership && options.subjectId.startsWith("user:") && !( options.personalWorkspaceOwnerException === true && (await subjectHasLiveWorkspaceAuthorityInScope(tx, { accountId: await accountIdInRlsScope(tx), workspaceId, subjectId: options.subjectId, })) ) ) throw new SessionListAccessError(); } /** No configuration, parent IDs or inaccessible IDs cross the hint boundary. */ export async function listVisibleSessionInvalidationIds( db: Database, workspaceId: string, sessionIds: string[], authority: SessionListReadAuthority, ): Promise { return (await listVisibleSessionInvalidationHints(db, workspaceId, sessionIds, authority)) .sessionIds; } /** * Ordinary IDs plus, separately, the viewer's own visible Site conversations. * A rail with Site rows refreshes their summaries for the latter without * treating every unknown Site conversation as a full list invalidation. */ export async function listVisibleSessionInvalidationHints( db: Database, workspaceId: string, sessionIds: string[], authority: SessionListReadAuthority, ): Promise<{ sessionIds: string[]; siteSessionIds: string[] }> { if (!sessionIds.length) return { sessionIds: [], siteSessionIds: [] }; // Exactly the rows ordinary discovery omits (an agent keeps its own root). const ownRoot = authority.authorizationScope?.agentAccessViewer?.callerRootSessionId; const siteOnly = ownRoot ? sql`(${schema.sessions.siteAccessRootId} is not null and ${schema.sessions.rootSessionId} is distinct from ${ownRoot}::uuid)` : sql`${schema.sessions.siteAccessRootId} is not null`; return await withWorkspaceSubjectRls( db, workspaceId, authority.subjectId, async (tx) => { await requireSessionListReadAuthorityInScope(tx, workspaceId, authority); const rows = await tx .select({ id: schema.sessions.id, site: siteOnly, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), inArray(schema.sessions.id, sessionIds), // Hints carry no content. Site conversations use the same viewer // authorization (and agent bound) as `siteConversations=include`. ...sessionFilters({ ...authority, archiveStatus: "all", siteConversations: "include" }), ), ); return { sessionIds: rows.filter((row) => !row.site).map((row) => row.id), siteSessionIds: rows.filter((row) => row.site).map((row) => row.id), }; }, { isolationLevel: "read committed" }, ); } async function readSessionListForSubject( db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, summary: boolean, skills: SessionSkillsRead = "read", ): Promise { const requestedLimit = options.limit ?? 50; const limit = Number.isFinite(requestedLimit) ? Math.min(500, Math.max(1, Math.floor(requestedLimit))) : 50; const listInTransaction = async (): Promise => { return await withWorkspaceSubjectRls( db, workspaceId, options.subjectId, async (tx) => { await requireSessionListReadAuthorityInScope(tx, workspaceId, options); const archiveMode = options.archiveStatus ?? (options.archivedOnly ? "archived" : "active"); const sortBy = options.sortBy ?? (archiveMode === "archived" ? "archivedAt" : "updatedAt"); if (options.archivedOnly && archiveMode !== "archived") { throw new SessionListCursorError("archivedOnly conflicts with archiveStatus"); } if (options.includeTotals && options.parentSessionId !== null && !options.pinsOnly) throw new SessionListCursorError("Attention totals require root or global pin pages"); const groupSites = options.siteConversations === "group"; if ( groupSites && (options.parentSessionId !== null || options.pinsOnly || archiveMode === "archived" || options.originSiteId || options.siteAccessId) ) throw new SessionListCursorError("App rows require an ordinary, non-archived root page"); // Site rows are a complete section like pins: read once, with page one. const siteGroupsRequested = groupSites && !options.cursor; const completeTotals = options.includeTotals || siteGroupsRequested ? await sessionListTotalsInScope( tx, workspaceId, options.pinsOnly ? { ...options, archiveStatus: "active", parentSessionId: null } : options, siteGroupsRequested, ) : undefined; const totals = options.includeTotals && completeTotals ? { needsYouCount: completeTotals.needsYouCount, groups: completeTotals.groups } : undefined; const siteGroups = siteGroupsRequested ? (completeTotals?.sites ?? []) : undefined; const siteGroupsTruncated = siteGroupsRequested && completeTotals?.sitesTruncated === true; const filters = [eq(schema.sessions.workspaceId, workspaceId), ...sessionFilters(options)]; // A pinned Site conversation is a personal shortcut like any other pin. const pinnedFilters = groupSites ? [ eq(schema.sessions.workspaceId, workspaceId), ...sessionFilters({ ...options, siteConversations: "include" }), ] : filters; const ordinaryPinFilter = archiveMode === "archived" ? sql`true` : or(isNull(schema.sessionPins.id), eq(schema.sessionPins.pinned, false))!; const parentFilter = sessionParentFilter(options.parentSessionId); const searchFilter = sessionSearchFilter(options.search); // Descendants inherit their root's archive ordering, just as they // inherit its archive visibility in sessionFilters. const archiveSortAt = sql`(select ${sessionArchivedAtSql(sql`archive_order`)} from ${schema.sessions} archive_order where archive_order.workspace_id = ${schema.sessions.workspaceId} and archive_order.id = ${schema.sessions.rootSessionId})`; // Locale-independent normalization shared with the UI contract. Do not // use localeCompare/lower(): those depend on deployment/client locale. const ordinarySortAt = sortBy === "name" ? sql`translate(btrim(coalesce(${schema.sessions.title}, '')), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') collate "C"` : sortBy === "createdAt" ? schema.sessions.createdAt : sortBy === "archivedAt" ? archiveSortAt : schema.sessions.updatedAt; const exactOrdinarySortAt = sortBy === "name" ? sql`${ordinarySortAt}` : sql`to_char(${ordinarySortAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`; const exactArchiveSortAt = archiveMode === "active" ? sql`null` : sql`to_char(${archiveSortAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`; const ordinaryOrder = sortBy === "name" ? [asc(ordinarySortAt), asc(schema.sessions.id)] : sortBy === "updatedAt" ? [desc(schema.sessions.activityXid), desc(ordinarySortAt), desc(schema.sessions.id)] : [desc(ordinarySortAt), desc(schema.sessions.id)]; const listFilter = sessionListFilterIdentity(options); const now = new Date(); if (options.pinsOnly && archiveMode === "archived") { throw new SessionListCursorError( "pins-only and archived session lists cannot be combined", ); } if (options.pinsOnly && options.cursor) { throw new SessionListCursorError("pins-only session lists do not accept a cursor"); } if (options.pinsOnly && options.includePinned === false) { throw new SessionListCursorError("pins-only session lists require pin hydration"); } // Never reinterpret a boundary from a different ordering domain. // v4 envelopes retain the reserved snapshot id so older replicas also // take the typed expiry/rebase path instead of mixing sort domains. if ( options.cursor && ((options.cursor.kind === "snapshot" && (sortBy !== "updatedAt" || archiveMode !== "active")) || (options.cursor.kind === "keyset" && (options.cursor.sortBy ?? "updatedAt") !== sortBy)) ) { throw new SessionListCursorExpiredError(); } // Configuration is never exposed by the summary branch. SQL substitutes // typed placeholders before transfer, so large JSON/prompt fields do not // become process allocations. Full reads select every original column // and, unless the caller omits them, the Skill folders a complete // Session carries. const fullColumns = sessionReadColumns(skills); const listColumns = summary ? { ...fullColumns, resources: sql`'[]'::jsonb`, skills: sql`'[]'::jsonb`, tools: sql`'[]'::jsonb`, instructions: sql`null::text`, initialModelContext: sql`null::text`, agentConfig: sql`null::jsonb`, mcpApprovalPolicies: sql`null::jsonb`, // Only list-entry fields are reliable here: `unattended` is not // (the create option's key is left out) and SessionListEntry omits it. metadata: sql`jsonb_build_object( 'scheduledTaskId', ${schema.sessions.metadata}->'scheduledTaskId', '_opengeniSiteOrigin', ${schema.sessions.metadata}->'_opengeniSiteOrigin')`, createdByContext: sql< SessionRow["createdByContext"] >`jsonb_build_object('label', ${schema.sessions.createdByContext}->'label')`, // Each tagged code unit may expand in storage. Derive the worst-case // prefix from the codec, then apply the exact shared logical scan bound. initialMessage: sql`left(${schema.sessions.initialMessage}, case when ${schema.sessions.initialMessageCodecVersion} = 1 then ${PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS * toPostgresLosslessText("\0").length}::integer else ${PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS}::integer end)`, } : fullColumns; let pageIds: string[]; // Keep each selected row in the same MVCC statement as its filters and // keyset boundary. A second READ COMMITTED hydration can observe a move // or activity change and return content that no longer matches the page. let selectedOrdinaryRows: | Array<{ session: SessionRowWithSkills; pin: typeof schema.sessionPins.$inferSelect | null; }> | undefined; let nextCursor: string | null = null; // Keep archive ordering precision in the public root projection as well // as the cursor. Drizzle's Date hydration otherwise loses microseconds. const exactArchiveTimestamps = new Map(); // The public selected date key must match the SQL/cursor key so clients // merging pages do not collapse sub-millisecond ordering into id ties. const exactOrdinaryTimestamps = new Map(); if (options.pinsOnly) { // The rail polls the complete personal pin section independently from // its root page. Do not turn that cheap projection into an O(N) // ordinary-session scan or a throwaway continuation snapshot. pageIds = []; } else if (options.cursor?.kind === "snapshot") { const cursor = options.cursor; if ( cursor.parentSessionFilter !== parentFilter || cursor.search !== searchFilter || cursor.archiveMode !== archiveMode || (cursor.filter ?? "all") !== listFilter || listFilter !== "all" ) { throw new SessionListCursorError("session list cursor does not match its filters"); } const [snapshot] = await tx .select() .from(schema.sessionListSnapshots) .where( and( eq(schema.sessionListSnapshots.id, cursor.snapshotId), eq(schema.sessionListSnapshots.workspaceId, workspaceId), eq(schema.sessionListSnapshots.subjectId, options.subjectId), ), ) .limit(1); if (!snapshot || snapshot.expiresAt.getTime() <= now.getTime()) { throw new SessionListCursorExpiredError(); } if ( snapshot.parentSessionFilter !== parentFilter || (snapshot.search ?? null) !== searchFilter || snapshot.archiveMode !== archiveMode || cursor.offset > snapshot.ordinarySessionIds.length ) { throw new SessionListCursorError(); } let nextOffset: number | null = null; { // A host may revoke rows between pages. Scan the immutable snapshot // in bounded database-filtered batches until this page is full plus // one authorized lookahead; never hydrate a stale broad slice and // return a short/empty page while later authorized rows still exist. const visible: Array<{ id: string; offsetAfter: number }> = []; const scanBatchSize = Math.max(500, Math.min(2_000, limit * 4)); let scanOffset = cursor.offset; while (scanOffset < snapshot.ordinarySessionIds.length && visible.length < limit + 1) { const batchEnd = Math.min( snapshot.ordinarySessionIds.length, scanOffset + scanBatchSize, ); const candidates = snapshot.ordinarySessionIds.slice(scanOffset, batchEnd); const allowedRows = await tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), anyOf(schema.sessions.id, candidates), sql`${schema.sessions.siteAccessRootId} is null`, ...(options.authorizationScope ? [sessionAuthorizationScopeFilter(options.authorizationScope)] : []), ), ); const allowed = new Set(allowedRows.map((row) => row.id)); for (let index = 0; index < candidates.length; index += 1) { const id = candidates[index]!; if (allowed.has(id)) { visible.push({ id, offsetAfter: scanOffset + index + 1 }); if (visible.length >= limit + 1) break; } } scanOffset = batchEnd; } pageIds = visible.slice(0, limit).map((row) => row.id); if (visible.length > limit) { nextOffset = visible[limit - 1]!.offsetAfter; } } if (nextOffset !== null) { nextCursor = encodeSessionListCursor({ kind: "snapshot", snapshotId: snapshot.id, offset: nextOffset, parentSessionFilter: snapshot.parentSessionFilter, search: snapshot.search ?? null, archiveMode: snapshot.archiveMode, filter: "all", }); } } else if (options.materializeSnapshot === false) { const ordinaryIdRows = await tx .select({ id: schema.sessions.id, session: listColumns, pin: schema.sessionPins, sortAt: exactOrdinarySortAt, archiveAt: exactArchiveSortAt, }) .from(schema.sessions) .leftJoin( schema.sessionPins, and( eq(schema.sessionPins.workspaceId, workspaceId), eq(schema.sessionPins.subjectId, options.subjectId), eq(schema.sessionPins.sessionId, schema.sessions.id), ), ) .where(and(...filters, ordinaryPinFilter)) .orderBy(...ordinaryOrder) .limit(limit); pageIds = ordinaryIdRows.map((row) => row.id); selectedOrdinaryRows = ordinaryIdRows; if (sortBy === "updatedAt" || sortBy === "createdAt") { for (const row of ordinaryIdRows) exactOrdinaryTimestamps.set(row.id, row.sortAt); } if (archiveMode !== "active") { for (const row of ordinaryIdRows) exactArchiveTimestamps.set(row.id, row.archiveAt); } } else { // A legacy boundary is in a different ordering domain. Restart rather // than interpreting its counter as an xid and silently losing rows. const requestedCursor = options.cursor?.kind === "keyset" ? options.cursor : undefined; const cursor = requestedCursor && isActivityXidToken(requestedCursor.snapshotRevision) ? requestedCursor : undefined; if ( cursor && (cursor.parentSessionFilter !== parentFilter || cursor.search !== searchFilter || cursor.archiveMode !== archiveMode || (cursor.filter ?? "all") !== listFilter) ) { throw new SessionListCursorError("session list cursor does not match its filters"); } const snapshotRevision = encodeActivityXid("0"); const timestampCursorPredicate = cursor ? sortBy === "name" ? or( sql`${ordinarySortAt} > ${cursor.sortAt}::text collate "C"`, and( sql`${ordinarySortAt} = ${cursor.sortAt}::text collate "C"`, gt(schema.sessions.id, cursor.id), ), ) : or( sql`${ordinarySortAt} < ${cursor.sortAt}::text::timestamptz`, and( sql`${ordinarySortAt} = ${cursor.sortAt}::text::timestamptz`, lt(schema.sessions.id, cursor.id), ), ) : undefined; const cursorPredicate = sortBy === "updatedAt" && cursor ? sql`(${schema.sessions.activityXid}, ${schema.sessions.updatedAt}, ${schema.sessions.id}) < (${cursor.sortXid ?? "0"}::xid8, ${cursor.sortAt}::timestamptz, ${cursor.id}::uuid)` : timestampCursorPredicate; const ordinaryIdRows = await tx .select({ id: schema.sessions.id, session: listColumns, pin: schema.sessionPins, sortAt: exactOrdinarySortAt, archiveAt: exactArchiveSortAt, sortXid: sql`${schema.sessions.activityXid}::text`, }) .from(schema.sessions) .leftJoin( schema.sessionPins, and( eq(schema.sessionPins.workspaceId, workspaceId), eq(schema.sessionPins.subjectId, options.subjectId), eq(schema.sessionPins.sessionId, schema.sessions.id), ), ) .where(and(...filters, ordinaryPinFilter, cursorPredicate)) .orderBy(...ordinaryOrder) .limit(limit + 1); const hasMore = ordinaryIdRows.length > limit; const page = ordinaryIdRows.slice(0, limit); pageIds = page.map((row) => row.id); selectedOrdinaryRows = page; if (sortBy === "updatedAt" || sortBy === "createdAt") { for (const row of page) exactOrdinaryTimestamps.set(row.id, row.sortAt); } if (archiveMode !== "active") { for (const row of page) exactArchiveTimestamps.set(row.id, row.archiveAt); } const last = page.at(-1); if (hasMore && last) { nextCursor = encodeSessionListCursor({ kind: "keyset", sortBy, snapshotRevision, sortXid: last.sortXid, sortAt: last.sortAt, id: last.id, parentSessionFilter: parentFilter, search: searchFilter, archiveMode, filter: listFilter, }); } } const pinnedLookaheadRows = archiveMode === "archived" || options.includePinned === false ? [] : await tx .select({ session: listColumns, pin: schema.sessionPins }) .from(schema.sessionPins) .innerJoin(schema.sessions, eq(schema.sessions.id, schema.sessionPins.sessionId)) .where( and( eq(schema.sessionPins.workspaceId, workspaceId), eq(schema.sessionPins.subjectId, options.subjectId), eq(schema.sessionPins.pinned, true), ...pinnedFilters, ), ) .orderBy(desc(schema.sessionPins.pinnedAt), desc(schema.sessions.id)) .limit(SESSION_LIST_MAX_PINNED + 1); const pinnedTruncated = pinnedLookaheadRows.length > SESSION_LIST_MAX_PINNED; const pinnedRows = pinnedLookaheadRows.slice(0, SESSION_LIST_MAX_PINNED); const ordinaryRows = selectedOrdinaryRows ?? (pageIds.length === 0 ? [] : await tx .select({ session: listColumns, pin: schema.sessionPins }) .from(schema.sessions) .leftJoin( schema.sessionPins, and( eq(schema.sessionPins.workspaceId, workspaceId), eq(schema.sessionPins.subjectId, options.subjectId), eq(schema.sessionPins.sessionId, schema.sessions.id), ), ) .where( and( eq(schema.sessions.workspaceId, workspaceId), anyOf(schema.sessions.id, pageIds), ...(options.authorizationScope ? [sessionAuthorizationScopeFilter(options.authorizationScope)] : []), ordinaryPinFilter, ), )); const ordinaryById = new Map(ordinaryRows.map((row) => [row.session.id, row])); const pageRows = pageIds.flatMap((id) => { const row = ordinaryById.get(id); return row ? [row] : []; }); const ids = [ ...pinnedRows.map((row) => row.session.id), ...pageRows.map((row) => row.session.id), ]; const canonicalRows = await canonicalSessionRowsFromEventCursors( tx, workspaceId, [...pinnedRows, ...pageRows].map((row) => row.session), false, ); // Every list page names each row's model with two fixed index probes // per row. The effective-policy walk can scan back over every turn // started since the last settings write, which took seconds on long // sessions; a single-session read still uses it. const canonicalSessions = await withSessionListModelPolicy(tx, workspaceId, canonicalRows); const canonicalSessionById = new Map( canonicalSessions.map((session) => [session.id, session]), ); const mcpServers = summary ? new Map() : await sessionMcpServerMetadataForSessions(tx, workspaceId, ids); const rootRelatedIds = await sessionIdsCoveredByAuthorizationRoots( tx, workspaceId, ids, options.authorizationScope, ); const treeStats = await sessionTreeStatsForSessions( tx, workspaceId, [...rootRelatedIds], options.subjectId, ); const requiresActionSince = await sessionRequiresActionSinceForSessions( tx, workspaceId, [...pinnedRows, ...pageRows] .filter((row) => row.session.status === "requires_action") .map((row) => row.session.id), ); const controls = await sessionControlProjections(tx, workspaceId, ids); const latestTurns = summary ? await sessionLatestTurnsForSessions(tx, workspaceId, ids) : new Map(); const mapListSession = ( row: (typeof pinnedRows)[number] | (typeof pageRows)[number], ): Session => { const canonical = canonicalSessionById.get(row.session.id); if (!canonical) throw new Error(`Session event cursor missing for session ${row.session.id}`); const session = summary ? { ...canonical, initialMessage: fromPostgresLosslessText( canonical.initialMessage, canonical.initialMessageCodecVersion, ).slice(0, PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS), initialMessageCodecVersion: 0, } : canonical; const control = controls.get(session.id); if (!control) throw new Error(`Effective control missing for session ${session.id}`); return projectSessionForRelatedAccess( withRequiresActionSince( { ...mapSession( session, control, mcpServers.get(session.id) ?? [], mapSessionPin(row.pin), mapSessionAttention(session, row.pin), { ...mapSessionArchive(row.pin), ...(exactArchiveTimestamps.get(session.id) ? { archivedAt: exactArchiveTimestamps.get(session.id)! } : {}), }, { subjectId: options.subjectId }, ), ...(sortBy === "updatedAt" && exactOrdinaryTimestamps.has(session.id) ? { updatedAt: exactOrdinaryTimestamps.get(session.id)! } : {}), ...(sortBy === "createdAt" && exactOrdinaryTimestamps.has(session.id) ? { createdAt: exactOrdinaryTimestamps.get(session.id)! } : {}), treeStats: treeStats.get(session.id) ?? EMPTY_SESSION_TREE_STATS, }, requiresActionSince, ), rootRelatedIds.has(session.id) ? "root" : "target", ); }; const listEntry = (row: (typeof pinnedRows)[number] | (typeof pageRows)[number]) => ({ ...sessionListEntry(mapListSession(row)), latestTurn: latestTurns.get(row.session.id) ?? null, }); if (summary) return { projection: "summary", ...(totals ? { totals } : {}), ...(options.needsYouOnly ? { needsYouOnly: true as const } : {}), ...(options.contentArchivedOnly ? { contentArchivedOnly: true as const } : {}), ...(options.mineOnly ? { mineOnly: true as const } : {}), ...(options.sessionIds ? { sessionIdsApplied: true as const } : {}), ...(options.siteConversations ? { siteConversations: options.siteConversations } : {}), ...(siteGroups ? { siteGroups } : {}), ...(siteGroupsTruncated ? { siteGroupsTruncated: true } : {}), pinned: pinnedRows.map(listEntry), pinnedTruncated, sessions: pageRows.map(listEntry), nextCursor, sortBy, archiveStatus: archiveMode, }; return { ...(totals ? { totals } : {}), ...(options.needsYouOnly ? { needsYouOnly: true as const } : {}), ...(options.contentArchivedOnly ? { contentArchivedOnly: true as const } : {}), ...(options.mineOnly ? { mineOnly: true as const } : {}), ...(options.sessionIds ? { sessionIdsApplied: true as const } : {}), ...(options.siteConversations ? { siteConversations: options.siteConversations } : {}), ...(siteGroups ? { siteGroups } : {}), ...(siteGroupsTruncated ? { siteGroupsTruncated: true } : {}), pinned: pinnedRows.map(mapListSession), pinnedTruncated, sessions: pageRows.map(mapListSession), nextCursor, sortBy, archiveStatus: archiveMode, }; }, { isolationLevel: "read committed" }, ); }; for (let attempt = 1; attempt <= SESSION_LIST_SERIALIZATION_MAX_ATTEMPTS; attempt += 1) { try { return await listInTransaction(); } catch (error) { if ( !isPostgresSerializationFailure(error) || attempt === SESSION_LIST_SERIALIZATION_MAX_ATTEMPTS ) { throw error; } // A 40001 invalidates the complete transaction, not only the statement // that happens to surface it. Every list-side write is part of that // rolled-back transaction, so retry the whole operation after a short // bounded yield without an unbounded request loop or partially committed // snapshot. await new Promise((resolve) => setTimeout(resolve, attempt * 10)); } } throw new Error("unreachable session list retry state"); } /** Read a session with the caller subject's personal pin projection. */ /** Read failure evidence at the already-authorized detail cursor, never a browser page. * Event rows are immutable; the sequence fence keeps these reads coherent even * if another turn is accepted while the detail projection is being assembled. * Keep this off fleet/list/worker reads. Existing type/turn indexes cover it. */ async function sessionFailureDiagnostics( db: Database, workspaceId: string, session: { id: string; lastSequence: number; status: string }, ): Promise { if (session.status !== "failed") return null; const scope = and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, session.id), lte(schema.sessionEvents.sequence, session.lastSequence), isNull(schema.sessionEvents.duplicateOfEventId), or( isNull(schema.sessionEvents.turnAssociation), eq(schema.sessionEvents.turnAssociation, "current"), ), ); // Transfer only codec-aware prefixes. Cutting an encoded storage scalar // directly would show base64 rather than the accepted logical error text. const maxChars = 1024; const storageChars = sessionTextStoragePrefixChars(maxChars); const diagnosticFields = ["error", "message", "detail", "lastRetryableError", "code", "status"]; const boundedFields = diagnosticFields.flatMap((field) => { const scalar = sql`case when jsonb_typeof(${schema.sessionEvents.payload}->${field}::text) = 'string' then ${schema.sessionEvents.payload}->>${field}::text else null end`; return [ sql`${field}::text`, sql`jsonb_build_object( 'prefix', left(${scalar}, ${storageChars}), 'chars', char_length(${scalar}), 'encoded', ${sessionMcpProgressScalarIsEncodedSql(scalar, schema.sessionEvents.payloadCodecVersion)})`, ]; }); const projectedPayload = sql>`jsonb_build_object( ${sql.join(boundedFields, sql`, `)}, 'providerRecoveryCount', case when jsonb_typeof(${schema.sessionEvents.payload}->'providerRecoveryCount') = 'number' and length((${schema.sessionEvents.payload}->'providerRecoveryCount')::text) <= 16 then ${schema.sessionEvents.payload}->'providerRecoveryCount' else 'null'::jsonb end, 'quotaScope', case when jsonb_typeof(${schema.sessionEvents.payload}->'quotaScope') = 'string' and ${schema.sessionEvents.payload}->>'quotaScope' in ('daily', 'monthly', 'credits', 'quota') then ${schema.sessionEvents.payload}->'quotaScope' else 'null'::jsonb end)`; const latest = async (type: string) => { const [row] = await db .select({ id: schema.sessionEvents.id, sequence: schema.sessionEvents.sequence, turnId: schema.sessionEvents.turnId, occurredAt: schema.sessionEvents.occurredAt, codecVersion: schema.sessionEvents.payloadCodecVersion, payload: projectedPayload, }) .from(schema.sessionEvents) .where(and(scope, eq(schema.sessionEvents.type, type))) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); if (!row) return null; // The closed exhausted-provider-quota marker is projected only as one of // its four literal values, so it adds no unbounded text. const payload: Record = { providerRecoveryCount: row.payload.providerRecoveryCount, ...(typeof row.payload.quotaScope === "string" ? { quotaScope: row.payload.quotaScope } : {}), }; const truncatedFields: string[] = []; for (const field of diagnosticFields) { const stored = row.payload[field] as { prefix: string | null; chars: number | null; encoded: boolean; }; const projected = projectSessionTextPrefix( stored.prefix, stored.chars, row.codecVersion, stored.encoded, maxChars, ); payload[field] = projected.text; if (projected.textTruncated || (projected.originalChars ?? 0) > maxChars) truncatedFields.push(field); } // Six 1024-character logical strings remain below 40KiB even when JSON // escapes every character as six bytes. Stored values remain untouched. payload.projection = { fieldsOnly: true, fieldLimitChars: maxChars, truncatedFields }; return { ...row, payload, occurredAt: row.occurredAt.toISOString() }; }; const turnFailure = await latest("turn.failed"); const latestStatus = await latest("session.status.changed"); const statusPayload = latestStatus?.payload as Record | undefined; // Do not associate an earlier failure with a later recorded revival. if ( latestStatus && (!turnFailure || latestStatus.sequence > turnFailure.sequence) && typeof statusPayload?.status === "string" && statusPayload.status !== "failed" ) return null; const preClaimFailure = statusPayload?.status === "failed" && statusPayload.code === "pre_claim_failure" ? latestStatus : null; const failure = preClaimFailure && (!turnFailure || (preClaimFailure.sequence > turnFailure.sequence && (!preClaimFailure.turnId || preClaimFailure.turnId !== turnFailure.turnId))) ? preClaimFailure : turnFailure; if (!failure) return null; return { eventId: failure.id, sequence: failure.sequence, turnId: failure.turnId ?? null, occurredAt: failure.occurredAt, payload: failure.payload, }; } /** A response that never carries the Skill folders passes `skills: "omit"`. */ export async function getSessionForSubject( db: Database, workspaceId: string, sessionId: string, subjectId: string, relatedSessionAccess: "target" | "root", skills: SessionSkillsRead, ): Promise; export async function getSessionForSubject( db: Database, workspaceId: string, sessionId: string, subjectId: string, relatedSessionAccess?: "target" | "root", skills?: "read", ): Promise; export async function getSessionForSubject( db: Database, workspaceId: string, sessionId: string, subjectId: string, relatedSessionAccess: "target" | "root" = "root", skills: SessionSkillsRead = "read", ): Promise { return await withWorkspaceSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const [row] = await scopedDb .select({ session: sessionReadColumns(skills), pin: schema.sessionPins, cursor: schema.sessionEventCursors, }) .from(schema.sessions) // Status and replay cursor must share one statement snapshot. Otherwise a // concurrent revival can pair an old failed row with a new running cursor, // causing the browser to skip the very event that would refresh its status. .leftJoin( schema.sessionEventCursors, and( eq(schema.sessionEventCursors.workspaceId, schema.sessions.workspaceId), eq(schema.sessionEventCursors.sessionId, schema.sessions.id), ), ) .leftJoin( schema.sessionPins, and( eq(schema.sessionPins.workspaceId, workspaceId), eq(schema.sessionPins.subjectId, subjectId), eq(schema.sessionPins.sessionId, schema.sessions.id), ), ) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' and private_slack_interaction.owning_subject_id <> ${subjectId} )`, ), ) .limit(1); if (!row) return null; if ( !row.cursor || row.cursor.accountId !== row.session.accountId || row.cursor.lastSequence < row.session.lastSequence ) { throw new Error(`Session event cursor invariant failed for session ${sessionId}`); } // mapSessionWithControl projects the effective policy below, once. const handledFailure = ( await sessionIdsWithHandledFailure(scopedDb, workspaceId, [row.session]) ).has(sessionId); const questionWithAgent = ( await sessionIdsWithQuestionsWithAgent(scopedDb, workspaceId, [row.session]) ).has(sessionId); const [session] = await withCurrentSessionInputWait(scopedDb, workspaceId, [ { ...row.session, lastSequence: row.cursor.lastSequence, meaningfulSequence: row.cursor.lastMeaningfulSequence, ...(handledFailure ? { failureHandled: true } : {}), ...(questionWithAgent ? { questionWithAgent: true } : {}), }, ]); if (!session) throw new Error(`Session event cursor missing for session ${sessionId}`); const mcpServers = await sessionMcpServerMetadataForSessions(scopedDb, workspaceId, [ sessionId, ]); const failureDiagnostics = await sessionFailureDiagnostics(scopedDb, workspaceId, session); const projected = projectSessionForRelatedAccess( { ...(await mapSessionWithControl( scopedDb, session, mcpServers.get(sessionId) ?? [], mapSessionPin(row.pin), mapSessionAttention(session, row.pin), mapSessionArchive(row.pin), undefined, { subjectId }, )), failureDiagnostics, }, relatedSessionAccess, ); return skills === "read" ? projected : omitSessionSkills(projected); }); } /** * Idempotently set a member's pin without mutating the session's lifecycle or * activity timestamps. A subject-scoped transaction advisory lock serializes * personal pin mutations across API replicas and fences list projections; * expectedVersion rejects stale tabs. */ export async function setSessionPin( db: Database, input: { workspaceId: string; subjectId: string; sessionId: string; pinned: boolean; expectedVersion?: number | undefined; /** See {@link PersonalWorkspaceOwnerException}. Absent means "no exception". */ personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }, ): Promise { return await withWorkspaceSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => await scopedDb.transaction(async (tx) => { // An exclusive subject fence keeps list projections stable and // serializes with member removal before changing personal state. A stale // API grant cannot recreate a pin after removal commits. await lockSessionPersonalStateExclusive(tx, input.workspaceId, input.subjectId); await requireSessionPersonalStateWriteAuthority(tx, input); const [storedSession] = await tx .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!storedSession) return null; const [session] = await canonicalSessionRowsFromEventCursors(tx, input.workspaceId, [ storedSession, ]); if (!session) throw new Error(`Session event cursor missing for session ${input.sessionId}`); const [existing] = await tx .select() .from(schema.sessionPins) .where( and( eq(schema.sessionPins.workspaceId, input.workspaceId), eq(schema.sessionPins.subjectId, input.subjectId), eq(schema.sessionPins.sessionId, input.sessionId), ), ) .limit(1); const current = mapSessionPin(existing); // Desired-state retries are idempotent even when their OCC revision is // stale. This is essential for a client that timed out after the server // committed: retrying the same pin/unpin must observe success, not a // conflict. OCC only protects a request that would CHANGE current state. if (current.pinned === input.pinned) { const mcpServers = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ session.id, ]); return await mapSessionWithControl( tx as unknown as Database, session, mcpServers.get(session.id) ?? [], mapSessionPin(existing), mapSessionAttention(session, existing), mapSessionArchive(existing), ); } if (input.expectedVersion !== undefined && input.expectedVersion !== current.pinVersion) { throw new SessionPinVersionConflictError(current); } // The Pinned list shows chats that are not archived, so an archived // chat cannot be pinned; unpinning one is always allowed. if (input.pinned && sessionRowArchive(session).archived) { throw new SessionArchivedPinError(); } let pin = existing ?? null; if (!existing) { const [inserted] = await tx .insert(schema.sessionPins) .values({ accountId: session.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, sessionId: input.sessionId, // The equal-state return above means an absent row can only // transition false -> true here; initial unpin stays row-free at // version zero instead of manufacturing an OCC revision. pinned: true, pinnedAt: new Date(), attentionVersion: 0, archiveVersion: 0, }) // A turn claim may have created this subject's row for the same // session between the read above and here, to acknowledge a // consumed child lifecycle notice. That writer keeps the pin domain // exactly at the absent-row projection (`pinned` false, version 0), // so the conflict path is the same false -> true transition; only // the attention fence it owns must survive untouched. .onConflictDoUpdate({ target: [ schema.sessionPins.subjectId, schema.sessionPins.workspaceId, schema.sessionPins.sessionId, ], set: { pinned: true, pinnedAt: new Date(), version: sql`${schema.sessionPins.version} + 1`, }, }) .returning(); pin = inserted ?? null; } else if (existing.pinned !== input.pinned) { const [updated] = await tx .update(schema.sessionPins) .set({ pinned: input.pinned, pinnedAt: input.pinned ? new Date() : null, version: sql`${schema.sessionPins.version} + 1`, }) .where( and( eq(schema.sessionPins.workspaceId, input.workspaceId), eq(schema.sessionPins.subjectId, input.subjectId), eq(schema.sessionPins.sessionId, input.sessionId), ), ) .returning(); pin = updated ?? null; } const mcpServers = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ session.id, ]); return await mapSessionWithControl( tx as unknown as Database, session, mcpServers.get(session.id) ?? [], mapSessionPin(pin), mapSessionAttention(session, pin), mapSessionArchive(pin), ); }), ); } /** * Idempotently update one member's explicit follow-up state. Route reads remain * side-effect free: a foreground client acknowledges its exact rendered event * frontier through this mutation, and later durable events remain unread. */ export async function setSessionAttention( db: Database, input: { workspaceId: string; subjectId: string; sessionId: string; unread?: boolean | undefined; acknowledgedThroughSequence?: number | undefined; activelyWorking?: boolean | undefined; expectedVersion?: number | undefined; /** See {@link PersonalWorkspaceOwnerException}. Absent means "no exception". */ personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }, ): Promise { return await withWorkspaceSubjectRls( db, input.workspaceId, input.subjectId, async (scopedDb) => await scopedDb.transaction(async (tx) => { await lockSessionPersonalStateExclusive(tx, input.workspaceId, input.subjectId); await requireSessionPersonalStateWriteAuthority(tx, input); const [storedSession] = await tx .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!storedSession) return null; const [session] = await canonicalSessionRowsFromEventCursors(tx, input.workspaceId, [ storedSession, ]); if (!session) throw new Error(`Session event cursor missing for session ${input.sessionId}`); const [existing] = await tx .select() .from(schema.sessionPins) .where( and( eq(schema.sessionPins.workspaceId, input.workspaceId), eq(schema.sessionPins.subjectId, input.subjectId), eq(schema.sessionPins.sessionId, input.sessionId), ), ) .limit(1); const current = mapSessionAttention(session, existing); const currentAcknowledgedSequence = existing?.acknowledgedSequence ?? 0; const acknowledgedSequence = input.unread === undefined ? currentAcknowledgedSequence : input.unread ? -1 : Math.max( currentAcknowledgedSequence, Math.min( input.acknowledgedThroughSequence ?? session.lastSequence, session.lastSequence, ), ); const desiredActivelyWorking = input.activelyWorking ?? current.activelyWorking; const manuallyUnreadThrough = input.unread === undefined ? (existing?.manuallyUnreadThrough ?? null) : input.unread ? session.lastSequence : null; if ( acknowledgedSequence === currentAcknowledgedSequence && manuallyUnreadThrough === (existing?.manuallyUnreadThrough ?? null) && desiredActivelyWorking === current.activelyWorking ) { const mcpServers = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ session.id, ]); return await mapSessionWithControl( tx as unknown as Database, session, mcpServers.get(session.id) ?? [], mapSessionPin(existing), current, ); } if ( input.expectedVersion !== undefined && input.expectedVersion !== current.attentionVersion ) { throw new SessionAttentionVersionConflictError(current); } // A turn claim acknowledging a consumed child lifecycle notice advances // this same fence for this same subject without holding the personal // state fence above (it must not: membership removal takes that fence // BEFORE the workspace/session lock prefix a claim already owns). Marking // read must therefore never regress a fence that committed after the read // above. An explicit mark-unread is the one deliberate regression and // keeps its exact sentinel. const monotonicAcknowledgment = input.unread !== true; const acknowledgedSequenceWrite = monotonicAcknowledgment ? sql`greatest(${schema.sessionPins.acknowledgedSequence}, ${acknowledgedSequence})` : acknowledgedSequence; let state = existing ?? null; if (!existing) { const [inserted] = await tx .insert(schema.sessionPins) .values({ accountId: session.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, sessionId: input.sessionId, pinned: false, pinnedAt: null, version: 0, acknowledgedSequence, manuallyUnreadThrough, activelyWorking: desiredActivelyWorking, attentionVersion: 1, archiveVersion: 0, }) .onConflictDoUpdate({ target: [ schema.sessionPins.subjectId, schema.sessionPins.workspaceId, schema.sessionPins.sessionId, ], set: { acknowledgedSequence: acknowledgedSequenceWrite, manuallyUnreadThrough, activelyWorking: desiredActivelyWorking, attentionVersion: sql`${schema.sessionPins.attentionVersion} + 1`, }, }) .returning(); state = inserted ?? null; } else { const [updated] = await tx .update(schema.sessionPins) .set({ acknowledgedSequence: acknowledgedSequenceWrite, manuallyUnreadThrough, activelyWorking: desiredActivelyWorking, attentionVersion: sql`${schema.sessionPins.attentionVersion} + 1`, }) .where( and( eq(schema.sessionPins.workspaceId, input.workspaceId), eq(schema.sessionPins.subjectId, input.subjectId), eq(schema.sessionPins.sessionId, input.sessionId), ), ) .returning(); state = updated ?? null; } const mcpServers = await sessionMcpServerMetadataForSessions(tx, input.workspaceId, [ session.id, ]); return await mapSessionWithControl( tx as unknown as Database, session, mcpServers.get(session.id) ?? [], mapSessionPin(state), mapSessionAttention(session, state), mapSessionArchive(state), ); }), ); } export async function listSessions( db: Database, workspaceId: string, limit?: number, ): Promise; export async function listSessions( db: Database, workspaceId: string, options?: ListSessionsOptions, ): Promise; export async function listSessions( db: Database, workspaceId: string, limitOrOptions: number | ListSessionsOptions = 50, ): Promise { const options = typeof limitOrOptions === "number" ? { limit: limitOrOptions } : limitOrOptions; const limit = options.limit ?? 50; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const filters: SQL[] = [eq(schema.sessions.workspaceId, workspaceId)]; if (Object.prototype.hasOwnProperty.call(options, "parentSessionId")) { const parentSessionId = options.parentSessionId; if (parentSessionId === null) { filters.push(isNull(schema.sessions.parentSessionId)); } else if (parentSessionId !== undefined) { filters.push(eq(schema.sessions.parentSessionId, parentSessionId)); } } const rows = await scopedDb .select(sessionRowWithSkillsColumns) .from(schema.sessions) .where(and(...filters)) .orderBy(desc(schema.sessions.createdAt), desc(schema.sessions.id)) .limit(limit); const canonicalRows = await canonicalSessionRowsFromEventCursors(scopedDb, workspaceId, rows); const grouped = await sessionMcpServerMetadataForSessions( scopedDb, workspaceId, canonicalRows.map((row) => row.id), ); const controls = await sessionControlProjections( scopedDb, workspaceId, canonicalRows.map((row) => row.id), ); return canonicalRows.map((row) => { const control = controls.get(row.id); if (!control) throw new Error(`Effective control missing for session ${row.id}`); return mapSession(row, control, grouped.get(row.id) ?? []); }); }); } /** * Return the model most recently chosen by one human subject in their own * workspace sessions. A later subject-initiated turn supersedes the session's * creation-time default; sessions with no such turn fall back to sessions.model. * Turn timestamp ties use queue position then UUID, and session ties use the * immutable session timestamp/UUID. Other subjects' turns never influence the * result. The workspace filter remains authoritative under FORCE RLS. */ export async function getLatestSessionModelForSubject( db: Database, workspaceId: string, subjectId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute<{ model: string }>(sql` select coalesce(latest_subject_turn.model, subject_session.model) as model from ${schema.sessions} subject_session left join lateral ( select subject_turn.id, subject_turn.model, subject_turn.position, subject_turn.created_at from ${schema.sessionTurns} subject_turn where subject_turn.workspace_id = ${workspaceId} and subject_turn.session_id = subject_session.id and subject_turn.initiator_kind = 'subject' and subject_turn.initiator_subject_id = ${subjectId} order by subject_turn.created_at desc, subject_turn.position desc, subject_turn.id desc limit 1 ) latest_subject_turn on true where subject_session.workspace_id = ${workspaceId} and subject_session.created_by_kind = 'subject' and subject_session.created_by_subject_id = ${subjectId} order by coalesce(latest_subject_turn.created_at, subject_session.created_at) desc, (latest_subject_turn.id is not null) desc, subject_session.created_at desc, subject_session.id desc, latest_subject_turn.position desc nulls last, latest_subject_turn.id desc nulls last limit 1 `); return rows[0]?.model ?? null; }); } export type SessionDiscoveryOrderBy = "createdAt" | "updatedAt" | "relevance"; export type SessionDiscoveryCursor = { /** Site provenance is bound for chronological as well as relevance lists. */ originSiteId?: string; orderBy: SessionDiscoveryOrderBy; /** Stable rank class for relevance order; null for chronological order. */ sortRank: number | null; /** Decimal database activity revision; zero is the legacy/created-order bucket. */ sortRevision: string; /** Exact PostgreSQL timestamp text (including microseconds), not a JS Date. */ sortAt: string; id: string; /** Created-order timestamp ceiling; retained as diagnostic context for updated order. */ snapshotAt: string; /** First-page revision fence: later activity belongs to the next incremental scan. */ snapshotRevision: string; /** Incremental revision scope is cursor-bound and cannot change on continuation. */ updatedAfter: string | null; /** SHA-256 of normalized relevance filters; null for chronological order. */ filterHash: string | null; }; export const SESSION_DISCOVERY_GOAL_MAX_CHARS = 600; export const SESSION_DISCOVERY_MESSAGE_MAX_CHARS = 600; /** Who can see a session: only its owner, or everyone in the workspace. */ export type SessionDiscoveryVisibility = "private" | "workspace"; export type SessionDiscoverySummary = { id: string; title: string | null; titleOriginalChars: number | null; visibility: SessionDiscoveryVisibility; /** Archived to long-term storage: read-only, still readable. */ archived: boolean; channelId?: string | null; parentSessionId: string | null; rootSessionId: string; nestedAgentDepth: number; status: SessionStatus; effectiveControl: SessionDiscoveryControl; goal: { status: SessionGoalStatus; text: string; textOriginalChars: number; } | null; queuedPromptCount: number; treeStats: NonNullable; latestMessage: { type: SessionEventType; preview: string | null; previewOriginalChars: number | null; } | null; workDiscovery: WorkDiscoveryProjection; createdAt: string; updatedAt: string; /** Internal exact revision key; omitted from the MCP row projection. */ sortRevision: string; /** Internal exact keyset timestamp; omitted from the MCP row projection. */ sortAt: string; /** Internal stable relevance class; omitted from public row projections. */ sortRank: number | null; }; function projectSessionDiscoveryControlForRelatedAccess( control: SessionDiscoveryControl, sessionId: string, access: "target" | "root", ): SessionDiscoveryControl { if ( access === "root" || control.primaryBlocker?.kind !== "session" || control.primaryBlocker.sessionId === sessionId ) { return control; } return { ...control, primaryBlocker: { kind: "session", displayName: "An ancestor session", displayNameOriginalChars: "An ancestor session".length, }, additionalBlockerCount: 0, }; } function normalizeSessionActivityRevision(value: string, label: string): string { return normalizeActivityToken(value, label); } const SESSION_DISCOVERY_QUERY_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u; type NormalizedSessionDiscoveryFilters = { originSiteId: string | null; query: string | null; statuses: SessionStatus[]; activeOnly: boolean; recentHours: number | null; rootSessionId: string | null; channelId: string | null | undefined; parentSessionId: string | null | undefined; subject: WorkClaimSubjectFilter | null; /** The app's Mine filter: chats the caller started or prompted. */ mineOnly: boolean; visibility: SessionDiscoveryVisibility | null; }; type SessionDiscoveryPageRow = { id: string | null; title: string | null; titleOriginalChars: number | string | null; visibility: string | null; archived: boolean | null; channelId?: string | null; parentSessionId: string | null; rootSessionId: string | null; nestedAgentDepth: number | string | null; status: string | null; createdAt: Date | string | null; updatedAt: Date | string | null; sortRevision: string | null; sortAt: string | null; sortRank: number | string | null; matchClass: string | null; matchedField: string | null; scoreBand: string | null; matchedClaimId: string | null; total: number | string; }; type SessionDiscoveryClaimRow = { sessionId: string; id: string; subjectNamespace: string; subjectType: string; canonicalKey: string; displayLabel: string | null; role: string; state: string; revision: number | string; provenance: string; versionKind: string | null; versionValue: string | null; observedAt: Date | string; updatedAt: Date | string; settledAt: Date | string | null; availableCount: number | string; }; function normalizeSessionDiscoveryQuery(value: string | undefined): string | null { if (value === undefined) return null; const canonical = value.normalize("NFKC"); if (SESSION_DISCOVERY_QUERY_CONTROL_CHARACTERS.test(canonical)) { throw new Error("sessions_list query must not contain control characters"); } const normalized = canonical.trim().replace(/\s+/gu, " ").toLowerCase(); if (!normalized) return null; if (Array.from(normalized).length > WORK_DISCOVERY_QUERY_MAX_CHARS) { throw new Error( `sessions_list query must be at most ${WORK_DISCOVERY_QUERY_MAX_CHARS} characters`, ); } return normalized; } function normalizeSessionDiscoverySubject( value: WorkClaimSubjectFilter | undefined, ): WorkClaimSubjectFilter | null { if (!value) return null; return { namespace: WorkClaimNamespace.parse(normalizeWorkClaimNamespace(value.namespace)), type: WorkClaimSubjectType.parse(value.type), canonicalKey: WorkClaimCanonicalKey.parse(normalizeWorkClaimCanonicalKey(value.canonicalKey)), }; } function normalizeSessionDiscoveryFilters(options: { originSiteId?: string; query?: string; search?: string; statuses?: SessionStatus[]; activeOnly?: boolean; recentHours?: number; rootSessionId?: string; channelId?: string | null; parentSessionId?: string | null; subject?: WorkClaimSubjectFilter; mineOnly?: boolean; visibility?: SessionDiscoveryVisibility; }): NormalizedSessionDiscoveryFilters { const query = normalizeSessionDiscoveryQuery(options.query ?? options.search); if ( options.query !== undefined && options.search !== undefined && normalizeSessionDiscoveryQuery(options.query) !== normalizeSessionDiscoveryQuery(options.search) ) { throw new Error("sessions_list query and legacy search filter do not match"); } const statuses = [...new Set(options.statuses ?? [])] .map((status) => SessionStatusSchema.parse(status)) .sort(); const recentHours = options.recentHours ?? null; if ( recentHours !== null && (!Number.isSafeInteger(recentHours) || recentHours < 1 || recentHours > WORK_DISCOVERY_RECENT_HOURS_MAX) ) { throw new Error( `sessions_list recentHours must be an integer between 1 and ${WORK_DISCOVERY_RECENT_HOURS_MAX}`, ); } const subject = normalizeSessionDiscoverySubject(options.subject); if (query && subject) { throw new Error("sessions_list query cannot be combined with an exact subject filter"); } return { query, originSiteId: options.originSiteId ?? null, statuses, activeOnly: options.activeOnly === true, recentHours, rootSessionId: options.rootSessionId ?? null, channelId: options.channelId, parentSessionId: Object.prototype.hasOwnProperty.call(options, "parentSessionId") ? (options.parentSessionId ?? null) : undefined, subject, mineOnly: options.mineOnly === true, visibility: options.visibility === undefined ? null : z.enum(["private", "workspace"]).parse(options.visibility), }; } function sessionDiscoveryFilterHash(filters: NormalizedSessionDiscoveryFilters): string { return createHash("sha256") .update( JSON.stringify({ query: filters.query, ...(filters.originSiteId ? { originSiteId: filters.originSiteId } : {}), statuses: filters.statuses, activeOnly: filters.activeOnly, recentHours: filters.recentHours, rootSessionId: filters.rootSessionId, parentSessionId: filters.parentSessionId === undefined ? { any: true } : filters.parentSessionId, ...(filters.channelId !== undefined ? { channelId: filters.channelId } : {}), subject: filters.subject, // Added later: present only when set, so earlier relevance cursors keep their hash. ...(filters.mineOnly ? { mineOnly: true } : {}), ...(filters.visibility ? { visibility: filters.visibility } : {}), }), ) .digest("hex"); } function sessionDiscoverySubjectDigest(subject: WorkClaimSubjectFilter): string { return createHash("sha256") .update(`${subject.namespace}\u001f${subject.type}\u001f${subject.canonicalKey}`, "utf8") .digest("hex"); } function sessionDiscoveryIso(value: Date | string): string { return (value instanceof Date ? value : new Date(value)).toISOString(); } async function selectSessionDiscoveryPageRows( db: Database, workspaceId: string, options: { limit: number; orderBy: SessionDiscoveryOrderBy; cursor?: SessionDiscoveryCursor; snapshotAt: string; snapshotRevision: string; updatedAfter: string | null; subjectId?: string; authorizationScope?: SessionAuthorizationListScope; filters: NormalizedSessionDiscoveryFilters; }, ): Promise<{ rows: SessionDiscoveryPageRow[]; total: number; watermark: string }> { const authorizationFilters: SQL[] = [eq(schema.sessions.workspaceId, workspaceId)]; if (options.subjectId) { authorizationFilters.push(sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' and private_slack_interaction.owning_subject_id <> ${options.subjectId} )`); } else { // Missing subject context must fail closed for Slack-private roots. Public // and ordinary workspace-shared discovery remains available to internal // callers that do not carry a human subject. authorizationFilters.push(sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' )`); } if (options.authorizationScope) { authorizationFilters.push(sessionAuthorizationScopeFilter(options.authorizationScope)); } if (options.filters.statuses.length > 0) { authorizationFilters.push(inArray(schema.sessions.status, options.filters.statuses)); } if (options.filters.originSiteId) { authorizationFilters.push( eq(schema.sessions.siteId, options.filters.originSiteId), sql`${schema.sessions.siteAccessRootId} is not null`, ); } else { const ownRoot = options.authorizationScope?.agentAccessViewer?.callerRootSessionId; authorizationFilters.push( ownRoot ? sql`(${schema.sessions.siteAccessRootId} is null OR ${schema.sessions.rootSessionId} = ${ownRoot}::uuid)` : sql`${schema.sessions.siteAccessRootId} is null`, ); } if (options.filters.activeOnly) { authorizationFilters.push(notInArray(schema.sessions.status, ["failed", "cancelled"])); } if (options.filters.mineOnly) { if (!options.subjectId) throw new Error("sessions_list mineOnly requires a caller identity"); authorizationFilters.push(sessionMineSql(options.subjectId)); } if (options.filters.visibility) { authorizationFilters.push( eq( schema.sessions.visibility, options.filters.visibility === "private" ? "user_private" : "workspace_shared", ), ); } if (options.filters.recentHours !== null) { authorizationFilters.push( sql`${schema.sessions.updatedAt} >= ${options.snapshotAt}::text::timestamptz - (${options.filters.recentHours}::integer * interval '1 hour')`, ); } if (options.filters.channelId !== undefined) { authorizationFilters.push( options.filters.channelId === null ? isNull(schema.sessions.channelId) : eq(schema.sessions.channelId, options.filters.channelId), ); } if (options.filters.rootSessionId) { authorizationFilters.push(eq(schema.sessions.rootSessionId, options.filters.rootSessionId)); } if (options.filters.parentSessionId !== undefined) { authorizationFilters.push( options.filters.parentSessionId === null ? isNull(schema.sessions.parentSessionId) : eq(schema.sessions.parentSessionId, options.filters.parentSessionId), ); } authorizationFilters.push( options.orderBy === "createdAt" ? sql`${schema.sessions.createdAt} <= ${options.snapshotAt}::text::timestamptz` : options.orderBy === "relevance" ? sql`${schema.sessions.activityXid} < (select watermark from activity_window)` : sql`true`, ); if (options.updatedAfter !== null) { authorizationFilters.push( sql`${schema.sessions.activityXid} >= ${decodeActivityXid(options.updatedAfter)}::xid8`, ); } const authorizedPredicate = and(...authorizationFilters) ?? sql`false`; const claimStatePredicate = options.filters.activeOnly || options.filters.recentHours === null ? sql`${schema.sessionWorkClaims.state} = 'active'` : sql`(${schema.sessionWorkClaims.state} = 'active' or ${schema.sessionWorkClaims.updatedAt} >= ${options.snapshotAt}::text::timestamptz - (${options.filters.recentHours}::integer * interval '1 hour'))`; const subjectDigest = options.filters.subject ? sessionDiscoverySubjectDigest(options.filters.subject) : null; const subjectScopePredicate = options.filters.subject ? sql`exists ( select 1 from ${schema.sessionWorkClaims} where ${schema.sessionWorkClaims.workspaceId} = ${workspaceId} and ${schema.sessionWorkClaims.sessionId} = authorized_sessions.id and ${schema.sessionWorkClaims.subjectNamespace} = ${options.filters.subject.namespace} and ${schema.sessionWorkClaims.subjectType} = ${options.filters.subject.type} and ${schema.sessionWorkClaims.subjectDigest} = ${subjectDigest} and ${claimStatePredicate} )` : sql`true`; const rankingCtes = options.filters.subject ? sql`, match_candidates as materialized ( select subject_scoped_sessions.id as session_id, 0::integer as match_rank, 'exact_subject'::text as match_class, 'subject'::text as matched_field, 'exact'::text as score_band, ${schema.sessionWorkClaims.id} as matched_claim_id, ${schema.sessionWorkClaims.updatedAt} as matched_claim_updated_at from subject_scoped_sessions join ${schema.sessionWorkClaims} on ${schema.sessionWorkClaims.workspaceId} = ${workspaceId} and ${schema.sessionWorkClaims.sessionId} = subject_scoped_sessions.id and ${schema.sessionWorkClaims.subjectNamespace} = ${options.filters.subject.namespace} and ${schema.sessionWorkClaims.subjectType} = ${options.filters.subject.type} and ${schema.sessionWorkClaims.subjectDigest} = ${subjectDigest} and ${claimStatePredicate} ), best_matches as materialized ( select distinct on (session_id) session_id, match_rank, match_class, matched_field, score_band, matched_claim_id from match_candidates order by session_id, match_rank, matched_claim_updated_at desc, matched_claim_id desc )` : options.filters.query ? sql`, search_input as materialized ( select lower(${options.filters.query}::text) as normalized_query, websearch_to_tsquery('simple', ${options.filters.query}::text) as ts_query ), match_candidates as materialized ( select subject_scoped_sessions.id as session_id, case when lower(search_session.title) = search_input.normalized_query then 10 when starts_with(lower(search_session.title), search_input.normalized_query) then 11 else 12 end::integer as match_rank, 'title'::text as match_class, 'title'::text as matched_field, case when lower(search_session.title) = search_input.normalized_query then 'exact' else 'strong' end::text as score_band, null::uuid as matched_claim_id, null::timestamptz as matched_claim_updated_at from subject_scoped_sessions join ${schema.sessions} search_session on search_session.workspace_id = ${workspaceId} and search_session.id = subject_scoped_sessions.id cross join search_input where search_session.title is not null and ( lower(search_session.title) = search_input.normalized_query or starts_with(lower(search_session.title), search_input.normalized_query) or to_tsvector('simple', search_session.title) @@ search_input.ts_query ) union all select subject_scoped_sessions.id as session_id, case when lower(${schema.sessionGoals.text}) = search_input.normalized_query then 20 when starts_with( lower(${schema.sessionGoals.text}), search_input.normalized_query ) then 21 else 22 end::integer as match_rank, 'goal'::text as match_class, 'goal'::text as matched_field, case when lower(${schema.sessionGoals.text}) = search_input.normalized_query then 'exact' else 'strong' end::text as score_band, null::uuid as matched_claim_id, null::timestamptz as matched_claim_updated_at from subject_scoped_sessions join ${schema.sessionGoals} on ${schema.sessionGoals.workspaceId} = ${workspaceId} and ${schema.sessionGoals.sessionId} = subject_scoped_sessions.id and ${schema.sessionGoals.status} = 'active' cross join search_input where lower(${schema.sessionGoals.text}) = search_input.normalized_query or starts_with(lower(${schema.sessionGoals.text}), search_input.normalized_query) or to_tsvector('simple', ${schema.sessionGoals.text}) @@ search_input.ts_query union all select subject_scoped_sessions.id as session_id, ( case when ${schema.sessionWorkClaims.state} = 'active' then 30 else 40 end + case when lower(${schema.sessionWorkClaims.canonicalKey}) = search_input.normalized_query or lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')) = search_input.normalized_query then 0 when starts_with( lower(${schema.sessionWorkClaims.canonicalKey}), search_input.normalized_query ) or starts_with( lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')), search_input.normalized_query ) then 1 else 2 end )::integer as match_rank, 'fuzzy'::text as match_class, case when lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')) = search_input.normalized_query or starts_with( lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')), search_input.normalized_query ) or to_tsvector('simple', coalesce(${schema.sessionWorkClaims.displayLabel}, '')) @@ search_input.ts_query then 'claim_label' else 'claim_key' end::text as matched_field, case when lower(${schema.sessionWorkClaims.canonicalKey}) = search_input.normalized_query or lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')) = search_input.normalized_query then 'exact' when starts_with( lower(${schema.sessionWorkClaims.canonicalKey}), search_input.normalized_query ) or starts_with( lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')), search_input.normalized_query ) then 'strong' else 'related' end::text as score_band, ${schema.sessionWorkClaims.id} as matched_claim_id, ${schema.sessionWorkClaims.updatedAt} as matched_claim_updated_at from subject_scoped_sessions join ${schema.sessionWorkClaims} on ${schema.sessionWorkClaims.workspaceId} = ${workspaceId} and ${schema.sessionWorkClaims.sessionId} = subject_scoped_sessions.id and ${claimStatePredicate} cross join search_input where lower(${schema.sessionWorkClaims.canonicalKey}) = search_input.normalized_query or starts_with( lower(${schema.sessionWorkClaims.canonicalKey}), search_input.normalized_query ) or to_tsvector( 'simple', ${schema.sessionWorkClaims.canonicalKey} || ' ' || coalesce(${schema.sessionWorkClaims.displayLabel}, '') ) @@ search_input.ts_query or lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')) = search_input.normalized_query or starts_with( lower(coalesce(${schema.sessionWorkClaims.displayLabel}, '')), search_input.normalized_query ) ), best_matches as materialized ( select distinct on (session_id) session_id, match_rank, match_class, matched_field, score_band, matched_claim_id from match_candidates order by session_id, match_rank, matched_claim_updated_at desc nulls last, matched_claim_id desc nulls last )` : sql``; const rankedCte = options.orderBy === "relevance" ? sql`, ranked_sessions as materialized ( select subject_scoped_sessions.*, best_matches.match_rank, best_matches.match_class, best_matches.matched_field, best_matches.score_band, best_matches.matched_claim_id from subject_scoped_sessions join best_matches on best_matches.session_id = subject_scoped_sessions.id )` : sql`, ranked_sessions as materialized ( select subject_scoped_sessions.*, null::integer as match_rank, null::text as match_class, null::text as matched_field, null::text as score_band, null::uuid as matched_claim_id from subject_scoped_sessions )`; const cursorPredicate = !options.cursor ? sql`true` : options.orderBy === "relevance" ? sql`( ranked_sessions.match_rank > ${options.cursor.sortRank}::integer or ( ranked_sessions.match_rank = ${options.cursor.sortRank}::integer and ( ranked_sessions.activity_xid < ${options.cursor.sortRevision}::text::xid8 or ( ranked_sessions.activity_xid = ${options.cursor.sortRevision}::text::xid8 and ( ranked_sessions.updated_at < ${options.cursor.sortAt}::text::timestamptz or ( ranked_sessions.updated_at = ${options.cursor.sortAt}::text::timestamptz and ranked_sessions.id < ${options.cursor.id}::uuid ) ) ) ) ) )` : options.orderBy === "updatedAt" ? sql`( ranked_sessions.activity_xid < ${options.cursor.sortRevision}::text::xid8 or ( ranked_sessions.activity_xid = ${options.cursor.sortRevision}::text::xid8 and ( ranked_sessions.updated_at < ${options.cursor.sortAt}::text::timestamptz or ( ranked_sessions.updated_at = ${options.cursor.sortAt}::text::timestamptz and ranked_sessions.id < ${options.cursor.id}::uuid ) ) ) )` : sql`( ranked_sessions.created_at < ${options.cursor.sortAt}::text::timestamptz or ( ranked_sessions.created_at = ${options.cursor.sortAt}::text::timestamptz and ranked_sessions.id < ${options.cursor.id}::uuid ) )`; const pageOrder = options.orderBy === "relevance" ? sql`ranked_sessions.match_rank asc, ranked_sessions.activity_xid desc, ranked_sessions.updated_at desc, ranked_sessions.id desc` : options.orderBy === "updatedAt" ? sql`ranked_sessions.activity_xid desc, ranked_sessions.updated_at desc, ranked_sessions.id desc` : sql`ranked_sessions.created_at desc, ranked_sessions.id desc`; const outerOrder = options.orderBy === "relevance" ? sql`page."sortRank" asc nulls last, page."sortRevision"::xid8 desc nulls last, page."sortAt"::timestamptz desc nulls last, page.id desc nulls last` : options.orderBy === "updatedAt" ? sql`page."sortRevision"::xid8 desc nulls last, page."sortAt"::timestamptz desc nulls last, page.id desc nulls last` : sql`page."sortAt"::timestamptz desc nulls last, page.id desc nulls last`; const sortRevision = options.orderBy === "createdAt" ? sql`'0'::text` : sql`ranked_sessions.activity_xid::text`; const sortAt = options.orderBy === "createdAt" ? sql`to_char(ranked_sessions.created_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')` : sql`to_char(ranked_sessions.updated_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`; const result = await rawRows( db, sql` with activity_window as materialized ( -- xmin and the rows share this statement's MVCC snapshot. A lower xid -- that commits late is >= this token and is replayed on the next poll. -- Keep page one's watermark across continuation pages: advancing it on -- a later page could skip an interleaved commit above that page's keyset. select ${options.cursor ? sql`${decodeActivityXid(options.snapshotRevision)}::xid8` : options.orderBy === "relevance" ? sql`pg_snapshot_xmax(pg_current_snapshot())` : sql`pg_snapshot_xmin(pg_current_snapshot())`} as watermark ), authorized_sessions as materialized ( select ${schema.sessions.id} as id, ${schema.sessions.title} as title, ${schema.sessions.visibility} as visibility, ${schema.sessions.archivedAt} is not null as archived, ${schema.sessions.channelId} as channel_id, ${schema.sessions.parentSessionId} as parent_session_id, ${schema.sessions.rootSessionId} as root_session_id, ${schema.sessions.nestedAgentDepth} as nested_agent_depth, ${schema.sessions.status} as status, ${schema.sessions.createdAt} as created_at, ${schema.sessions.updatedAt} as updated_at, ${schema.sessions.activityXid} as activity_xid from ${schema.sessions} where ${authorizedPredicate} ), subject_scoped_sessions as materialized ( select * from authorized_sessions where ${subjectScopePredicate} ) ${rankingCtes} ${rankedCte} select page.id, page.title, page."titleOriginalChars", page.visibility, page.archived, page."channelId", page."parentSessionId", page."rootSessionId", page."nestedAgentDepth", page.status, page."createdAt", page."updatedAt", page."sortRevision", page."sortAt", page."sortRank", page."matchClass", page."matchedField", page."scoreBand", page."matchedClaimId", totals.total, activity_window.watermark::text as watermark from activity_window cross join (select count(*)::integer as total from ranked_sessions) totals left join lateral ( select ranked_sessions.id, left(ranked_sessions.title, ${SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS}) as title, char_length(ranked_sessions.title)::integer as "titleOriginalChars", ranked_sessions.visibility, ranked_sessions.archived, ranked_sessions.channel_id as "channelId", ranked_sessions.parent_session_id as "parentSessionId", ranked_sessions.root_session_id as "rootSessionId", ranked_sessions.nested_agent_depth as "nestedAgentDepth", ranked_sessions.status, ranked_sessions.created_at as "createdAt", ranked_sessions.updated_at as "updatedAt", ${sortRevision} as "sortRevision", ${sortAt} as "sortAt", ranked_sessions.match_rank as "sortRank", ranked_sessions.match_class as "matchClass", ranked_sessions.matched_field as "matchedField", ranked_sessions.score_band as "scoreBand", ranked_sessions.matched_claim_id as "matchedClaimId" from ranked_sessions where ${cursorPredicate} order by ${pageOrder} limit ${options.limit + 1} ) page on true order by ${outerOrder} `, ); const total = Number(result[0]?.total ?? 0); return { rows: result.filter((row) => row.id !== null), total, watermark: result[0]!.watermark }; } async function sessionDiscoveryClaimsForSessions( db: Database, workspaceId: string, sessionIds: string[], options: { snapshotAt: string; activeOnly: boolean; recentHours: number | null; limit: number; matchedClaimIds: ReadonlyMap; }, ): Promise> { if (sessionIds.length === 0 || options.limit < 1) return new Map(); const claimStatePredicate = options.activeOnly || options.recentHours === null ? sql`${schema.sessionWorkClaims.state} = 'active'` : sql`(${schema.sessionWorkClaims.state} = 'active' or ${schema.sessionWorkClaims.updatedAt} >= ${options.snapshotAt}::text::timestamptz - (${options.recentHours}::integer * interval '1 hour'))`; const rows = await rawRows( db, sql` with requested_sessions(session_id, matched_claim_id) as ( values ${sql.join( sessionIds.map( (sessionId) => sql`(${sessionId}::uuid, ${options.matchedClaimIds.get(sessionId) ?? null}::uuid)`, ), sql`, `, )} ) select requested_sessions.session_id as "sessionId", claim.id, claim.subject_namespace as "subjectNamespace", claim.subject_type as "subjectType", claim.canonical_key as "canonicalKey", claim.display_label as "displayLabel", claim.role, claim.state, claim.revision, claim.provenance, claim.version_kind as "versionKind", claim.version_value as "versionValue", claim.observed_at as "observedAt", claim.updated_at as "updatedAt", claim.settled_at as "settledAt", claim.available_count as "availableCount" from requested_sessions cross join lateral ( select ${schema.sessionWorkClaims.id} as id, ${schema.sessionWorkClaims.subjectNamespace} as subject_namespace, ${schema.sessionWorkClaims.subjectType} as subject_type, ${schema.sessionWorkClaims.canonicalKey} as canonical_key, ${schema.sessionWorkClaims.displayLabel} as display_label, ${schema.sessionWorkClaims.role} as role, ${schema.sessionWorkClaims.state} as state, ${schema.sessionWorkClaims.revision} as revision, ${schema.sessionWorkClaims.provenance} as provenance, ${schema.sessionWorkClaims.versionKind} as version_kind, ${schema.sessionWorkClaims.versionValue} as version_value, ${schema.sessionWorkClaims.observedAt} as observed_at, ${schema.sessionWorkClaims.updatedAt} as updated_at, ${schema.sessionWorkClaims.settledAt} as settled_at, count(*) over()::integer as available_count from ${schema.sessionWorkClaims} where ${schema.sessionWorkClaims.workspaceId} = ${workspaceId} and ${schema.sessionWorkClaims.sessionId} = requested_sessions.session_id and ${claimStatePredicate} order by ( requested_sessions.matched_claim_id is not null and ${schema.sessionWorkClaims.id} = requested_sessions.matched_claim_id ) desc, (${schema.sessionWorkClaims.state} = 'active') desc, ${schema.sessionWorkClaims.updatedAt} desc, ${schema.sessionWorkClaims.id} desc limit ${options.limit} ) claim order by requested_sessions.session_id, ( requested_sessions.matched_claim_id is not null and claim.id = requested_sessions.matched_claim_id ) desc, (claim.state = 'active') desc, claim.updated_at desc, claim.id desc `, ); const grouped = new Map(); for (const row of rows) { const entry = grouped.get(row.sessionId) ?? { claims: [], truncated: false, }; entry.claims.push( WorkClaimDiscoverySummarySchema.parse({ id: row.id, sessionId: row.sessionId, subject: { namespace: row.subjectNamespace, type: row.subjectType, canonicalKey: row.canonicalKey, displayLabel: row.displayLabel, }, role: row.role, state: row.state, revision: Number(row.revision), provenance: row.provenance, version: row.versionKind === null || row.versionValue === null ? null : { kind: row.versionKind, value: row.versionValue }, observedAt: sessionDiscoveryIso(row.observedAt), updatedAt: sessionDiscoveryIso(row.updatedAt), settledAt: row.settledAt === null ? null : sessionDiscoveryIso(row.settledAt), }), ); entry.truncated = Number(row.availableCount) > options.limit; grouped.set(row.sessionId, entry); } return grouped; } /** * SQL twin of `isStreamedAssistantMessageCompletion` in `@opengeni/contracts`. * Every branch is coalesced: a missing key must keep the row, never make the * negated predicate unknown. */ function excludeStreamedAssistantMessageEventFilter(): SQL { const event = schema.sessionEvents; return sql`not ( ${event.type} = 'agent.message.completed' and ( coalesce(${event.payload} ->> 'phase', '') in ('commentary', 'final_answer') or coalesce( jsonb_typeof(${event.payload} -> 'messageId') = 'string' and ${event.payload} ->> 'messageId' <> '', false ) ) )`; } /** * Compact-by-construction discovery projection for the first-party * `sessions_list` MCP tool. It never selects instructions, resources, tools, * MCP metadata, repositories, settings, or full event/history bodies. */ export async function listSessionDiscoverySummaries( db: Database, workspaceId: string, options: { originSiteId?: string; limit: number; cursor?: SessionDiscoveryCursor; includeLastMessage?: boolean; orderBy?: SessionDiscoveryOrderBy; updatedAfter?: string; channelId?: string | null; parentSessionId?: string | null; rootSessionId?: string; query?: string; /** @deprecated use query; retained for the existing topology route. */ search?: string; statuses?: SessionStatus[]; activeOnly?: boolean; recentHours?: number; subject?: WorkClaimSubjectFilter; /** The app's Mine filter (chats the caller started or prompted); needs subjectId. */ mineOnly?: boolean; visibility?: SessionDiscoveryVisibility; claimLimit?: number; /** Skip advisory claim reads on plain MCP browse or an operator-disabled rollout. * Omitted retains the REST/UI legacy evidence default. */ includeWorkDiscovery?: boolean; subjectId?: string; authorizationScope?: SessionAuthorizationListScope; }, ): Promise<{ sessions: SessionDiscoverySummary[]; hasMore: boolean; nextCursor: SessionDiscoveryCursor | null; total: number; orderBy: SessionDiscoveryOrderBy; snapshotAt: string; snapshotRevision: string; updatedThrough: string | null; updatedAfter: string | null; /** Internal relevance cursor binding; omitted from row projections. */ filterHash: string | null; originSiteId?: string; }> { const limit = Math.max(1, Math.min(100, Math.floor(options.limit))); const claimLimit = Math.max( 1, Math.min( WORK_CLAIM_DISCOVERY_LIMIT, Math.floor(options.claimLimit ?? WORK_CLAIM_DISCOVERY_DEFAULT_LIMIT), ), ); const filters = normalizeSessionDiscoveryFilters(options); const relevanceRequested = filters.query !== null || filters.subject !== null; const orderBy = options.orderBy ?? options.cursor?.orderBy ?? (relevanceRequested ? "relevance" : "createdAt"); if (relevanceRequested && orderBy !== "relevance") { throw new Error("sessions_list query and exact subject filters require relevance order"); } if (!relevanceRequested && orderBy === "relevance") { throw new Error("sessions_list relevance order requires query or an exact subject filter"); } const filterHash = relevanceRequested ? sessionDiscoveryFilterHash(filters) : null; const readPage = async (scopedDb: Database) => { if (options.cursor && (options.cursor.originSiteId ?? null) !== filters.originSiteId) { throw new Error("sessions_list cursor app filter does not match the request"); } const requestedUpdatedAfter = options.updatedAfter ?? options.cursor?.updatedAfter ?? null; const updatedAfter = requestedUpdatedAfter === null ? null : normalizeSessionActivityRevision(requestedUpdatedAfter, "updatedAfter"); if (options.cursor?.orderBy !== undefined && options.cursor.orderBy !== orderBy) { throw new Error("sessions_list cursor order does not match the request"); } if (options.cursor && options.cursor.updatedAfter !== updatedAfter) { throw new Error("sessions_list cursor incremental filter does not match the request"); } if (updatedAfter !== null && orderBy !== "updatedAt") { throw new Error("sessions_list updatedAfter requires orderBy=updatedAt"); } if (options.cursor && orderBy === "relevance") { if ( !Number.isSafeInteger(options.cursor.sortRank) || options.cursor.sortRank === null || options.cursor.sortRank < 0 ) { throw new Error("sessions_list relevance cursor rank is invalid"); } if (options.cursor.filterHash !== filterHash) { throw new Error("sessions_list cursor relevance filters do not match the request"); } } else if ( options.cursor && (options.cursor.sortRank !== null || options.cursor.filterHash !== null) ) { throw new Error("sessions_list chronological cursor cannot carry relevance fields"); } const cursor = orderBy !== "createdAt" && (!options.cursor || !isActivityXidToken(options.cursor.snapshotRevision)) ? undefined : options.cursor; const snapshotAt = cursor?.snapshotAt ?? ( await rawRows<{ value: string }>( scopedDb, // The transaction-start cutoff is no later than any statement or // repeatable-read snapshot used below. Later rows therefore belong // to the next traversal instead of entering this cursor mid-scan. sql`select to_char(transaction_timestamp() at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') as value`, ) )[0]!.value; // For a new traversal the SQL page statement captures its own xmin. let snapshotRevision = cursor?.snapshotRevision ?? "0"; const cursorSortRevision = cursor ? normalizeSessionActivityRevision(cursor.sortRevision, "cursor sort revision") : null; if ( orderBy === "createdAt" && options.cursor && (cursorSortRevision !== "0" || options.cursor.snapshotRevision !== "0" || options.cursor.sortRank !== null || options.cursor.filterHash !== null) ) { throw new Error("sessions_list created-order cursor cannot carry activity revisions"); } const selected = await selectSessionDiscoveryPageRows(scopedDb, workspaceId, { limit, orderBy, ...(cursor ? { cursor } : {}), snapshotAt, snapshotRevision, updatedAfter, ...(options.subjectId ? { subjectId: options.subjectId } : {}), ...(options.authorizationScope ? { authorizationScope: options.authorizationScope } : {}), filters, }); snapshotRevision = orderBy === "createdAt" ? "0" : encodeActivityXid(selected.watermark); const hasMore = selected.rows.length > limit; const page = selected.rows.slice(0, limit); const ids = page.map((row) => row.id!); if (ids.length === 0) { return { sessions: [], hasMore: false, nextCursor: null, total: selected.total, orderBy, snapshotAt, snapshotRevision, updatedThrough: orderBy === "updatedAt" ? snapshotRevision : null, updatedAfter, filterHash, }; } const rootRelatedIds = await sessionIdsCoveredByAuthorizationRoots( scopedDb, workspaceId, ids, options.authorizationScope, ); const controls = await evaluateSessionDiscoveryControls(scopedDb, workspaceId, ids); const treeStats = await sessionTreeStatsForSessions(scopedDb, workspaceId, [...rootRelatedIds]); const includeWorkDiscovery = options.includeWorkDiscovery !== false; const workClaims = includeWorkDiscovery ? await sessionDiscoveryClaimsForSessions(scopedDb, workspaceId, ids, { snapshotAt, activeOnly: filters.activeOnly, recentHours: filters.recentHours, limit: claimLimit, matchedClaimIds: new Map(page.map((row) => [row.id!, row.matchedClaimId] as const)), }) : new Map(); const goals = await scopedDb .select({ sessionId: schema.sessionGoals.sessionId, status: schema.sessionGoals.status, text: sql`left(${schema.sessionGoals.text}, ${SESSION_DISCOVERY_GOAL_MAX_CHARS})`, textOriginalChars: sql`char_length(${schema.sessionGoals.text})::integer`, }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), inArray(schema.sessionGoals.sessionId, ids), ), ); const goalsBySession = new Map(goals.map((goal) => [goal.sessionId, goal])); const queueCounts = await scopedDb .select({ sessionId: schema.sessionTurns.sessionId, count: sql`count(*)::int`, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), inArray(schema.sessionTurns.sessionId, ids), eq(schema.sessionTurns.status, "queued"), inArray(schema.sessionTurns.source, ["user", "api"]), ), ) .groupBy(schema.sessionTurns.sessionId); const queueBySession = new Map( queueCounts.map((entry) => [entry.sessionId, Number(entry.count)]), ); const latestMessages = options.includeLastMessage ? await scopedDb .selectDistinctOn([schema.sessionEvents.sessionId], { sessionId: schema.sessionEvents.sessionId, type: schema.sessionEvents.type, // Extract only the bounded textual preview in PostgreSQL. Selecting // the JSON payload here would re-materialize the exact multi-MB // event bodies this compact discovery path exists to avoid. preview: sql`left(coalesce( ${schema.sessionEvents.payload}->>'text', ${schema.sessionEvents.payload}->>'message', ${schema.sessionEvents.payload}->>'content' ), ${SESSION_DISCOVERY_MESSAGE_MAX_CHARS})`, previewOriginalChars: sql`char_length(coalesce( ${schema.sessionEvents.payload}->>'text', ${schema.sessionEvents.payload}->>'message', ${schema.sessionEvents.payload}->>'content' ))::integer`, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), inArray(schema.sessionEvents.sessionId, ids), inArray(schema.sessionEvents.type, ["user.message", "agent.message.completed"]), excludeUnclaimedHumanPromptEventFilter(workspaceId), ), ) .orderBy(schema.sessionEvents.sessionId, desc(schema.sessionEvents.sequence)) : []; const latestBySession = new Map(latestMessages.map((entry) => [entry.sessionId, entry])); const sessions = page.map((row): SessionDiscoverySummary => { const sessionId = row.id!; const control = controls.get(sessionId); if (!control) throw new Error(`Effective control missing for session ${sessionId}`); const relatedAccess = rootRelatedIds.has(sessionId) ? "root" : "target"; const goal = goalsBySession.get(sessionId); const latest = latestBySession.get(sessionId); const claims = workClaims.get(sessionId) ?? { claims: [], truncated: false, }; const match = !includeWorkDiscovery || row.matchClass === null || row.matchedField === null || row.scoreBand === null ? null : WorkDiscoveryMatchSchema.parse({ class: row.matchClass, field: row.matchedField, scoreBand: row.scoreBand, claimId: row.matchedClaimId, }); return { id: sessionId, title: row.title, titleOriginalChars: row.titleOriginalChars === null ? null : Number(row.titleOriginalChars), visibility: row.visibility === "user_private" ? "private" : "workspace", archived: row.archived === true, channelId: row.channelId ?? null, parentSessionId: relatedAccess === "root" ? row.parentSessionId : null, rootSessionId: relatedAccess === "root" ? row.rootSessionId! : sessionId, nestedAgentDepth: Number(row.nestedAgentDepth), status: row.status as SessionStatus, effectiveControl: projectSessionDiscoveryControlForRelatedAccess( control, sessionId, relatedAccess, ), goal: goal ? { status: goal.status as SessionGoalStatus, text: goal.text, textOriginalChars: Number(goal.textOriginalChars), } : null, queuedPromptCount: queueBySession.get(sessionId) ?? 0, treeStats: relatedAccess === "root" ? (treeStats.get(sessionId) ?? EMPTY_SESSION_TREE_STATS) : EMPTY_SESSION_TREE_STATS, latestMessage: latest ? { type: latest.type as SessionEventType, preview: latest.preview, previewOriginalChars: latest.previewOriginalChars === null ? null : Number(latest.previewOriginalChars), } : null, workDiscovery: { claims: claims.claims, claimsTruncated: claims.truncated, match, possibleOverlap: match !== null, advisoryOnly: true, noAdditionalAccess: true, }, createdAt: sessionDiscoveryIso(row.createdAt!), updatedAt: sessionDiscoveryIso(row.updatedAt!), sortRevision: row.sortRevision!, sortAt: row.sortAt!, sortRank: row.sortRank === null ? null : Number(row.sortRank), }; }); const last = page.at(-1); return { sessions, hasMore, nextCursor: hasMore && last ? { orderBy, sortRank: last.sortRank === null ? null : Number(last.sortRank), sortRevision: last.sortRevision!, sortAt: last.sortAt!, id: last.id!, snapshotAt, snapshotRevision, updatedAfter, filterHash, ...(filters.originSiteId ? { originSiteId: filters.originSiteId } : {}), } : null, total: selected.total, orderBy, snapshotAt, snapshotRevision, updatedThrough: orderBy === "updatedAt" ? snapshotRevision : null, updatedAfter, filterHash, ...(filters.originSiteId ? { originSiteId: filters.originSiteId } : {}), }; }; const transactionConfig: PgTransactionConfig = orderBy === "createdAt" ? { isolationLevel: "read committed", accessMode: "read only" } : { isolationLevel: "repeatable read", accessMode: "read only" }; return options.subjectId ? await withWorkspaceSubjectRls(db, workspaceId, options.subjectId, readPage, transactionConfig) : await withWorkspaceRls(db, workspaceId, readPage, transactionConfig); } export type SessionDiscoveryAncestor = { id: string; title: string | null; titleOriginalChars: number | null; }; /** * Return bounded root-to-parent paths for a bounded discovery result page. * Authorization is re-applied to every ancestor so exact-session grants never * acquire parent metadata merely by searching for their target. */ export async function listSessionDiscoveryAncestorPaths( db: Database, workspaceId: string, sessionIds: string[], authorizationScope?: SessionAuthorizationListScope, subjectId?: string, ): Promise> { const targetIds = [...new Set(sessionIds)].slice(0, 100); if (targetIds.length === 0) return new Map(); const readPaths = async (scopedDb: Database) => { const authorizationFilters: SQL[] = [eq(schema.sessions.workspaceId, workspaceId)]; authorizationFilters.push( subjectId ? sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' and private_slack_interaction.owning_subject_id <> ${subjectId} )` : sql`not exists ( select 1 from ${schema.slackInteractions} private_slack_interaction where private_slack_interaction.workspace_id = ${schema.sessions.workspaceId} and private_slack_interaction.session_reservation_id = ${schema.sessions.rootSessionId} and private_slack_interaction.visibility = 'private' )`, ); if (authorizationScope) { authorizationFilters.push(sessionAuthorizationScopeFilter(authorizationScope)); } const authorizedPredicate = and(...authorizationFilters) ?? sql`false`; const rows = await rawRows<{ targetId: string; id: string; title: string | null; titleOriginalChars: number | string | null; depth: number | string; cycle: boolean; }>( scopedDb, sql` with recursive authorized_sessions as materialized ( select ${schema.sessions.id} as id, ${schema.sessions.parentSessionId} as parent_session_id, ${schema.sessions.title} as title from ${schema.sessions} where ${authorizedPredicate} ), lineage as ( select target.id as target_id, target.id, target.parent_session_id, target.title, 0::integer as depth, array[target.id]::uuid[] as path, false as cycle from authorized_sessions target where ${inArray(sql`target.id`, targetIds)} union all select child.target_id, parent.id, parent.parent_session_id, parent.title, child.depth + 1, child.path || parent.id, parent.id = any(child.path) from lineage child join authorized_sessions parent on parent.id = child.parent_session_id where not child.cycle and child.depth < 64 ) select target_id as "targetId", id, left(title, ${SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS}) as title, char_length(title)::integer as "titleOriginalChars", depth, cycle from lineage where depth > 0 order by target_id, depth desc `, ); const result = new Map(); for (const row of rows) { if (row.cycle) continue; const path = result.get(row.targetId) ?? []; path.push({ id: row.id, title: row.title, titleOriginalChars: row.titleOriginalChars === null ? null : Number(row.titleOriginalChars), }); result.set(row.targetId, path); } return result; }; return subjectId ? await withWorkspaceSubjectRls(db, workspaceId, subjectId, readPaths) : await withWorkspaceRls(db, workspaceId, readPaths); } export type SessionLineage = { ancestors: Session[]; children: LineageNode[]; truncated: boolean; }; /** A lineage whose sessions were read without their Skill folders. */ export type SessionLineageWithoutSkills = { ancestors: SessionWithoutSkills[]; children: LineageNodeWithoutSkills[]; truncated: boolean; }; export type LineageNodeWithoutSkills = { session: SessionWithoutSkills; children: LineageNodeWithoutSkills[]; }; /** * Resolve a session tree to its root without materializing the full lineage. * Every recursive hop stays workspace-scoped and invalid/cyclic/deep chains * fail closed instead of returning an ambiguous credential authority. */ export async function getSessionRootId( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string; parentSessionId: string | null; depth: number; cycle: boolean; }>(sql` with recursive lineage(id, parent_session_id, depth, path, cycle) as ( select ${schema.sessions.id}, ${schema.sessions.parentSessionId}, 0, array[${schema.sessions.id}], false from ${schema.sessions} where ${schema.sessions.workspaceId} = ${workspaceId} and ${schema.sessions.id} = ${sessionId} union all select parent.id, parent.parent_session_id, lineage.depth + 1, lineage.path || parent.id, parent.id = any(lineage.path) from ${schema.sessions} parent join lineage on lineage.parent_session_id = parent.id where parent.workspace_id = ${workspaceId} and not lineage.cycle and lineage.depth < 64 ) select id, parent_session_id as "parentSessionId", depth, cycle from lineage order by depth desc limit 1 `); const root = rows[0]; if (!root) return null; if (root.cycle || root.parentSessionId !== null || Number(root.depth) >= 64) { throw new Error(`session lineage for ${sessionId} has no valid workspace root`); } return root.id; }); } type LineageIdRow = { id: string; parentSessionId: string | null; depth: number; path: string[]; cycle: boolean; }; /** Descendants a lineage read lists: depth 5 and this many rows at most. */ export const SESSION_TREE_DESCENDANT_LIMIT = 200; /** * Descendants of a session, shallower before deeper and newest first within a * level, so a long fleet loses its oldest grandchildren first. Returns one row * more than the limit when there are more. */ async function selectSessionDescendantRows( scopedDb: Database, workspaceId: string, sessionId: string, ): Promise { return (await scopedDb.execute(sql` with recursive descendants(id, parent_session_id, created_at, depth, path) as ( select child.id, child.parent_session_id, child.created_at, 1, array[${sessionId}, child.id] from ${schema.sessions} child where child.workspace_id = ${workspaceId} and child.parent_session_id = ${sessionId} union all select child.id, child.parent_session_id, child.created_at, descendants.depth + 1, descendants.path || child.id from ${schema.sessions} child join descendants on child.parent_session_id = descendants.id where child.workspace_id = ${workspaceId} and descendants.depth < 5 and not child.id = any(descendants.path) ) select id, parent_session_id as "parentSessionId", depth, path, false as cycle from descendants order by depth, created_at desc, id desc limit ${SESSION_TREE_DESCENDANT_LIMIT + 1} `)) as LineageIdRow[]; } /** * A session and the descendants its lineage lists, in that order, or null when * the session is not visible in the workspace. Ids only: callers authorize * each session before using it. */ export async function listSessionTreeIds( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rootRows = await scopedDb.execute<{ id: string }>(sql` select id from ${schema.sessions} where ${schema.sessions.workspaceId} = ${workspaceId} and ${schema.sessions.id} = ${sessionId} limit 1 `); if (rootRows.length === 0) return null; const rows = await selectSessionDescendantRows(scopedDb, workspaceId, sessionId); return [sessionId, ...rows.slice(0, SESSION_TREE_DESCENDANT_LIMIT).map((row) => row.id)]; }); } /** * Read the full lineage slice around a session. Every recursive step carries * workspace_id as a hard predicate; a foreign parent/child id is invisible even * before RLS is considered. Up to 63 ancestors are returned root-first; an * invalid, cyclic, foreign, or deeper chain fails closed instead of presenting * a partial path as if it were rooted. Descendants are capped at depth 5 and * 200 total rows, returned as a nested tree with each level newest first (as * the sidebar lists chats). The cap keeps shallower agents before deeper ones * and newer before older, so a long fleet loses its oldest grandchildren * first, never a direct child picked at random. A response that never carries * the Skill folders passes `skills: "omit"`. */ export async function getSessionLineage( db: Database, workspaceId: string, sessionId: string, skills: SessionSkillsRead, ): Promise; export async function getSessionLineage( db: Database, workspaceId: string, sessionId: string, skills?: "read", ): Promise; export async function getSessionLineage( db: Database, workspaceId: string, sessionId: string, skills: SessionSkillsRead = "read", ): Promise { const descendantLimit = SESSION_TREE_DESCENDANT_LIMIT; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { // Existence check on the ALREADY-SCOPED connection — never a nested // withWorkspaceRls (getSession opens its own scoped transaction, which // acquires a SECOND pooled connection while this one is held; under load // that is a classic pool-starvation deadlock). const rootRows = await scopedDb.execute<{ id: string }>(sql` select id from ${schema.sessions} where ${schema.sessions.workspaceId} = ${workspaceId} and ${schema.sessions.id} = ${sessionId} limit 1 `); if (rootRows.length === 0) { return null; } const ancestorLineageRows = (await scopedDb.execute(sql` with recursive ancestors(id, parent_session_id, depth, path, cycle) as ( select ${schema.sessions.id}, ${schema.sessions.parentSessionId}, 0, array[${schema.sessions.id}], false from ${schema.sessions} where ${schema.sessions.workspaceId} = ${workspaceId} and ${schema.sessions.id} = ${sessionId} union all select parent.id, parent.parent_session_id, ancestors.depth + 1, ancestors.path || parent.id, parent.id = any(ancestors.path) from ${schema.sessions} parent join ancestors on ancestors.parent_session_id = parent.id where parent.workspace_id = ${workspaceId} and not ancestors.cycle and ancestors.depth < 64 ) select id, parent_session_id as "parentSessionId", depth, path, cycle from ancestors order by depth desc `)) as LineageIdRow[]; const frontier = ancestorLineageRows[0]; if ( !frontier || frontier.cycle || frontier.parentSessionId !== null || Number(frontier.depth) >= 64 ) { throw new Error(`session lineage for ${sessionId} has no valid workspace root`); } const ancestorRows = ancestorLineageRows.filter((row) => row.depth > 0); const childRows = await selectSessionDescendantRows(scopedDb, workspaceId, sessionId); const truncated = childRows.length > descendantLimit; const descendantRows = truncated ? childRows.slice(0, descendantLimit) : childRows; const lineageRows = [...ancestorRows, ...descendantRows]; const ids = [...new Set(lineageRows.map((row) => row.id))]; if (ids.length === 0) { return { ancestors: [], children: [], truncated: false }; } const rows = await scopedDb .select(sessionReadColumns(skills)) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), anyOf(schema.sessions.id, ids))); const canonicalRows = await canonicalSessionRowsFromEventCursors(scopedDb, workspaceId, rows); const grouped = await sessionMcpServerMetadataForSessions( scopedDb, workspaceId, canonicalRows.map((row) => row.id), ); const controls = await sessionControlProjections(scopedDb, workspaceId, ids); const requiresActionSince = await sessionRequiresActionSinceForSessions( scopedDb, workspaceId, canonicalRows.filter((row) => row.status === "requires_action").map((row) => row.id), ); const omitUnreadSkills = (session: Session): Session | SessionWithoutSkills => skills === "read" ? session : omitSessionSkills(session); const sessionsById = new Map( canonicalRows.map((row) => { const control = controls.get(row.id); if (!control) throw new Error(`Effective control missing for session ${row.id}`); return [ row.id, omitUnreadSkills( withRequiresActionSince( mapSession(row, control, grouped.get(row.id) ?? []), requiresActionSince, ), ), ] as const; }), ); const ancestors = ancestorRows .map((row) => sessionsById.get(row.id)) .filter((session): session is Session | SessionWithoutSkills => Boolean(session)); const nodesById = new Map(); for (const row of descendantRows) { const session = sessionsById.get(row.id); if (session) { nodesById.set(row.id, { session, children: [] }); } } const children: LineageNodeWithoutSkills[] = []; for (const row of descendantRows) { const node = nodesById.get(row.id); if (!node) continue; if (row.parentSessionId === sessionId) { children.push(node); } else { nodesById.get(row.parentSessionId ?? "")?.children.push(node); } } // Read with the Skill folders, every node carries them. return { ancestors, children, truncated } as SessionLineage | SessionLineageWithoutSkills; }); } /** * Count sessions still attached to a live Temporal workflow: queued, running, * or awaiting an approval (requires_action). idle has no running execution and * failed/cancelled are terminal, so neither blocks a workspace delete. The * delete path uses this to refuse (409) while a session could still be running * in Temporal, since there is no clean session-terminate to call first. */ export async function countActiveSessionsForWorkspace( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [{ count } = { count: 0 }] = await scopedDb .select({ count: sql`count(*)::int`, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), inArray(schema.sessions.status, ["queued", "running", "requires_action"]), ), ); return Number(count); }); } /** Immutable creation evidence for scheduled-session binding checks, never continuation defaults. */ export async function getSessionCreationExecutionPolicy( db: Database, workspaceId: string, sessionId: string, ) { return withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ model: schema.sessions.model, reasoningEffort: schema.sessions.reasoningEffort, latencyMode: schema.sessions.latencyMode, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return row ?? null; }); } export async function requireSession( db: Database, workspaceId: string, sessionId: string, ): Promise { const session = await getSession(db, workspaceId, sessionId); if (!session) { throw new Error(`Session not found: ${sessionId}`); } return session; } export type ListSessionEventsOptions = { after?: number; before?: number; limit?: number; direction?: SessionEventReadDirection; includeTypes?: readonly SessionEventType[]; excludeTypes?: readonly SessionEventType[]; includeClasses?: readonly SessionEventSemanticClass[]; excludeClasses?: readonly SessionEventSemanticClass[]; defaultExcludeTypes?: readonly SessionEventType[]; /** * Agent-monitoring conversation boundary: omit a human/API `user.message` * whose accepted turn was never claimed (`session_turns.started_at IS NULL`), * whether it is still queued or reached a terminal state before any claim. * The row appears at its own sequence once the turn is claimed. Forensic, * SSE, and REST readers leave this unset so the retained event log stays * exact. */ excludeUnclaimedHumanPrompts?: boolean; /** * Omit per-message assistant completions (they carry a provider `messageId` * or a `phase`). The settling `turn.completed` carries the answer, so a * reader of settled changes excludes them in SQL: a long run of progress * notes can then neither wake it nor fill its page ahead of the outcome. */ excludeStreamedAssistantMessages?: boolean; payloadMode?: SessionEventPayloadMode; /** * Keep `agent.toolCall.created` rows of presented calls (see * isPresentedSessionToolCall) even when that type is excluded, so a * conversation-first reader still sees images, published files, Skill * changes and payment pages without loading every step. Excluded rows without a turn (PTY and * background command output) stay excluded: the sandbox dock reads them * itself. No effect unless `agent.toolCall.created` is excluded. */ retainPresentedToolCalls?: boolean; /** * Full-mode step reads: return each `agent.toolCall.output` payload larger * than SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MIN_BYTES as a bounded preview * (long strings keep their head and tail around an explicit omission * marker) carrying an `outputPreview` fact. Readers load one row's exact * payload with an ordinary full read when they need it. No effect in other * payload modes. */ toolOutputPreview?: boolean; /** * Internal exclusive-latest selector. Eligible legacy rows with a null * association remain visible, while late-rejected and duplicate callbacks do * not compete with current truth. Durable session sequence is authoritative * across distinct turns; turn generation is metadata only here. Callers must * pair this with a single semantic class and limit 1. */ authoritativeLatest?: boolean; }; /** * LIKE patterns equal to isPresentedSessionToolName: each leaf alone, or after * `__`. One LIKE ANY evaluates the name once per row and costs a fraction of * the equivalent regex, which dominated long scans even on a short column. */ const PRESENTED_TOOL_NAME_PATTERNS = SESSION_EVENT_PRESENTED_TOOL_LEAVES.flatMap((leaf) => { const literal = leaf.replace(/[\\%_]/g, "\\$&"); return [literal, `%\\_\\_${literal}`]; }); /** The same LIKE patterns for the app action call tool. */ const APP_ACTION_CALL_NAME_PATTERNS = [SESSION_EVENT_APP_ACTION_CALL_LEAF].flatMap((leaf) => { const literal = leaf.replace(/[\\%_]/g, "\\$&"); return [literal, `%\\_\\_${literal}`]; }); function sessionEventExcludeTypesFilter( excludeTypes: readonly SessionEventType[], options: Pick, ): SQL { const excluded = notInArray(schema.sessionEvents.type, [...excludeTypes]); if (!options.retainPresentedToolCalls || !excludeTypes.includes("agent.toolCall.created")) { return excluded; } // The name check reads only created rows (never tool outputs) and uses the // trigger-filled tool_name column (migration 0889), so it never detoasts a // call's arguments. Rows written before 0889 keep a NULL column; only they // fall back to the payload name, which classifies them exactly as before. const patterns = sql.join( PRESENTED_TOOL_NAME_PATTERNS.map((pattern) => sql`${pattern}::text`), sql`, `, ); const appActionPatterns = sql.join( APP_ACTION_CALL_NAME_PATTERNS.map((pattern) => sql`${pattern}::text`), sql`, `, ); const toolName = sql`coalesce(${schema.sessionEvents.toolName}, ${schema.sessionEvents.payload} ->> 'name')`; // An app action call's arguments are an object or its JSON text; only their // top-level "id" counts, trimmed and matched exactly as presentedAppActionId does. // Text is read as json (not jsonb) and skipped if it escapes a NUL, which // Postgres can't turn into text: no stored call can make this query fail. const payload = schema.sessionEvents.payload; const actionId = sql`btrim(case jsonb_typeof(${payload} -> 'arguments') when 'object' then ${payload} -> 'arguments' ->> 'id' when 'string' then case when (${payload} ->> 'arguments') is json object and strpos(${payload} ->> 'arguments', ${"\\u0000"}::text) = 0 then (${payload} ->> 'arguments')::json ->> 'id' end end, ${SESSION_EVENT_APP_ACTION_ID_SPACE}::text)`; const presentedActions = sql.join( SESSION_EVENT_PRESENTED_APP_ACTION_NAMES.map((name) => sql`${name}::text`), sql`, `, ); return or( excluded, and( eq(schema.sessionEvents.type, "agent.toolCall.created"), or( sql`${toolName} like any (array[${patterns}])`, // Payment pages: only app action calls (whose payload is their short // arguments) are read past the name, for the action id. and( sql`${toolName} like any (array[${appActionPatterns}])`, sql`${actionId} = any (array[${presentedActions}])`, ), ), ), )!; } export type ListSessionEventPageOptions = ListSessionEventsOptions & { /** UTF-8 JSON-array page target; one oversized full event is returned alone. */ maxBytes?: number; /** Internal SQL fetch size. Batches never escape the surrounding RLS transaction. */ batchSize?: number; }; export type SessionEventPage = { events: SessionEvent[]; hasMore: boolean; bytes: number; /** True only when every full-mode event is the exact retained database row. */ fullPayloadsExact: boolean; direction: SessionEventReadDirection; coveredSequence: { first: number; last: number } | null; nextAfter: number | null; nextBefore: number | null; truncatedBy: "count" | "bytes" | null; }; const POSTGRES_INT_MAX = 2_147_483_647; export const SESSION_EVENT_DB_PAGE_MAX_BYTES = 1024 * 1024; /** * Largest canonical event payload a full-mode history read returns verbatim. * Larger legacy rows are projected in SQL to an explicit preview. */ export const SESSION_EVENT_FULL_READ_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024; const SESSION_EVENT_FULL_READ_PREVIEW_CHARS = 32 * 1024; /** A previewed step read returns tool-output payloads up to this size exactly. */ export const SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MIN_BYTES = 4 * 1024; /** Hard ceiling of one previewed tool-output payload (structured or text). */ export const SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MAX_BYTES = 16 * 1024; /** Strings longer than this keep only their head and tail in a preview. */ const TOOL_OUTPUT_PREVIEW_STRING_MAX_CHARS = 2048; const TOOL_OUTPUT_PREVIEW_HEAD_CHARS = 1024; const TOOL_OUTPUT_PREVIEW_TAIL_CHARS = 512; /** * Nesting below `output` whose strings are shortened in place * (output.content[i].text is 3). Containers are walked above this depth only. */ const TOOL_OUTPUT_PREVIEW_DEPTH = 3; /** A walked array or object wider than this sends the row to the text preview. */ const TOOL_OUTPUT_PREVIEW_MAX_WIDTH = 16; /** Internal marker of a container too wide to walk; never delivered. */ const TOOL_OUTPUT_PREVIEW_TOO_WIDE = "opengeni:tool-output-preview:too-wide"; /** A previewed output plans at least this share of its source bytes (1/n). */ const TOOL_OUTPUT_PREVIEW_SOURCE_SHARE = 16; const SESSION_EVENT_DB_BATCH_SIZE = 256; const SESSION_EVENT_INTERACTIVE_PAGE_MAX = 255; type SessionEventProjectionRow = { id: string; workspaceId: string; sessionId: string; sequence: number; type: string; payload: unknown; payloadCodecVersion: number | null; occurredAt: Date; clientEventId: string | null; turnId: string | null; turnGeneration: number | null; turnAttemptId: string | null; turnAssociation: string | null; duplicateOfEventId: string | null; duplicateReason: string | null; /** Full mode replaced an oversized canonical payload with a read preview. */ payloadReadBounded?: boolean; }; type SessionEventProjectionMetadataRow = { id: string; sequence: number; /** Conservative server-side size including columns omitted from the public event. */ transferBytes: number; }; type SessionEventProjectionSource = { [Key in keyof SessionEventProjectionRow]: SQLWrapper; }; /** * The last sequence a reader positioned after `after` may treat as covered * because storage intentionally holds nothing there (an archived session's * purged telemetry, for example). Sequences are allocated under the session * row lock, so a committed later event or `last_sequence` proves every lower * sequence already committed or was removed. One statement reads both in one * snapshot: the next stored sequence minus one, or `last_sequence` when * nothing is stored after `after`. Never less than `after`. */ export async function readSessionEventStorageGapEnd( db: Database, workspaceId: string, sessionId: string, after: number, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ next: number | null; last: number | null }>( scopedDb, sql`select (select min(e.sequence) from session_events e where e.workspace_id = ${workspaceId}::uuid and e.session_id = ${sessionId}::uuid and e.sequence > ${after}) as next, (select s.last_sequence from sessions s where s.workspace_id = ${workspaceId}::uuid and s.id = ${sessionId}::uuid) as last`, ); const next = row?.next === null || row?.next === undefined ? null : Number(row.next); const last = row?.last === null || row?.last === undefined ? after : Number(row.last); return Math.max(after, next === null ? last : next - 1); }); } /** * Read one direction-aware session-event page. Full mode selects the canonical * row exactly, allowing one oversized event alone so its cursor can progress. * The byte budget bounds page selection, never retained payloads. Summary/none modes derive * bounded monitoring projections in SQL without rewriting the retained source. * `bytes` is the exact UTF-8 size of `JSON.stringify(events)`; `hasMore` is true * whenever count or byte selection stopped before the durable range ended. */ export async function listSessionEventPage( db: Database, workspaceId: string, sessionId: string, options: ListSessionEventPageOptions = {}, ): Promise { const after = normalizeEventSequence(options.after, 0); const requestedLimit = Math.max(1, normalizeEventLimit(options.limit, 500)); const hasBefore = options.before !== undefined && Number.isFinite(options.before); const before = hasBefore ? Math.floor(options.before as number) : undefined; const direction = options.direction ?? (hasBefore ? "before" : "after"); const payloadMode = options.payloadMode ?? "full"; const toolOutputPreview = payloadMode === "full" && options.toolOutputPreview === true; const transferBytesSql = sessionEventTransferBytes(toolOutputPreview); const typeFilters = resolveSessionEventTypeFilters({ includeTypes: options.includeTypes, excludeTypes: options.excludeTypes, includeClasses: options.includeClasses, excludeClasses: options.excludeClasses, defaultExcludeTypes: options.defaultExcludeTypes, }); const maxBytes = Math.max( SESSION_EVENT_ENVELOPE_MAX_BYTES + 2, normalizeEventLimit(options.maxBytes, SESSION_EVENT_DB_PAGE_MAX_BYTES), ); // Interactive browser pages intentionally stop at 255 rows. Carry their // one-row continuation lookahead in the same indexed query so latency is not // multiplied by transaction-pool or cross-region round trips. Larger reads // use bounded 256-row batches; full-mode metadata planning below preserves // the page's byte budget before any canonical payload is transferred. const defaultBatchSize = requestedLimit <= SESSION_EVENT_INTERACTIVE_PAGE_MAX ? requestedLimit + 1 : SESSION_EVENT_DB_BATCH_SIZE; const batchSize = Math.max( 1, Math.min(256, normalizeEventLimit(options.batchSize, defaultBatchSize)), ); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const events: SessionEvent[] = []; let bytes = 2; // [] let cursor = direction === "before" ? before : after; let hasMore = false; let fullPayloadsExact = payloadMode === "full"; let truncatedBy: SessionEventPage["truncatedBy"] = null; for (;;) { const remainingWithLookahead = Math.max(1, requestedLimit - events.length + 1); const queryLimit = Math.min(batchSize, remainingWithLookahead); const filters: SQL[] = [ eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), gt(schema.sessionEvents.sequence, after), ]; if (options.excludeUnclaimedHumanPrompts) { filters.push(excludeUnclaimedHumanPromptEventFilter(workspaceId)); } if (options.excludeStreamedAssistantMessages) { filters.push(excludeStreamedAssistantMessageEventFilter()); } if (options.authoritativeLatest) { // Historical rows predate association stamping and intentionally carry // null. They remain eligible; explicitly stale/duplicate rows and rows // carrying a duplicate reference cannot compete with current truth. A // completed progress note is not a result, so it cannot be the latest // terminal event while a turn is still working. filters.push( and( or( isNull(schema.sessionEvents.turnAssociation), eq(schema.sessionEvents.turnAssociation, "current"), )!, isNull(schema.sessionEvents.duplicateOfEventId), sql`not (${schema.sessionEvents.type} = 'agent.message.completed' and coalesce(${schema.sessionEvents.payload} ->> 'phase', '') = 'commentary')`, )!, ); } if (typeFilters.includeTypes.length > 0) { filters.push(inArray(schema.sessionEvents.type, typeFilters.includeTypes)); } if (typeFilters.excludeTypes.length > 0) { filters.push(sessionEventExcludeTypesFilter(typeFilters.excludeTypes, options)); } if (direction === "before") { if (cursor !== undefined && cursor <= POSTGRES_INT_MAX) { filters.push(lt(schema.sessionEvents.sequence, cursor)); } } else if (cursor !== undefined) { filters.push(gt(schema.sessionEvents.sequence, cursor)); } if (direction === "after" && before !== undefined && before <= POSTGRES_INT_MAX) { filters.push(lt(schema.sessionEvents.sequence, before)); } const ordering = options.authoritativeLatest || direction === "before" ? desc(schema.sessionEvents.sequence) : asc(schema.sessionEvents.sequence); let rows: SessionEventProjectionRow[]; let sourceRowCount: number; let sourceRowsFullyConsumed = true; if (payloadMode === "full") { if ( requestedLimit <= SESSION_EVENT_INTERACTIVE_PAGE_MAX && options.batchSize === undefined ) { const remainingCount = Math.max(1, requestedLimit - events.length); const availableTransferBytes = Math.max( 1, maxBytes - bytes + (events.length === 0 ? 1 : 0), ); const candidateOrdering = options.authoritativeLatest || direction === "before" ? sql`sequence desc` : sql`sequence asc`; // Plan from IDs first, then size only the prefix that can reach this page. // A window over payload sizes would detoast every lookahead row // and repeat that work for each oversized event delivered alone. // The recursive guard stops before reading the next payload once the // count/byte target is reached. IDs still provide exact continuation. const selection = sql`( with recursive candidates as materialized ( select ${schema.sessionEvents.id}, ${schema.sessionEvents.sequence} from ${schema.sessionEvents} where ${and(...filters)} order by ${ordering} limit ${queryLimit} ), ordered as materialized ( select id, row_number() over (order by ${candidateOrdering})::int as row_number from candidates ), bounded as ( select ordered.id, ordered.row_number, ${transferBytesSql} + 1 as cumulative_transfer_bytes from ordered join ${schema.sessionEvents} on ${schema.sessionEvents.id} = ordered.id where ordered.row_number = 1 union all select ordered.id, ordered.row_number, bounded.cumulative_transfer_bytes + ${transferBytesSql} + 1 from bounded join ordered on ordered.row_number = bounded.row_number + 1 join ${schema.sessionEvents} on ${schema.sessionEvents.id} = ordered.id where bounded.cumulative_transfer_bytes <= ${availableTransferBytes} and bounded.row_number < ${remainingCount} ) select id, row_number, (select count(*)::int from ordered) as source_row_count from bounded where row_number = 1 or cumulative_transfer_bytes <= ${availableTransferBytes} ) as session_event_page_selected`; const selectedRows = await scopedDb .select({ ...sessionEventProjectionSelect("full", schema.sessionEvents, { toolOutputPreview }), sourceRowCount: sql`session_event_page_selected.source_row_count`, }) .from(schema.sessionEvents) .innerJoin(selection, sql`${schema.sessionEvents.id} = session_event_page_selected.id`) .orderBy(sql`session_event_page_selected.row_number`); sourceRowCount = Number(selectedRows[0]?.sourceRowCount ?? 0); rows = selectedRows.map(({ sourceRowCount: _sourceRowCount, ...row }) => row); sourceRowsFullyConsumed = rows.length >= sourceRowCount; if (!sourceRowsFullyConsumed) { hasMore = true; truncatedBy = rows.length >= remainingCount ? "count" : "bytes"; } } else { // Discover the complete candidate frontier without payloads, then size // only the prefix the byte/count budget can use (plus its overflow row). // Indexing the ordered ID array avoids rescanning an ordered CTE at // every recursion step. Keep the subsequent payload SELECT separate: // this is still metadata planning, not a new page-wide snapshot. // The recursive step reads its next ID through a scalar subquery so // the lookup compares the ID with a plain parameter (the subquery runs // as an InitPlan). Under row-level security PostgreSQL uses a lookup // as an index condition only when it is leakproof, and since the // November 2026 minor releases (16.16, 17.12, 18.7; CVE-2026-116327) // any non-leakproof function over a value from elsewhere in the query // makes it leaky. `id = ordered.ids[bounded.row_number + 1]` written // in the lookup itself is leaky because of `+`, and turns every step // into a filtered scan of the whole session. const metadataRows = await rawRows< SessionEventProjectionMetadataRow & { sourceRowCount: number } >( scopedDb, sql`with recursive candidates as materialized ( select ${schema.sessionEvents.id}, ${schema.sessionEvents.sequence} from ${schema.sessionEvents} where ${and(...filters)} order by ${ordering} limit ${queryLimit} ), ordered as materialized ( select array_agg(id order by ${ options.authoritativeLatest || direction === "before" ? sql`sequence desc` : sql`sequence asc` }) as ids from candidates ), bounded as ( select sized.id, sized.sequence, 1 as row_number, sized.bytes as transfer_bytes, ${bytes + (events.length === 0 ? 0 : 1)}::bigint + sized.bytes as cumulative_bytes from ordered cross join lateral ( select ${schema.sessionEvents.id}, ${schema.sessionEvents.sequence}, (${transferBytesSql})::int as bytes from ${schema.sessionEvents} where ${schema.sessionEvents.id} = ordered.ids[1] and ${schema.sessionEvents.workspaceId} = ${workspaceId} and ${schema.sessionEvents.sessionId} = ${sessionId} offset 0 ) sized union all select sized.id, sized.sequence, bounded.row_number + 1, sized.bytes, bounded.cumulative_bytes + 1 + sized.bytes from bounded cross join lateral ( select ${schema.sessionEvents.id}, ${schema.sessionEvents.sequence}, (${transferBytesSql})::int as bytes from ${schema.sessionEvents} where ${schema.sessionEvents.id} = ( select ordered.ids[bounded.row_number + 1] from ordered ) and ${schema.sessionEvents.workspaceId} = ${workspaceId} and ${schema.sessionEvents.sessionId} = ${sessionId} offset 0 ) sized where bounded.cumulative_bytes <= ${maxBytes} and bounded.row_number <= ${requestedLimit - events.length} ) select id, sequence, transfer_bytes as "transferBytes", (select cardinality(ids) from ordered) as "sourceRowCount" from bounded order by row_number`, ); sourceRowCount = Number(metadataRows[0]?.sourceRowCount ?? 0); if (metadataRows.length === 0) break; const exactIds: string[] = []; let estimatedBytes = bytes; for (const metadata of metadataRows) { if (events.length + exactIds.length >= requestedLimit) { hasMore = true; truncatedBy = "count"; break; } const separatorBytes = events.length + exactIds.length === 0 ? 0 : 1; const transferBytes = Number(metadata.transferBytes); if (estimatedBytes + separatorBytes + transferBytes > maxBytes) { if (events.length === 0 && exactIds.length === 0) { exactIds.push(metadata.id); if (sourceRowCount > 1) { hasMore = true; truncatedBy = "bytes"; } } else { hasMore = true; truncatedBy = "bytes"; } break; } exactIds.push(metadata.id); estimatedBytes += separatorBytes + transferBytes; } sourceRowsFullyConsumed = exactIds.length >= sourceRowCount; if (exactIds.length > 0) { rows = await scopedDb .select( sessionEventProjectionSelect("full", schema.sessionEvents, { toolOutputPreview }), ) .from(schema.sessionEvents) .where(and(...filters, inArray(schema.sessionEvents.id, exactIds))) .orderBy(ordering) .limit(exactIds.length); } else { rows = []; } } } else { rows = await scopedDb .select(sessionEventProjectionSelect(payloadMode)) .from(schema.sessionEvents) .where(and(...filters)) .orderBy(ordering) .limit(queryLimit); sourceRowCount = rows.length; if (rows.length === 0) break; } for (const row of rows) { if (events.length >= requestedLimit) { hasMore = true; truncatedBy = "count"; break; } const event = mapProjectedEvent(row); if (row.payloadReadBounded === true) fullPayloadsExact = false; if (toolOutputPreview && isToolOutputPreviewEvent(event)) fullPayloadsExact = false; const eventBytes = utf8JsonBytes(event); const separatorBytes = events.length === 0 ? 0 : 1; if (bytes + separatorBytes + eventBytes > maxBytes) { if (events.length === 0) { if (payloadMode !== "full" && eventBytes + 2 > maxBytes) { throw new RangeError( `A projected session event cannot fit in the database page envelope (${eventBytes + 2} > ${maxBytes} bytes)`, ); } } else { hasMore = true; truncatedBy = "bytes"; break; } } events.push(event); bytes += separatorBytes + eventBytes; cursor = event.sequence; } if (hasMore) break; if (sourceRowsFullyConsumed && sourceRowCount < queryLimit) break; } if (direction === "before") events.reverse(); const first = events[0]?.sequence ?? null; const last = events.at(-1)?.sequence ?? null; return { events, hasMore, bytes, fullPayloadsExact, direction, coveredSequence: first === null || last === null ? null : { first, last }, nextAfter: direction === "after" ? (last ?? after) : null, nextBefore: direction === "before" ? (first ?? before ?? null) : null, truncatedBy, }; }); } export type SessionEventConversationTurn = { turnId: string; /** * Sequence of the turn's first `turn.started` in the page, if the page holds * one. The turn's first stored `turn.started` takes precedence. */ started: number | null; }; const SESSION_TURN_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** Bookkeeping rows one turn may add to a conversation page (normally a handful). */ const SESSION_EVENT_CONVERSATION_BOOKKEEPING_PER_TURN = 64; /** * The bookkeeping rows (SESSION_EVENT_BOOKKEEPING_STEP_TYPES) a conversation * page that excludes them still carries, strictly inside `(after, before)`, * for the page's turns and the turn last started at or before `after` (its * rows may continue into this page without any of its rows on it): * * - a turn with no content step at all (SESSION_EVENT_CONTENT_STEP_TYPES) * keeps every bookkeeping row, so its window skips no sequence and a reader * is not offered steps that are not there; * - any other turn keeps its model request rows from its first `turn.started` * through its first model response: the only ones its startup phases draw. * Later request rows and all usage rows are steps. The segment depends only * on stored rows, so every page boundary splits it the same way. * * One statement plans the ids from indexes (per turn, at most * SESSION_EVENT_CONVERSATION_BOOKKEEPING_PER_TURN rows of each kind) and a * second reads them, ascending. */ export async function listSessionEventConversationBookkeeping( db: Database, workspaceId: string, sessionId: string, options: { turns: readonly SessionEventConversationTurn[]; after: number; before?: number | undefined; payloadMode?: SessionEventPayloadMode; }, ): Promise { const turns = options.turns.filter((turn) => SESSION_TURN_ID_PATTERN.test(turn.turnId)); const after = Math.max(0, Math.floor(options.after)); const before = options.before !== undefined && Number.isFinite(options.before) ? Math.min(POSTGRES_INT_MAX, Math.floor(options.before)) : POSTGRES_INT_MAX; if (before <= after + 1) return []; const turnIds = `{${turns.map((turn) => turn.turnId).join(",")}}`; const anchors = `{${turns.map((turn) => (turn.started === null ? "NULL" : String(Math.floor(turn.started)))).join(",")}}`; const contentTypes = `{${SESSION_EVENT_CONTENT_STEP_TYPES.join(",")}}`; const bookkeepingTypes = `{${SESSION_EVENT_BOOKKEEPING_STEP_TYPES.join(",")}}`; const perTurn = SESSION_EVENT_CONVERSATION_BOOKKEEPING_PER_TURN; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const planned = await rawRows<{ id: string }>( scopedDb, sql`with open_turn as ( select e.turn_id, e.sequence as anchor from session_events e where e.workspace_id = ${workspaceId}::uuid and e.session_id = ${sessionId}::uuid and e.type = 'turn.started' and e.sequence <= ${after} and e.turn_id is not null order by e.sequence desc limit 1 ), listed as ( select turn_id, anchor from unnest(${turnIds}::uuid[], ${anchors}::int[]) as t(turn_id, anchor) union all select turn_id, anchor from open_turn ), turn_list as ( select turn_id, min(anchor) as listed_anchor from listed group by turn_id ), page_turns as ( select t.turn_id, coalesce(( select min(s.sequence) from session_events s where s.workspace_id = ${workspaceId}::uuid and s.turn_id = t.turn_id and s.type = 'turn.started' and s.session_id = ${sessionId}::uuid ), t.listed_anchor) as anchor, exists ( select 1 from session_events c where c.workspace_id = ${workspaceId}::uuid and c.turn_id = t.turn_id and c.type = any(${contentTypes}::text[]) and c.session_id = ${sessionId}::uuid ) as has_content from turn_list t ), content_free as ( select b.id from page_turns p cross join lateral ( select e.id from session_events e where e.workspace_id = ${workspaceId}::uuid and e.turn_id = p.turn_id and e.type = any(${bookkeepingTypes}::text[]) and e.session_id = ${sessionId}::uuid and e.sequence > ${after} and e.sequence < ${before} order by e.sequence limit ${perTurn} ) b where not p.has_content ), startup as ( select r.id, p.turn_id, r.sequence, r.responded from page_turns p cross join lateral ( select e.id, e.turn_id, e.sequence, coalesce(e.payload ->> 'phase', '') in ('first_byte', 'first_event') as responded from session_events e where e.workspace_id = ${workspaceId}::uuid and e.session_id = ${sessionId}::uuid and e.type = 'agent.model.request' and e.sequence > p.anchor and e.sequence < ${before} order by e.sequence limit ${perTurn} ) r where p.has_content and p.anchor is not null and r.turn_id = p.turn_id ), startup_segment as ( select id from ( select id, sequence, coalesce(sum(case when responded then 1 else 0 end) over ( partition by turn_id order by sequence rows between unbounded preceding and 1 preceding ), 0) as earlier_responses from startup ) ranked where earlier_responses = 0 and sequence > ${after} ) select id from content_free union select id from startup_segment`, ); if (planned.length === 0) return []; const rows = await scopedDb .select(sessionEventProjectionSelect(options.payloadMode ?? "full")) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), inArray( schema.sessionEvents.id, planned.map((row) => row.id), ), ), ) .orderBy(asc(schema.sessionEvents.sequence)); return rows.map(mapProjectedEvent); }); } /** * Conservative transfer size used to plan a page before payloads are read. A * tool output a previewed read may bound counts its preview ceiling, or a * sixteenth of its source when larger: the page then also bounds the source * bytes the projection walks, not only the bytes it delivers. A row the * projection then returns exact is still bounded by the delivered page check. */ function sessionEventTransferBytes(toolOutputPreview: boolean): SQL { const exact = sql`octet_length(row_to_json(${schema.sessionEvents})::text)::bigint`; if (!toolOutputPreview) return exact; const ceiling = sql.raw(String(SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MAX_BYTES + 2048)); const share = sql.raw(String(TOOL_OUTPUT_PREVIEW_SOURCE_SHARE)); // offset 0 keeps the serialized size computed once instead of inlined. The // payload is read here anyway, so only a row the projection can preview (an // object with an `output`) is planned below its exact size. return sql`(select case when ${toolOutputPreviewCandidate(schema.sessionEvents)} and jsonb_typeof(${schema.sessionEvents.payload}) = 'object' and (${schema.sessionEvents.payload} -> 'output') is not null then least(tool_output_row.bytes, greatest(${ceiling}, tool_output_row.bytes / ${share})) else tool_output_row.bytes end from (select ${exact} as bytes offset 0) as tool_output_row)`; } /** * A row a previewed read may bound: a tool output not stored with the * lossless string codec (shortening an encoded string would corrupt it). * Decided from columns alone, without reading the payload; its shape and size * are decided once inside the projection. */ function toolOutputPreviewCandidate( source: Pick, ): SQL { return sql`( ${source.type} = 'agent.toolCall.output' and ${source.payloadCodecVersion} is null )`; } /** Head and tail of a long string around an explicit omission marker. */ function toolOutputPreviewText(text: SQL): SQL { const max = sql.raw(String(TOOL_OUTPUT_PREVIEW_STRING_MAX_CHARS)); const head = sql.raw(String(TOOL_OUTPUT_PREVIEW_HEAD_CHARS)); const tail = sql.raw(String(TOOL_OUTPUT_PREVIEW_TAIL_CHARS)); const kept = sql.raw(String(TOOL_OUTPUT_PREVIEW_HEAD_CHARS + TOOL_OUTPUT_PREVIEW_TAIL_CHARS)); return sql`case when char_length(${text}) <= ${max} then ${text} else left(${text}, ${head}) || chr(10) || '…[' || (char_length(${text}) - ${kept})::text || ' characters omitted from this preview]…' || chr(10) || right(${text}, ${tail}) end`; } /** * Shorten the long strings of one JSON value, keeping its shape. Inline media * (data URLs, `data`/`image_url` fields) is kept whole: a shortened image is * not an image, so such a row falls back to the text preview below. A * container wider than TOOL_OUTPUT_PREVIEW_MAX_WIDTH is not walked: it becomes * a marker that sends the row to the text preview, so the walk stays bounded * however large the output is. Each string is extracted once (offset 0). */ function toolOutputPreviewValue(value: SQL, key: SQL | null, depth: number): SQL { const t = sql.raw(`tool_output_s${depth}.t`); const shortened = sql`(select case when left(${t}, 5) = 'data:' then ${value} else to_jsonb(${toolOutputPreviewText(t)}) end from (select ${value} #>> '{}' as t offset 0) as ${sql.raw(`tool_output_s${depth}`)})`; const string = key ? sql`case when ${key} in ('data', 'image_url', 'blob') then ${value} else ${shortened} end` : shortened; if (depth >= TOOL_OUTPUT_PREVIEW_DEPTH) { return sql`case when jsonb_typeof(${value}) = 'string' then ${string} else ${value} end`; } const width = sql.raw(String(TOOL_OUTPUT_PREVIEW_MAX_WIDTH)); const wide = sql.raw(`to_jsonb('${TOOL_OUTPUT_PREVIEW_TOO_WIDE}'::text)`); const k = sql.raw(`tool_output_k${depth}`); const x = sql.raw(`tool_output_x${depth}`); const o = sql.raw(`tool_output_o${depth}`); return sql`case jsonb_typeof(${value}) when 'string' then ${string} when 'object' then case when (select count(*) from ( select 1 from jsonb_object_keys(${value}) limit ${width} + 1 ) as ${sql.raw(`tool_output_w${depth}`)}) > ${width} then ${wide} else coalesce(( select jsonb_object_agg(${k}, ${toolOutputPreviewValue(x, k, depth + 1)}) from jsonb_each(${value}) as ${sql.raw(`tool_output_e${depth}`)}(${k}, ${x}) ), '{}'::jsonb) end when 'array' then case when jsonb_array_length(${value}) > ${width} then ${wide} else coalesce(( select jsonb_agg(${toolOutputPreviewValue(x, null, depth + 1)} order by ${o}) from jsonb_array_elements(${value}) with ordinality as ${sql.raw(`tool_output_a${depth}`)}(${x}, ${o}) ), '[]'::jsonb) end else ${value} end`; } /** * The bounded preview of one tool-output payload. A payload that is not an * object with an `output`, or is within SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MIN_BYTES, * is exact. Otherwise every field but `output` is kept and the output keeps * its shape with long strings shortened (`shape: "structured"`). When that is * too wide or still exceeds the ceiling, a payload within the ceiling is exact * and a larger one becomes the head and tail of its output text * (`shape: "text"`). A payload with nothing to shorten is returned exact, * without a preview fact. * * Each step is fenced with offset 0 so the planner does not inline it: the * payload is read (detoasted) and serialized once, and the output text at * most once more. */ function toolOutputPreviewPayload(payload: SQLWrapper): SQL { const min = sql.raw(String(SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MIN_BYTES)); const max = sql.raw(String(SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MAX_BYTES)); const wide = sql.raw(`'"${TOOL_OUTPUT_PREVIEW_TOO_WIDE}"'`); const source = sql.raw("tool_output_source.payload"); const output = sql.raw("tool_output_source.output"); const structuredText = sql.raw("tool_output_structured.text"); const flatText = sql.raw("tool_output_flat.preview"); const fact = (shape: "structured" | "text", previewBytes: SQL) => sql`jsonb_build_object( 'truncated', true, 'reason', 'tool_output_preview', 'shape', ${sql.raw(`'${shape}'`)}, 'originalBytes', tool_output_size.original_bytes, 'previewBytes', ${previewBytes} )`; const textPreview = sql`(select jsonb_strip_nulls(jsonb_build_object( 'id', left(${source} ->> 'id', 256), 'name', left(${source} ->> 'name', 256), 'toolName', left(${source} ->> 'toolName', 256), 'status', left(${source} ->> 'status', 128), 'error', case when jsonb_typeof(${source} -> 'error') = 'boolean' then ${source} -> 'error' when jsonb_typeof(${source} -> 'error') = 'string' then to_jsonb(left(${source} ->> 'error', 1024)) when ${output} -> 'isError' = 'true'::jsonb then 'true'::jsonb end, 'failed', case when jsonb_typeof(${source} -> 'failed') = 'boolean' then ${source} -> 'failed' end, 'truncation', case when octet_length((${source} -> 'truncation')::text) <= 4096 then ${source} -> 'truncation' end, 'output', to_jsonb(${flatText}), 'outputPreview', ${fact("text", sql`octet_length(${flatText})`)} )) from (select coalesce( case when jsonb_typeof(${output}) = 'string' then ${output} #>> '{}' end, ${output} #>> '{content,0,text}', ${output}::text ) as text offset 0) as tool_output_text, lateral (select ${toolOutputPreviewText(sql.raw("tool_output_text.text"))} as preview offset 0) as tool_output_flat)`; return sql`(select case when not tool_output_source.previewable then ${payload} when tool_output_size.original_bytes <= ${min} then ${source} when position(${wide} in ${structuredText}) = 0 and octet_length(${structuredText}) <= ${max} then case when octet_length(${structuredText}) = tool_output_size.original_bytes then ${source} else tool_output_structured.payload || jsonb_build_object('outputPreview', ${fact( "structured", sql`octet_length(${structuredText})`, )}) end when tool_output_size.original_bytes <= ${max} then ${source} else ${textPreview} end from (select tool_output_read.payload, tool_output_read.payload -> 'output' as output, jsonb_typeof(tool_output_read.payload) = 'object' and (tool_output_read.payload -> 'output') is not null as previewable from (select ${payload} || '{}'::jsonb as payload offset 0) as tool_output_read offset 0) as tool_output_source, lateral (select octet_length((${source})::text) as original_bytes offset 0) as tool_output_size, lateral (select tool_output_structured_value.payload, tool_output_structured_value.payload::text as text from (select case when tool_output_source.previewable and tool_output_size.original_bytes > ${min} then (${source} - 'output') || jsonb_build_object( 'output', ${toolOutputPreviewValue(output, null, 0)} ) end as payload offset 0) as tool_output_structured_value offset 0) as tool_output_structured)`; } function isToolOutputPreviewEvent(event: SessionEvent): boolean { return ( event.type === "agent.toolCall.output" && typeof event.payload === "object" && event.payload !== null && Object.prototype.hasOwnProperty.call(event.payload, "outputPreview") ); } function sessionEventProjectionSelect( payloadMode: SessionEventPayloadMode = "full", source: SessionEventProjectionSource = schema.sessionEvents, options: { toolOutputPreview?: boolean | undefined } = {}, ) { const typeInvalid = sql`( octet_length(${source.type}) > ${SESSION_EVENT_TYPE_MAX_BYTES} or position(E'\\n' in ${source.type}) > 0 or position(E'\\r' in ${source.type}) > 0 )`; const clientEventIdInvalid = sql`( ${source.clientEventId} is not null and octet_length(${source.clientEventId}) > ${SESSION_EVENT_CLIENT_EVENT_ID_MAX_BYTES} )`; const turnAssociationInvalid = sql`( ${source.turnAssociation} is not null and ${source.turnAssociation} not in ( 'current', 'late_rejected', 'duplicate' ) )`; const duplicateReasonInvalid = sql`( ${source.duplicateReason} is not null and octet_length(${source.duplicateReason}) > ${SESSION_EVENT_DUPLICATE_REASON_MAX_BYTES} )`; const envelopeInvalid = sql`( ${typeInvalid} or ${clientEventIdInvalid} or ${turnAssociationInvalid} or ${duplicateReasonInvalid} )`; const projectedType = sql`case when ${typeInvalid} then 'session.event.envelope_omitted' else ${source.type} end`; const projectedClientEventId = sql`case when ${clientEventIdInvalid} then left(${source.clientEventId}, 256) else ${source.clientEventId} end`; const projectedTurnAssociation = sql`case when ${turnAssociationInvalid} then null else ${source.turnAssociation} end`; const projectedDuplicateReason = sql`case when ${duplicateReasonInvalid} then left(${source.duplicateReason}, 1024) else ${source.duplicateReason} end`; const projectedEnvelopeFields = sql`( '[]'::jsonb || case when ${typeInvalid} then jsonb_build_array(jsonb_build_object( 'field', 'type', 'originalBytes', octet_length(${source.type}), 'deliveredBytes', octet_length(${projectedType}) )) else '[]'::jsonb end || case when ${clientEventIdInvalid} then jsonb_build_array(jsonb_build_object( 'field', 'clientEventId', 'originalBytes', octet_length(${source.clientEventId}), 'deliveredBytes', octet_length(${projectedClientEventId}) )) else '[]'::jsonb end || case when ${turnAssociationInvalid} then jsonb_build_array(jsonb_build_object( 'field', 'turnAssociation', 'originalBytes', octet_length(${source.turnAssociation}), 'deliveredBytes', 0 )) else '[]'::jsonb end || case when ${duplicateReasonInvalid} then jsonb_build_array(jsonb_build_object( 'field', 'duplicateReason', 'originalBytes', octet_length(${source.duplicateReason}), 'deliveredBytes', octet_length(${projectedDuplicateReason}) )) else '[]'::jsonb end )`; const projectedPayload = sql`case when ${envelopeInvalid} then jsonb_build_object( 'preview', '[legacy event envelope normalized at bounded database read boundary]', 'originalEventBytes', octet_length(row_to_json(${schema.sessionEvents})::text), 'originalType', left(${source.type}, 64), 'envelopeProjection', jsonb_build_object( 'truncated', true, 'surface', 'database_read_projection', 'fields', ${projectedEnvelopeFields} ), 'fullEvidence', jsonb_build_object('available', false, 'reason', 'not_retained') ) else opengeni_private.project_session_event_payload(${source.payload}) end`; const projectedPayloadBytes = sql`octet_length((${projectedPayload})::text)`; // Full reads stay exact for every ordinary row. A row whose canonical JSON // exceeds the read ceiling (only possible for rows written before tool output // was bounded at write time) is replaced in SQL by an explicit head preview, // so the API never materializes it. The cheap stored-size test comes first: // a row stored compressed in at most 16 KiB cannot expand past the ceiling. const fullPayloadOversized = sql`( pg_column_size(${source.payload}) > 16384 and octet_length((${source.payload})::text) > ${SESSION_EVENT_FULL_READ_MAX_PAYLOAD_BYTES} )`; const fullPayloadPreview = sql`left( coalesce( case when jsonb_typeof(${source.payload} -> 'output') = 'string' then ${source.payload} ->> 'output' end, ${source.payload} #>> '{output,content,0,text}', (${source.payload} -> 'output')::text, (${source.payload})::text ), ${SESSION_EVENT_FULL_READ_PREVIEW_CHARS} )`; const fullPayload = sql`case when ${fullPayloadOversized} then jsonb_strip_nulls(jsonb_build_object( 'id', left(${source.payload} ->> 'id', 256), 'name', left(coalesce(${source.payload} ->> 'name', ${source.payload} ->> 'toolName'), 256), 'status', left(${source.payload} ->> 'status', 128), 'error', case when jsonb_typeof(${source.payload} -> 'error') = 'boolean' then ${source.payload} -> 'error' end, 'isError', case when jsonb_typeof(${source.payload} #> '{output,isError}') = 'boolean' then ${source.payload} #> '{output,isError}' end, 'preview', ${fullPayloadPreview} || '…[rest of this oversized event omitted at the history read boundary]', 'truncation', jsonb_build_object( 'truncated', true, 'surface', 'database_read_projection', 'reason', 'payload_bytes_exceeded', 'originalBytes', octet_length((${source.payload})::text), 'deliveredBytes', octet_length(${fullPayloadPreview}), 'omittedBytes', octet_length((${source.payload})::text) - octet_length(${fullPayloadPreview}), 'estimatedOriginalTokens', ceil(octet_length((${source.payload})::text) / 4.0)::integer, 'estimatedDeliveredTokens', ceil(octet_length(${fullPayloadPreview}) / 4.0)::integer, 'fullEvidence', jsonb_build_object('available', false, 'reason', 'oversized'), 'details', jsonb_build_array(jsonb_build_object( 'path', '$', 'kind', 'object', 'originalBytes', octet_length((${source.payload})::text) )) ) )) ${ options.toolOutputPreview ? sql`when ${toolOutputPreviewCandidate(source)} then ${toolOutputPreviewPayload(source.payload)}` : sql`` } else ${source.payload} end`; const selectedPayload = payloadMode === "full" ? fullPayload : payloadMode === "none" ? sql`jsonb_build_object( '_monitoring', jsonb_build_object( 'payloadMode', 'none', 'payloadOmitted', true, 'projectedPayloadBytes', ${projectedPayloadBytes} ) )` : sql`case when ${projectedPayloadBytes} <= 4096 then ${projectedPayload} else jsonb_build_object( '_monitoring', jsonb_build_object( 'payloadMode', 'summary', 'payloadTruncated', true, 'projectedPayloadBytes', ${projectedPayloadBytes}, 'fullForensicPayload', 'request payloadMode=full explicitly' ), 'preview', left((${projectedPayload})::text, 2048) ) end`; return { id: sql`${source.id}`.as("id"), workspaceId: sql`${source.workspaceId}`.as("workspace_id"), sessionId: sql`${source.sessionId}`.as("session_id"), sequence: sql`${source.sequence}`.as("sequence"), type: payloadMode === "full" ? sql`${source.type}`.as("type") : projectedType.as("type"), payload: selectedPayload.as("payload"), payloadCodecVersion: payloadMode === "full" ? sql`case when ${fullPayloadOversized} then null else ${source.payloadCodecVersion} end`.as("payload_codec_version") : sql`null`.as("payload_codec_version"), occurredAt: sql`${source.occurredAt}`.as("occurred_at"), clientEventId: payloadMode === "full" ? sql`${source.clientEventId}`.as("client_event_id") : projectedClientEventId.as("client_event_id"), turnId: sql`${source.turnId}`.as("turn_id"), turnGeneration: sql`${source.turnGeneration}`.as("turn_generation"), turnAttemptId: sql`${source.turnAttemptId}`.as("turn_attempt_id"), turnAssociation: payloadMode === "full" ? sql`${source.turnAssociation}`.as("turn_association") : projectedTurnAssociation.as("turn_association"), duplicateOfEventId: sql`${source.duplicateOfEventId}`.as( "duplicate_of_event_id", ), duplicateReason: payloadMode === "full" ? sql`${source.duplicateReason}`.as("duplicate_reason") : projectedDuplicateReason.as("duplicate_reason"), payloadReadBounded: payloadMode === "full" ? sql`coalesce(${fullPayloadOversized}, false)`.as("payload_read_bounded") : sql`false`.as("payload_read_bounded"), }; } export async function listSessionEvents( db: Database, workspaceId: string, sessionId: string, ): Promise; export async function listSessionEvents( db: Database, workspaceId: string, sessionId: string, after: number, limit?: number, ): Promise; export async function listSessionEvents( db: Database, workspaceId: string, sessionId: string, options: ListSessionEventsOptions, ): Promise; export async function listSessionEvents( db: Database, workspaceId: string, sessionId: string, afterOrOptions: number | ListSessionEventsOptions = 0, legacyLimit = 500, ): Promise { const options = typeof afterOrOptions === "number" ? { after: afterOrOptions, limit: legacyLimit } : afterOrOptions; const after = normalizeEventSequence(options.after, 0); const limit = normalizeEventLimit(options.limit, 500); const hasBefore = options.before !== undefined && Number.isFinite(options.before); const before = hasBefore ? Math.floor(options.before as number) : undefined; const direction = options.direction ?? (hasBefore ? "before" : "after"); const typeFilters = resolveSessionEventTypeFilters({ includeTypes: options.includeTypes, excludeTypes: options.excludeTypes, includeClasses: options.includeClasses, excludeClasses: options.excludeClasses, defaultExcludeTypes: options.defaultExcludeTypes, }); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const filters: SQL[] = [ eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), gt(schema.sessionEvents.sequence, after), ]; if (typeFilters.includeTypes.length > 0) { filters.push(inArray(schema.sessionEvents.type, typeFilters.includeTypes)); } if (typeFilters.excludeTypes.length > 0) { filters.push(sessionEventExcludeTypesFilter(typeFilters.excludeTypes, options)); } if (before !== undefined && before <= POSTGRES_INT_MAX) { filters.push(lt(schema.sessionEvents.sequence, before)); } const rows = await scopedDb .select( sessionEventProjectionSelect(options.payloadMode ?? "full", schema.sessionEvents, { toolOutputPreview: (options.payloadMode ?? "full") === "full" && options.toolOutputPreview, }), ) .from(schema.sessionEvents) .where(and(...filters)) .orderBy( direction === "before" ? desc(schema.sessionEvents.sequence) : asc(schema.sessionEvents.sequence), ) .limit(limit); return (direction === "before" ? rows.reverse() : rows).map(mapProjectedEvent); }); } /** * The recorded model responses of a session (optionally one turn, one attempt * or a recent window) whose deferred ledger writes have not finished, in * session order. A response's usage event (or, for a fenced attempt, its * `turn.event.rejected_late` audit row) records the settlement's charges and * the idempotency key of its last ledger write (`completionKey`); a response * is owed while no usage or credit ledger row has that key. One query; a * settled response costs one index probe per table and no write. * * The candidates, with their completion keys, are a materialized CTE so the * ledger anti-joins compare two plain text columns. Under row-level security * PostgreSQL uses a join clause as an index condition only when it is * leakproof, and the JSON operators that read the key out of the payload are * not: written in the anti-join itself, they turned each probe into a scan of * every usage row the tenant can see, with its row policy, per event. Every * idle, failure and worker-death boundary and every attempt's first model * request runs this read, so its cost must follow the session's own responses, * never the size of the ledger. */ export async function listOwedModelUsageSettlements( db: Database, workspaceId: string, input: { sessionId: string; turnId?: string; attemptId?: string; since?: Date }, ): Promise< Array<{ id: string; accountId: string; turnId: string | null; turnAttemptId: string | null; /** A fenced attempt's `turn.event.rejected_late` audit row. */ rejected: boolean; /** The usage event's payload (unwrapped from a rejected audit row). */ payload: unknown; }> > { const events = schema.sessionEvents; const usagePayload = sql`(case when ${events.type} = 'agent.model.usage' then ${events.payload} else ${events.payload} -> 'rejectedPayload' end)`; const completionKey = sql`(${usagePayload} -> 'settlement' -> 'charges' ->> 'completionKey')`; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const filters: SQL[] = [ eq(events.workspaceId, workspaceId), eq(events.sessionId, input.sessionId), or( and(eq(events.type, "agent.model.usage"), eq(events.turnAssociation, "current")), and( eq(events.type, "turn.event.rejected_late"), sql`${events.payload} ->> 'rejectedType' = 'agent.model.usage'`, ), )!, sql`${completionKey} is not null`, ]; if (input.turnId) filters.push(eq(events.turnId, input.turnId)); if (input.attemptId) filters.push(eq(events.turnAttemptId, input.attemptId)); if (input.since) filters.push(gte(events.createdAt, input.since)); const rows = await rawRows<{ id: string; accountId: string; turnId: string | null; turnAttemptId: string | null; rejected: boolean; payload: unknown; payloadCodecVersion: number | null; }>( scopedDb, sql`with candidates as materialized ( select ${events.id} as id, ${events.accountId} as account_id, ${events.turnId} as turn_id, ${events.turnAttemptId} as turn_attempt_id, ${events.sequence} as sequence, (${events.type} <> 'agent.model.usage') as rejected, ${usagePayload} as payload, ${events.payloadCodecVersion} as payload_codec_version, ${completionKey} as completion_key from ${events} where ${and(...filters)} ) select candidates.id::text as "id", candidates.account_id::text as "accountId", candidates.turn_id::text as "turnId", candidates.turn_attempt_id::text as "turnAttemptId", candidates.rejected as "rejected", candidates.payload as "payload", candidates.payload_codec_version as "payloadCodecVersion" from candidates where not exists ( select 1 from ${schema.usageEvents} where ${schema.usageEvents.idempotencyKey} = candidates.completion_key ) and not exists ( select 1 from ${schema.creditLedgerEntries} where ${schema.creditLedgerEntries.idempotencyKey} = candidates.completion_key ) order by candidates.sequence`, ); // The payload is read through SQL, so restore the logical values here: a // source key the codec stored encoded must reach settlement as the // original key, or its receipt identity is encoded a second time. const decoded = rows.map(({ payloadCodecVersion, ...row }) => ({ ...row, payload: fromPostgresLosslessJson(row.payload, payloadCodecVersion), })); // Such a key's completion key is encoded in the payload but written to the // ledger as given, so the anti-join above cannot see its ledger row. // Check those few keys as written. const encodedKeys = new Map<(typeof decoded)[number], string>(); for (const row of decoded) { const key = owedCompletionKey(row.payload); if (key !== null && !isStoredVerbatimAsLosslessJsonString(key)) encodedKeys.set(row, key); } if (encodedKeys.size === 0) return decoded; const keys = [...new Set(encodedKeys.values())]; const settled = new Set( [ ...(await scopedDb .select({ key: schema.usageEvents.idempotencyKey }) .from(schema.usageEvents) .where(inArray(schema.usageEvents.idempotencyKey, keys))), ...(await scopedDb .select({ key: schema.creditLedgerEntries.idempotencyKey }) .from(schema.creditLedgerEntries) .where(inArray(schema.creditLedgerEntries.idempotencyKey, keys))), ].map((row) => row.key), ); if (settled.size === 0) return decoded; // Compare as the database stored both sides. const stored = (key: string) => Buffer.from(key, "utf8").toString("utf8"); const settledStored = new Set([...settled].map(stored)); return decoded.filter((row) => { const key = encodedKeys.get(row); return key === undefined || !settledStored.has(stored(key)); }); }); } function owedCompletionKey(payload: unknown): string | null { const settlement = (payload as { settlement?: { charges?: { completionKey?: unknown } } } | null) ?.settlement; const key = settlement?.charges?.completionKey; return typeof key === "string" ? key : null; } function normalizeEventSequence(value: number | undefined, fallback: number): number { if (value === undefined || !Number.isFinite(value)) { return fallback; } return Math.floor(value); } function normalizeEventLimit(value: number | undefined, fallback: number): number { if (value === undefined || !Number.isFinite(value)) { return fallback; } return Math.max(0, Math.floor(value)); } export async function getSessionEvent( db: Database, workspaceId: string, eventId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.id, eventId), ), ) .limit(1); return row ? mapEvent(row) : null; }); } /** * Trusted Site lifecycle only: cancel an exact published root using native * controls. No request/agent endpoint exposes this adapter or its transaction. * The host has authorized the Site mutation; its actor stays unchanged. * Only the receipt and events written by this command leave the capability. */ export async function cancelSiteRuntimeConversation( db: Database, input: { accountId: string; workspaceId: string; siteId: string; sessionId: string; operationKey: string; reason: string; }, ) { // Own the complete transaction, including activity finalization. A nested // activity gate could otherwise outlive the exact-root visibility witness. if (isTransactionHandle(db)) throw new Error("App cancellation requires its own transaction"); return await runIdempotentPersistenceTransaction( { stage: "site_lifecycle.cancel", eventTypes: ["session.control.paused", "turn.cancelled"], maxAttempts: 3, }, () => withRlsContext(db, input, async (scopedDb) => { const [opened] = await rawRows<{ token: string | null }>( scopedDb, sql` select opengeni_private.begin_site_session_cancellation( ${input.accountId}::uuid,${input.workspaceId}::uuid,${input.siteId}::uuid,${input.sessionId}::uuid ) as token`, ); if (!opened?.token) return null; const value = await withRestoredSessionActivityRlsContext(scopedDb, input, async (tx) => { const [context] = await rawRows<{ actor: string | null }>( tx, sql` select nullif(current_setting('opengeni.subject_id',true),'') as actor`, ); // Serialize the active-state decision with native admission/control. // Replays still enter the native receipt path after terminal settlement. await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const [candidate] = await rawRows<{ needed: boolean }>( tx, sql` select exists(select 1 from sessions s where s.workspace_id=${input.workspaceId} and s.site_access_root_id=${input.sessionId}::uuid and s.status in ('queued','running','requires_action','recovering','waiting_capacity')) or exists(select 1 from session_command_receipts r where r.workspace_id=${input.workspaceId} and r.target_session_id=${input.sessionId}::uuid and r.operation_key=${input.operationKey} and r.actor_type='service' and r.actor_subject_id=${context?.actor ?? "site-lifecycle"}) as needed`, ); if (!candidate?.needed) return null; const result = await mutateSessionControlInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, actor: { type: "service", subjectId: context?.actor ?? "site-lifecycle" }, operationKey: input.operationKey, action: "cancel", reason: input.reason, }); const events: SessionEvent[] = []; for (const affected of result.affectedSessionEvents) { for (const eventId of affected.eventIds) { const event = await getSessionEvent(tx, input.workspaceId, eventId); if (!event || event.sessionId !== affected.sessionId) throw new Error("App cancellation lost its committed event"); events.push(event); } } const workspaceEvent = result.workspaceControlEventId ? await getWorkspaceControlEvent(tx, input.workspaceId, result.workspaceControlEventId) : null; return { receiptId: result.receipt.id, replay: result.replay, cancelledSessionCount: result.cancelledSessionCount, cancelledTurnCount: result.cancelledTurnCount, wakeCount: result.wakeCount, events, workspaceEvent, }; }); // Also covers activity-revision stamping. On error the outer transaction // rolls the witness back, without masking the original SQL diagnostic. await scopedDb.execute( sql`select opengeni_private.end_site_session_cancellation(${opened.token}::uuid)`, ); return value; }), ); } /** Read one durable event under the exact human subject visibility projection. */ export async function getSessionEventForSubject( db: Database, workspaceId: string, subjectId: string, eventId: string, ): Promise { return await withWorkspaceSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.id, eventId), ), ) .limit(1); return row ? mapEvent(row) : null; }); } function mapWorkspaceControlEvent( row: typeof schema.workspaceControlEvents.$inferSelect, ): WorkspaceControlEvent { const revision = Number(row.revision); return boundWorkspaceControlEvent( { id: row.id, workspaceId: row.workspaceId, sequence: revision, revision, type: "workspace.control.changed", scope: row.scope as WorkspaceControlEvent["scope"], rootSessionId: row.rootSessionId, action: row.action as WorkspaceControlEvent["action"], automatic: row.automatic, reason: row.reason, actor: row.actor, occurredAt: row.occurredAt.toISOString(), }, { surface: "durable_control", // Untouched bounded rows from before migration 0068 intentionally retain // null metadata. Their delivered bytes are the exact original facts. reasonOriginalBytes: row.reason === null ? null : (row.reasonOriginalBytes ?? workspaceControlUtf8Bytes(row.reason)), actorOriginalBytes: row.actorOriginalBytes ?? workspaceControlUtf8Bytes(row.actor), }, ); } export async function listWorkspaceControlEvents( db: Database, workspaceId: string, after = 0, limit = 500, ): Promise { const cursor = normalizeEventSequence(after, 0); const boundedLimit = Math.min(1000, normalizeEventLimit(limit, 500)); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.workspaceControlEvents) .where( and( eq(schema.workspaceControlEvents.workspaceId, workspaceId), gt(schema.workspaceControlEvents.revision, cursor), ), ) .orderBy(asc(schema.workspaceControlEvents.revision)) .limit(boundedLimit); return rows.map(mapWorkspaceControlEvent); }); } export async function getWorkspaceControlEvent( db: Database, workspaceId: string, eventId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.workspaceControlEvents) .where( and( eq(schema.workspaceControlEvents.workspaceId, workspaceId), eq(schema.workspaceControlEvents.id, eventId), ), ) .limit(1); return row ? mapWorkspaceControlEvent(row) : null; }); } /** * Resolve a client-idempotent event inside one exact workspace/session scope. * The three predicates are deliberate: a client event id is unique only within * a session, while the workspace predicate remains the tenancy boundary. */ export async function getSessionEventByClientEventId( db: Database, workspaceId: string, sessionId: string, clientEventId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.clientEventId, clientEventId), ), ) .limit(1); return row ? mapEvent(row) : null; }); } /** * Resolve the visible creation event for one exact tool operation. This is a * rolling-upgrade compatibility lookup for producers that predate deterministic * client event ids; the operation id remains bound to the same turn attempt. */ export async function getSessionToolCallCreatedEventByOperationId( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; operationId: string; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.turnAttemptId, input.attemptId), eq(schema.sessionEvents.turnAssociation, "current"), eq(schema.sessionEvents.type, "agent.toolCall.created"), eq(sql`${schema.sessionEvents.payload} ->> 'id'`, input.operationId), ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); return row ? mapEvent(row) : null; }); } export const APPROVAL_RUN_STATE_MAX_JSON_BYTES = 3 * 1024 * 1024; export const APPROVAL_RUN_STATE_MAX_JSON_NODES = 65_536; export const APPROVAL_RUN_STATE_MAX_JSON_PROPERTIES = 32_768; export const APPROVAL_PENDING_MAX_JSON_BYTES = 256 * 1024; export const APPROVAL_PENDING_MAX_ITEMS = 256; export type ApprovalRunStateMaterializationLimits = { maximumJsonBytes: number; maximumJsonNodes: number; maximumJsonProperties: number; maximumPendingApprovalBytes: number; maximumPendingApprovalItems: number; }; export type ApprovalRunStateLimitKind = | "json_bytes" | "json_nodes" | "json_properties" | "invalid_json" | "pending_approval_bytes" | "pending_approval_items"; export class ApprovalRunStateLimitExceededError extends Error { readonly code = "approval_run_state_too_large"; constructor( readonly limitKind: ApprovalRunStateLimitKind, readonly actual: number, readonly maximum: number, ) { super(approvalRunStateLimitMessage(limitKind, actual, maximum)); this.name = "ApprovalRunStateLimitExceededError"; } } function approvalRunStateLimitMessage( kind: ApprovalRunStateLimitKind, actual: number, maximum: number, ): string { if (kind === "invalid_json") return "Approval run state is not a valid serialized JSON object."; const label = kind === "json_bytes" ? "UTF-8 JSON bytes" : kind === "json_nodes" ? "decoded JSON nodes" : kind === "json_properties" ? "decoded JSON object properties" : kind === "pending_approval_bytes" ? "pending-approval JSON bytes" : "pending approval items"; return `Approval run state has ${actual} ${label}; the materialization limit is ${maximum}.`; } const DEFAULT_APPROVAL_RUN_STATE_LIMITS: ApprovalRunStateMaterializationLimits = { maximumJsonBytes: APPROVAL_RUN_STATE_MAX_JSON_BYTES, maximumJsonNodes: APPROVAL_RUN_STATE_MAX_JSON_NODES, maximumJsonProperties: APPROVAL_RUN_STATE_MAX_JSON_PROPERTIES, maximumPendingApprovalBytes: APPROVAL_PENDING_MAX_JSON_BYTES, maximumPendingApprovalItems: APPROVAL_PENDING_MAX_ITEMS, }; type ApprovalRunStateMeasurement = { actualBytes: number; validJsonObject: boolean; actualNodes: number; actualProperties: number; pendingApprovalBytes: number; pendingApprovalItems: number; }; function approvalRunStateLimits( overrides: Partial, ): ApprovalRunStateMaterializationLimits { const limits = { ...DEFAULT_APPROVAL_RUN_STATE_LIMITS, ...overrides }; for (const [name, value] of Object.entries(limits)) { if (!Number.isSafeInteger(value) || value < 1) { throw new Error(`${name} must be a positive safe integer`); } } return limits; } function safeEnvelopeInteger(value: string, label: string): number { const parsed = Number(value); if (!Number.isSafeInteger(parsed) || parsed < 0) { throw new Error(`${label} is not a non-negative safe integer: ${String(value)}`); } return parsed; } function approvalRunStateMeasurementViolation( measured: ApprovalRunStateMeasurement, limits: ApprovalRunStateMaterializationLimits, ): ApprovalRunStateLimitExceededError | null { if (measured.actualBytes > limits.maximumJsonBytes) { return new ApprovalRunStateLimitExceededError( "json_bytes", measured.actualBytes, limits.maximumJsonBytes, ); } if (!measured.validJsonObject) { return new ApprovalRunStateLimitExceededError("invalid_json", 1, 0); } if (measured.actualNodes > limits.maximumJsonNodes) { return new ApprovalRunStateLimitExceededError( "json_nodes", measured.actualNodes, limits.maximumJsonNodes, ); } if (measured.actualProperties > limits.maximumJsonProperties) { return new ApprovalRunStateLimitExceededError( "json_properties", measured.actualProperties, limits.maximumJsonProperties, ); } if (measured.pendingApprovalBytes > limits.maximumPendingApprovalBytes) { return new ApprovalRunStateLimitExceededError( "pending_approval_bytes", measured.pendingApprovalBytes, limits.maximumPendingApprovalBytes, ); } if (measured.pendingApprovalItems > limits.maximumPendingApprovalItems) { return new ApprovalRunStateLimitExceededError( "pending_approval_items", measured.pendingApprovalItems, limits.maximumPendingApprovalItems, ); } return null; } function assertApprovalRunStateMeasurement( measured: ApprovalRunStateMeasurement, limits: ApprovalRunStateMaterializationLimits, ): void { const violation = approvalRunStateMeasurementViolation(measured, limits); if (violation) throw violation; } /** * Validate and count RunState text in-process (linear, no decoding). Counts are * reported as at most limit + 1, the bounded measurement callers already see. */ function boundedApprovalRunStateTextMeasurement( serializedRunState: string, actualBytes: number, limits: ApprovalRunStateMaterializationLimits, ): Pick< ApprovalRunStateMeasurement, "actualBytes" | "validJsonObject" | "actualNodes" | "actualProperties" > { const measured = measureJsonObjectText(serializedRunState); return { actualBytes, validJsonObject: measured.validJsonObject, actualNodes: Math.min(measured.nodes, limits.maximumJsonNodes + 1), actualProperties: Math.min(measured.properties, limits.maximumJsonProperties + 1), }; } function approvalRunStateNullableDate(value: Date | string | null): Date | null { if (value === null) return null; const parsed = value instanceof Date ? value : new Date(value); if (Number.isNaN(parsed.getTime())) { throw new Error("Approval run state has a malformed provider artifact invalidation timestamp"); } return parsed; } /** * Read the one approval/human-input RunState through a bounded envelope: the * database withholds text over the byte bound, and the JSON shape of the rest * is measured in one linear pass before anything decodes it. * Ordinary turns never call this path; they use canonical history items only. */ export async function getLatestRunState( db: Database, workspaceId: string, sessionId: string, limitOverrides: Partial = {}, ): Promise<{ id: string; turnId: string | null; serializedRunState: string; pendingApprovals: unknown[]; providerArtifactInvalidatedAt: Date | null; } | null> { const limits = approvalRunStateLimits(limitOverrides); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ id: string; turn_id: string | null; serialized_run_state: string | null; serialized_run_state_codec_version: number | null; pending_approvals: unknown[] | null; pending_approvals_codec_version: number | null; provider_artifact_invalidated_at: Date | string | null; actual_bytes: string; pending_approval_bytes: string; pending_approval_items: string; }>( scopedDb, sql` with latest as materialized ( select id, turn_id, serialized_run_state, serialized_run_state_codec_version, pending_approvals, pending_approvals_codec_version, provider_artifact_invalidated_at, state_version, created_at from agent_run_states where workspace_id = ${workspaceId} and session_id = ${sessionId} order by created_at desc, state_version desc limit 1 ), measured as materialized ( select latest.*, octet_length(serialized_run_state)::bigint as actual_bytes, octet_length(pending_approvals::text)::bigint as pending_approval_bytes, case when jsonb_typeof(pending_approvals) = 'array' then jsonb_array_length(pending_approvals)::bigint else ${limits.maximumPendingApprovalItems + 1}::bigint end as pending_approval_items from latest ) select id, turn_id, case when actual_bytes <= ${limits.maximumJsonBytes} then serialized_run_state else null end as serialized_run_state, case when pending_approval_bytes <= ${limits.maximumPendingApprovalBytes} and pending_approval_items <= ${limits.maximumPendingApprovalItems} then pending_approvals else null end as pending_approvals, serialized_run_state_codec_version, pending_approvals_codec_version, provider_artifact_invalidated_at, actual_bytes::text as actual_bytes, pending_approval_bytes::text as pending_approval_bytes, pending_approval_items::text as pending_approval_items from measured `, ); if (!row) return null; // Only text within the byte bound leaves the database. Its JSON shape is // measured here in one linear pass, before anything decodes it. const actualBytes = safeEnvelopeInteger(row.actual_bytes, "approval run-state bytes"); assertApprovalRunStateMeasurement( { ...(row.serialized_run_state === null ? { actualBytes, validJsonObject: false, actualNodes: 0, actualProperties: 0 } : boundedApprovalRunStateTextMeasurement(row.serialized_run_state, actualBytes, limits)), pendingApprovalBytes: safeEnvelopeInteger( row.pending_approval_bytes, "pending-approval JSON bytes", ), pendingApprovalItems: safeEnvelopeInteger( row.pending_approval_items, "pending approval items", ), }, limits, ); if (row.serialized_run_state === null || row.pending_approvals === null) { throw new Error("Approval run-state envelope passed without materialized bounded values"); } return { id: row.id, turnId: row.turn_id ?? null, serializedRunState: fromPostgresLosslessText( row.serialized_run_state, row.serialized_run_state_codec_version, ), pendingApprovals: fromPostgresLosslessJson( row.pending_approvals, row.pending_approvals_codec_version, ), providerArtifactInvalidatedAt: approvalRunStateNullableDate( row.provider_artifact_invalidated_at, ), }; }); } export class HumanInputResponseValidationError extends Error { readonly name = "HumanInputResponseValidationError"; constructor( readonly code: "INVALID_RESPONSE" | "SKIP_NOT_ALLOWED" | "HUMAN_AUTH_REQUIRED", message: string, ) { super(message); } } function mapSessionHumanInputRequest( row: typeof schema.sessionHumanInputRequests.$inferSelect, ): SessionHumanInputRequest { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, turnId: row.turnId, turnGeneration: row.turnGeneration, creationAttemptId: row.creationAttemptId, toolCallId: row.toolCallId, origin: row.origin === "secret_use_approval" ? "secret_use_approval" : "tool_call", status: row.status as SessionHumanInputRequest["status"], questions: row.questions, allowSkip: row.allowSkip, response: row.response ?? null, respondedBy: row.respondedBy ?? null, respondedAt: row.respondedAt?.toISOString() ?? null, expiresAt: row.expiresAt?.toISOString() ?? null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } export async function getSessionHumanInputRequest( db: Database, workspaceId: string, sessionId: string, requestId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, sessionId), eq(schema.sessionHumanInputRequests.id, requestId), ), ) .limit(1); return row ? mapSessionHumanInputRequest(row) : null; }); } export async function listSessionHumanInputRequests( db: Database, workspaceId: string, sessionId: string, options: { status?: SessionHumanInputRequest["status"]; limit?: number } = {}, ): Promise { const limit = Math.min(100, Math.max(1, Math.floor(options.limit ?? 50))); return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const actionablePendingIds = options.status === "pending" ? await scopedDb.execute<{ id: string }>(sql` select actionable.id from ( select request_row.id, request_row.created_at from session_human_input_requests request_row join sessions session_row on session_row.workspace_id = request_row.workspace_id and session_row.id = request_row.session_id join session_turns turn_row on turn_row.workspace_id = request_row.workspace_id and turn_row.session_id = request_row.session_id and turn_row.id = request_row.turn_id join session_events trigger_row on trigger_row.workspace_id = turn_row.workspace_id and trigger_row.session_id = turn_row.session_id and trigger_row.id = turn_row.trigger_event_id where request_row.workspace_id = ${workspaceId} and request_row.session_id = ${sessionId} and request_row.status = 'pending' and request_row.origin = 'tool_call' and (request_row.expires_at is null or request_row.expires_at > now()) and session_row.status = 'requires_action' and session_row.active_turn_id = request_row.turn_id and turn_row.status = 'requires_action' and turn_row.execution_generation = request_row.turn_generation and not exists ( select 1 from session_events accepted_row where accepted_row.workspace_id = request_row.workspace_id and accepted_row.session_id = request_row.session_id and accepted_row.turn_id = request_row.turn_id and accepted_row.turn_generation = request_row.turn_generation and accepted_row.type in ('user.approvalDecision', 'user.humanInputResponse') and accepted_row.sequence > trigger_row.sequence ) union all -- Opengeni's own approval cards wait on no turn: pending is actionable. select request_row.id, request_row.created_at from session_human_input_requests request_row where request_row.workspace_id = ${workspaceId} and request_row.session_id = ${sessionId} and request_row.status = 'pending' and request_row.origin = 'secret_use_approval' ) actionable order by actionable.created_at desc, actionable.id desc limit ${limit} `) : null; if (actionablePendingIds !== null && actionablePendingIds.length === 0) return []; const predicates = [ eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, sessionId), ]; if (options.status) { predicates.push(eq(schema.sessionHumanInputRequests.status, options.status)); } if (actionablePendingIds !== null) { predicates.push( inArray( schema.sessionHumanInputRequests.id, actionablePendingIds.map((row: { id: string }) => row.id), ), ); } const rows = await scopedDb .select() .from(schema.sessionHumanInputRequests) .where(and(...predicates)) .orderBy( desc(schema.sessionHumanInputRequests.createdAt), desc(schema.sessionHumanInputRequests.id), ) .limit(limit); return rows.map(mapSessionHumanInputRequest); }); } function validateAnsweredHumanInput( questions: HumanInputQuestion[], submittedAnswers: HumanInputAnswer[], secretAnswerQuestionIds: ReadonlySet = new Set(), ): HumanInputAnswer[] { const questionsById = new Map(questions.map((question) => [question.id, question])); for (const questionId of secretAnswerQuestionIds) { if (questionsById.get(questionId)?.kind !== "secret") { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `A secret answer was sent for ${questionId}, which is not a secret question`, ); } } // `secret` on an answer is server-written (the saved reference); a client // never supplies it. A secret answered by value may omit its answer entry. const answers = submittedAnswers.map(({ secret: _serverOwned, ...answer }) => answer); for (const questionId of secretAnswerQuestionIds) { if (!answers.some((answer) => answer.questionId === questionId)) { answers.push({ questionId, values: [] }); } } const answersById = new Map(); for (const answer of answers) { if (!questionsById.has(answer.questionId)) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Unknown human-input question: ${answer.questionId}`, ); } if (answersById.has(answer.questionId)) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Duplicate human-input answer: ${answer.questionId}`, ); } answersById.set(answer.questionId, answer); } for (const question of questions) { const answer = answersById.get(question.id); const values = answer?.values ?? []; const other = answer?.other?.trim() ?? ""; const answeredByValue = secretAnswerQuestionIds.has(question.id); const suppliedCount = values.length + (other ? 1 : 0) + (answeredByValue ? 1 : 0); if (question.required && suppliedCount === 0) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Question ${question.id} requires an answer`, ); } if (!answer) continue; if (new Set(values).size !== values.length) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Question ${question.id} contains duplicate values`, ); } if (question.kind === "secret") { validateSecretHumanInputAnswer(question.id, values, other, answeredByValue); continue; } if (question.kind === "text") { if (values.length > 1 || other) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Text question ${question.id} accepts one value`, ); } // Text answers have no agent-chosen char bounds — only the platform // string cap on HumanInputAnswer.values. Ignore legacy minLength/maxLength // still present on older persisted question JSON. continue; } const optionIds = new Set(question.options.map((option) => option.id)); if (values.some((value) => !optionIds.has(value))) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Question ${question.id} contains an unknown option`, ); } if (question.kind === "single_select" && suppliedCount > 1) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Single-select question ${question.id} accepts one selection`, ); } if (question.kind === "multi_select") { const minSelections = question.validation?.minSelections; const maxSelections = question.validation?.maxSelections; if (minSelections != null && suppliedCount < minSelections) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Question ${question.id} has too few selections`, ); } if (maxSelections != null && suppliedCount > maxSelections) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Question ${question.id} has too many selections`, ); } } } return answers; } /** * A secret question is answered either by a value the API already moved into * `secretAnswers` (values stay empty here) or, for agents and API callers * relaying an existing secret, by exactly one secret reference (AC-7). */ function validateSecretHumanInputAnswer( questionId: string, values: string[], other: string, answeredByValue: boolean, ): void { if (other) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Secret question ${questionId} does not take free text`, ); } if (answeredByValue) { if (values.length > 0) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Secret question ${questionId} was answered twice`, ); } return; } if (values.length === 0) return; let reference: SecretReference | null = null; if (values.length === 1) { try { reference = parseSecretReference(values[0]!.trim()); } catch { reference = null; } } if (!reference || reference.kind !== "secret") { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", `Secret question ${questionId} accepts a secret value through secretAnswers or one {{secret:...}} reference, never a plain value`, ); } } /** * "Let the agent decide" may settle an agent's own question, but never a * secret question, a Skill review or a secret-use approval card: those stay * with the person. */ export function humanInputAgentMayDecide( request: Pick & Partial>, ): boolean { if ((request.origin ?? "tool_call") !== "tool_call") return false; return request.questions.every( (question) => question.kind !== "secret" && question.secret == null && question.skillReview == null && secretUseApprovalIdFromQuestionId(question.id) === null, ); } export function validateHumanInputResponse( request: Pick & Partial>, rawResponse: unknown, secretAnswerQuestionIds: ReadonlySet = new Set(), ): HumanInputResponse { const response = SubmitHumanInputResponseRequest.parse(rawResponse); if (response.outcome === "answered" && response.secretAnswers?.length) { // Values travel only through the caller's prepared, encrypted answers. throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "secretAnswers must be submitted separately from the stored response", ); } if (response.outcome === "skipped") { if (response.agentDecides) { if (!humanInputAgentMayDecide(request)) { throw new HumanInputResponseValidationError( "SKIP_NOT_ALLOWED", "Only the person can answer this request", ); } return { outcome: "skipped", agentDecides: true }; } if (!request.allowSkip) { throw new HumanInputResponseValidationError( "SKIP_NOT_ALLOWED", "This human-input request cannot be skipped", ); } return response; } return { outcome: "answered", answers: validateAnsweredHumanInput( request.questions, response.answers, secretAnswerQuestionIds, ), }; } export type AcceptSessionHumanInputResponseResult = | { action: "accepted"; request: SessionHumanInputRequest; event: SessionEvent; events: SessionEvent[]; /** Null when no wake was needed (an approval card answered while its chat is busy). */ workflowWakeRevision: number | null; } | { action: "completed"; request: SessionHumanInputRequest; event: SessionEvent; events: SessionEvent[]; workflowWakeRevision: number | null; /** * `same_submission`: this exact submission (its clientEventId) already * committed and is replayed. `earlier_response`: another response, an * expiry or a cancellation settled the request first; this submission * was not used. */ settledBy: "same_submission" | "earlier_response"; } | { action: "conflict"; request: SessionHumanInputRequest; events: SessionEvent[]; workflowWakeRevision: number | null; } | { action: "not_found" }; /** * One requires-action boundary admits one question answer: only the trigger * carries an answer into the resume. Approval decisions never block it; the * peek resumes from the answer first, and that resume applies every approval * decision of the pause recorded before it. */ async function hasAcceptedRequiresActionAdvance( tx: Database, input: { workspaceId: string; sessionId: string; turnId: string; turnGeneration: number; triggerEventId: string; }, ): Promise { const [trigger] = await tx .select({ sequence: schema.sessionEvents.sequence }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.id, input.triggerEventId), ), ) .limit(1); if (!trigger) throw new Error(`Turn trigger not found: ${input.triggerEventId}`); const [accepted] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.turnGeneration, input.turnGeneration), eq(schema.sessionEvents.type, "user.humanInputResponse"), gt(schema.sessionEvents.sequence, trigger.sequence), ), ) .limit(1); return accepted !== undefined; } /** One approval's identity for one question round; rounds only for MCP questions. */ function approvalDecisionKey(approvalId: string | null, round: number | undefined): string { return `${approvalId ?? ""}\u0000${round ?? ""}`; } /** A recorded approval decision: the call it decides and the decision payload. */ export type TurnApprovalDecision = { eventId: string; sequence: number; approvalId: string; /** The question round it answers or declined; none for an approval without one. */ elicitationRound?: number; payload: Record; }; async function turnApprovalDecisionsTx( tx: Database, input: { workspaceId: string; sessionId: string; turnId: string; afterSequence?: number; throughSequence?: number; }, ): Promise { const rows = await tx .select({ id: schema.sessionEvents.id, sequence: schema.sessionEvents.sequence, payload: schema.sessionEvents.payload, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "user.approvalDecision"), eq(schema.sessionEvents.turnId, input.turnId), ...(input.afterSequence !== undefined ? [gt(schema.sessionEvents.sequence, input.afterSequence)] : []), ...(input.throughSequence !== undefined ? [lte(schema.sessionEvents.sequence, input.throughSequence)] : []), ), ) .orderBy(asc(schema.sessionEvents.sequence)); return rows.flatMap((row) => { const payload = sessionEventPayloadRecord(row.payload, row.payloadCodecVersion); if (typeof payload.approvalId !== "string") return []; const round = approvalDecisionRound(payload); return [ { eventId: row.id, sequence: row.sequence, approvalId: payload.approvalId, ...(round !== undefined ? { elicitationRound: round } : {}), payload, }, ]; }); } /** Keys of the approvals decided after the attempt's trigger: the next resume applies them. */ async function approvalDecisionsAfterTriggerTx( tx: Database, input: { workspaceId: string; sessionId: string; turnId: string; triggerEventId: string }, ): Promise> { const [trigger] = await tx .select({ sequence: schema.sessionEvents.sequence }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.id, input.triggerEventId), ), ) .limit(1); if (!trigger) return new Set(); const decisions = await turnApprovalDecisionsTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, afterSequence: trigger.sequence, }); return new Set( decisions.map((decision) => approvalDecisionKey(decision.approvalId, decision.elicitationRound), ), ); } /** * The approval decisions a resume applies besides its own trigger: every * decision of the turn recorded up to the trigger, oldest first. A pause's * decisions are applied together; one recorded later resumes the turn again. */ export async function listTurnApprovalDecisions( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; throughSequence: number }, ): Promise { return await withWorkspaceRls( db, input.workspaceId, async (scopedDb) => await turnApprovalDecisionsTx(scopedDb, input), ); } async function humanInputResponseEventForRequest( tx: Database, input: { workspaceId: string; sessionId: string; requestId: string; }, ): Promise { const [event] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "user.humanInputResponse"), sql`${schema.sessionEvents.payload} ->> 'requestId' = ${input.requestId}`, ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); return event ? mapEvent(event) : null; } type AcceptSessionHumanInputResponseInput = Parameters[1]; async function humanInputRequestIsSecretUseApprovalCard( db: Database, input: Pick, ): Promise { if (!UUID_PATTERN.test(input.requestId)) return false; return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ origin: schema.sessionHumanInputRequests.origin }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.id, input.requestId), ), ) .limit(1); return row?.origin === "secret_use_approval"; }); } /** Unwinds the answer transaction when another answer settled the card first. */ class SecretUseApprovalCardSettledError extends Error { constructor() { super("The approval card was already answered"); } } /** * Answer one of Opengeni's own secret approval cards. Only the person the * blocked run acted for, signed in to Opengeni themselves, may answer, with * one of the card's choices. In one transaction the card is answered, the * request becomes a grant (or a denial), and the agent gets a * `secret_use_approval_decided` input that wakes an idle chat. The turn that * was blocked is never resumed: nothing ran, so the agent retries the call. */ /** The session's current receiving context turn, when it has one. */ async function sessionExecutionContextTurnTx( tx: Database, input: { workspaceId: string; sessionId: string }, ) { const [session] = await tx .select({ executionContextTurnId: schema.sessions.executionContextTurnId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session?.executionContextTurnId) return null; const [context] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, session.executionContextTurnId), ), ) .limit(1); return context ?? null; } async function acceptSecretUseApprovalCardResponse( db: Database, input: AcceptSessionHumanInputResponseInput, ): Promise { const loaded = await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [request] = await scopedDb .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.id, input.requestId), ), ) .limit(1); if (!request) return null; const approvalId = secretUseApprovalIdFromQuestionId(request.toolCallId); const approvals = approvalId ? await secretUseApprovalsForSessionTx(scopedDb, { workspaceId: input.workspaceId, sessionId: input.sessionId, ids: [approvalId], }) : new Map(); const sameSubmission = input.clientEventId ? ( await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.clientEventId, input.clientEventId), ), ) .limit(1) )[0] : undefined; const answer = request.status === "pending" ? null : await humanInputResponseEventForRequest(scopedDb, { workspaceId: input.workspaceId, sessionId: input.sessionId, requestId: request.id, }); return { request, approval: approvalId ? (approvals.get(approvalId) ?? null) : null, sameSubmission, answer, context: request.status === "pending" ? await sessionExecutionContextTurnTx(scopedDb, input) : null, }; }); if (!loaded) return { action: "not_found" }; const { request, approval } = loaded; const settled = async (): Promise => { const current = await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.id, input.requestId), ), ) .limit(1); const event = row ? await humanInputResponseEventForRequest(scopedDb, { workspaceId: input.workspaceId, sessionId: input.sessionId, requestId: row.id, }) : null; return row ? { row, event } : null; }); if (!current) return { action: "not_found" }; const mapped = mapSessionHumanInputRequest(current.row); if (!current.event) { return { action: "conflict", request: mapped, events: [], workflowWakeRevision: null }; } return { action: "completed", request: mapped, event: current.event, events: [], workflowWakeRevision: null, settledBy: input.clientEventId && current.event.clientEventId === input.clientEventId ? "same_submission" : "earlier_response", }; }; if (loaded.sameSubmission) { if ( loaded.sameSubmission.type !== "user.humanInputResponse" || (loaded.sameSubmission.payload as { requestId?: unknown }).requestId !== request.id ) { throw new Error("clientEventId belongs to a different session operation"); } return await settled(); } if (request.status !== "pending") return await settled(); const mappedRequest = mapSessionHumanInputRequest(request); // The card has no deadline, so there is nothing to expire. if (input.expireOnly) { return { action: "conflict", request: mappedRequest, events: [], workflowWakeRevision: null }; } if ((input.secretAnswers?.length ?? 0) > 0) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "An approval card takes no secret answers.", ); } const response = validateHumanInputResponse(mappedRequest, input.response); const question = request.questions[0]; const answer = response.outcome === "answered" && question ? response.answers.find((candidate) => candidate.questionId === question.id) : undefined; const decision = answer?.values[0]; if ( !answer || answer.values.length !== 1 || Boolean(answer.other?.trim()) || !(SECRET_USE_APPROVAL_DECISIONS as readonly string[]).includes(decision ?? "") ) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "Choose one of the card's options to allow or deny this secret.", ); } const responderKind = childRequiresActionRespondedByKindFor( input.respondedBy, input.respondedByKind, ); if ( responderKind !== "human" || input.personSignedIn !== true || !approval || input.respondedBy !== approval.approverSubjectId ) { throw new HumanInputResponseValidationError( "HUMAN_AUTH_REQUIRED", "Only the person this agent works for can allow it to use this secret, signed in to Opengeni themselves.", ); } const chosen = decision as SecretUseApprovalDecision; const view = secretUseApprovalView(approval); // The answer stands in for the person's own "go ahead": like a goal // continuation it runs in their receiving context, so the agent resumes // with their vaults and accounts. Someone else's context gives it no // authority, and the claim re-checks the context it finds then. const context = loaded.context; const receivingAuthority = (() => { if (!context || turnHuman(context) !== approval.approverSubjectId) { return {}; } const human = approval.approverSubjectId; const personalConnectionDelegations = parsedPersonalConnectionDelegations( context.personalConnectionDelegations, `session_turns:${input.workspaceId}:${input.sessionId}:${context.id}`, ); const xaiProviderAccountAuthoritySnapshot = XaiProviderAccountAuthoritySnapshotV1.parse( context.xaiProviderAccountAuthoritySnapshot, ); const claudeProviderAccountAuthoritySnapshot = ClaudeProviderAccountAuthoritySnapshotV1.parse( context.claudeProviderAccountAuthoritySnapshot, ); return { lineage: { causalTurnId: context.id, ...(personalConnectionDelegations.length > 0 ? { connectionAuthoritySubjectId: human } : {}), ...(xaiProviderAccountAuthoritySnapshot.scope === "user" ? { xaiAuthoritySubjectId: human } : {}), ...(claudeProviderAccountAuthoritySnapshot.scope === "user" ? { claudeAuthoritySubjectId: human } : {}), }, personalConnectionDelegations, mcpAccountBindings: parseAcceptedMcpAccountBindings(context.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot, }; })(); const answered: { event?: SessionEvent; request?: SessionHumanInputRequest } = {}; try { const result = await withWorkspaceSessionActivityRls(db, input.workspaceId, (scopedDb) => addSessionSystemUpdateWithSourceMutation( scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: "secret_use_approval_decided", classification: chosen === "deny" ? "info" : "action_required", sourceId: approval.id, dedupeKey: `secret-use-approval-decided:${approval.id}`, summary: secretUseApprovalDecisionSummary(view, chosen), payload: { type: "secret_use_approval_decided", approvalId: approval.id, requestId: request.id, decision: chosen, secrets: view.targets .slice(0, 20) .map((target) => (target.fieldName ? `${target.itemName} › ${target.fieldName}` : target.itemName ).slice(0, 512), ), surface: view.surface.slice(0, 64), toolName: view.toolName.slice(0, 200), destination: view.destination?.slice(0, 500) ?? null, }, ...receivingAuthority, }, async () => undefined, { prepareSource: async (tx, sessionId) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions[0]; if (!session) throw new Error("Failed to answer the approval card"); const [locked] = await tx .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, sessionId), eq(schema.sessionHumanInputRequests.id, request.id), ), ) .for("update") .limit(1); if (locked?.status !== "pending") throw new SecretUseApprovalCardSettledError(); const now = new Date(); const decided = await decideSecretUseApprovalTx(tx, { workspaceId: input.workspaceId, sessionId, approvalId: approval.id, decision: chosen, subjectId: input.respondedBy, now, }); if (!decided) throw new SecretUseApprovalCardSettledError(); const [updated] = await tx .update(schema.sessionHumanInputRequests) .set({ status: "answered", response, respondedBy: input.respondedBy, respondedAt: now, updatedAt: now, }) .where(eq(schema.sessionHumanInputRequests.id, request.id)) .returning(); if (!updated) throw new Error("Failed to answer the approval card"); // Turnless: the card belongs to no waiting turn, and the answer // must not read as a resume of the turn that was blocked. const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId, sequence: session.lastSequence + 1, type: "user.humanInputResponse", payload: { requestId: request.id, response, respondedByKind: responderKind }, clientEventId: input.clientEventId ?? null, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append the approval card's answer"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); answered.event = mapEvent(event); answered.request = mapSessionHumanInputRequest(updated); return { events: [answered.event] }; }, }, ), ); if (!("update" in result) || !answered.event || !answered.request) { // An archived or cancelled chat takes no more work. return { action: "conflict", request: mappedRequest, events: [], workflowWakeRevision: null, }; } return { action: "accepted", request: answered.request, event: answered.event, events: result.events, workflowWakeRevision: result.workflowWakeRevision, }; } catch (error) { if (error instanceof SecretUseApprovalCardSettledError) return await settled(); throw error; } } /** * First-writer-wins settlement for one structured input boundary. Session + * logical turn + current freeze generation are locked with the row; the * creation attempt is provenance and is intentionally not the resume owner. * A committed response replays its original event without another event or * workflow wake. Historical cancelled rows missing that canonical event are * repaired exactly once under the same locks, but never wake terminal work. */ export async function acceptSessionHumanInputResponse( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; requestId: string; response: unknown; respondedBy: string; /** API-owned sign-in proof for Skill review and existing native secret answers. */ canonicalHumanSession?: boolean; /** API-owned proof for saving a secret answer to Only me. Not a proof for any other card. */ privateSecretAnswerAuthorized?: boolean; /** * API-owned: the response comes from the person's own Opengeni sign-in * (browser, desktop or phone app), not an agent, personal key or * integration acting as them. Secret approval cards require it. */ personSignedIn?: boolean; /** Bounded responder kind for the parent's resolution notice; derived from `respondedBy` when omitted. */ respondedByKind?: ChildRequiresActionRespondedByKind; clientEventId?: string | null; expireOnly?: boolean; /** Validated/encrypted by the API; never copied into the response event. */ mcpCredentialUpdates?: UpdateSessionMcpServerCredentialsInput[]; /** * Secret ask-card answers, already generated and encrypted by the caller. * They are written to vaults in this transaction; the stored response and * event carry only the resulting references. */ secretAnswers?: readonly PreparedSecretAnswer[]; /** Whose authority writes `secretAnswers` (the responding person or attempt). */ secretWriteContext?: VaultDbContext; }, ): Promise { // Opengeni's own secret approval cards wait on no turn; their answer is a // grant plus a machine input for the agent. `origin` never changes. if (await humanInputRequestIsSecretUseApprovalCard(db, input)) { return await acceptSecretUseApprovalCardResponse(db, input); } const secretAnswers = input.expireOnly ? [] : (input.secretAnswers ?? []); const secretAnswerQuestionIds = new Set(secretAnswers.map((answer) => answer.questionId)); if (secretAnswerQuestionIds.size !== secretAnswers.length) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "Each secret question takes one secret answer", ); } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { // Skill activation shares the response transaction. Acquire its canonical // organization/workspace/publication prefix before any session row lock. // Questions are immutable after request creation; recheck below anyway. const [requestPreview] = await tx .select({ questions: schema.sessionHumanInputRequests.questions }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.id, input.requestId), ), ) .limit(1); const skillScopeLocked = requestPreview?.questions.some((question) => question.skillReview != null) ?? false; if (skillScopeLocked) { await tx.execute( sql`SELECT pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ); await tx.execute( sql`SELECT id FROM workspaces WHERE id=${input.workspaceId}::uuid AND account_id=${input.accountId}::uuid FOR KEY SHARE`, ); await lockSkillPublication(tx as unknown as Database, input.workspaceId); } // The parent (when notices are enabled) joins the same UUID-ordered // session lock so the resolution notice can be enqueued for it here. const sessionIds = await sessionIdsWithParentTx( tx as unknown as Database, input.workspaceId, input.sessionId, ); const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds, }); const session = locks.sessions.find((row) => row.id === input.sessionId); if (!session) return { action: "not_found" } as const; const [request] = await tx .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.id, input.requestId), ), ) .for("update") .limit(1); if (!request) return { action: "not_found" } as const; const hasSkillReview = request.questions.some((question) => question.skillReview != null); if (hasSkillReview && !skillScopeLocked) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "The review request changed. Reload before responding.", ); } if (hasSkillReview && !input.expireOnly && input.canonicalHumanSession !== true) { throw new HumanInputResponseValidationError( "HUMAN_AUTH_REQUIRED", "Skill approval requires a verified human browser session.", ); } if (input.clientEventId) { const [existing] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.clientEventId, input.clientEventId), ), ) .limit(1); if (existing) { if ( existing.type !== "user.humanInputResponse" || (existing.payload as { requestId?: unknown }).requestId !== request.id ) { throw new Error("clientEventId belongs to a different session operation"); } return { action: "completed", request: mapSessionHumanInputRequest(request), event: mapEvent(existing), events: [], workflowWakeRevision: null, settledBy: "same_submission", } as const; } } if (request.status !== "pending") { // A timeout that lost the first-writer race has nothing left to expire. // It does not acknowledge a human response or repair historical receipts. if (input.expireOnly) { return { action: "conflict", request: mapSessionHumanInputRequest(request), events: [], workflowWakeRevision: null, } as const; } let event = await humanInputResponseEventForRequest(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, requestId: request.id, }); let repairedEvents: SessionEvent[] = []; if ( !event && request.status === "cancelled" && (request.response as { outcome?: unknown } | null)?.outcome === "cancelled" ) { const turnLocks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [request.turnId], }); const turn = turnLocks.turns[0]; if (!turn || turn.sessionId !== session.id) { throw new SessionControlInvariantError( `Cancelled human-input request ${request.id} has no owning turn`, ); } const occurredAt = request.respondedAt ?? request.updatedAt; const [inserted] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: request.turnId, turnGeneration: request.turnGeneration, turnAssociation: "current", sequence: session.lastSequence + 1, type: "user.humanInputResponse", payload: { requestId: request.id, response: { outcome: "cancelled" }, }, clientEventId: null, occurredAt, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!inserted) { throw new SessionControlInvariantError( `Cancelled human-input request ${request.id} could not repair its response event`, ); } await mirrorSessionRealtimeContextInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sourceKind: "human_input_response", sourceId: inserted.id, turnId: request.turnId, channel: null, text: renderRealtimeHumanInputResponseContext({ requestId: request.id, questions: request.questions, response: { outcome: "cancelled" }, }), payload: { requestId: request.id, outcome: "cancelled", sourceEventId: inserted.id, }, now: occurredAt, }); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: new Date(), }) .where(eq(schema.sessions.id, session.id)); event = mapEvent(inserted); repairedEvents = [event]; } if (!event) { throw new Error(`Terminal human-input request has no response event: ${request.id}`); } return { action: "completed", request: mapSessionHumanInputRequest(request), event, events: repairedEvents, workflowWakeRevision: null, settledBy: "earlier_response", } as const; } const [turnPreview] = session.activeTurnId ? await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, session.activeTurnId), ), ) .limit(1) : []; const turn = turnPreview ? ( await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [turnPreview.id], }) ).turns[0] : undefined; if ( hasSkillReview && !input.expireOnly && turn && input.respondedBy !== (turn.initiatingHumanSubjectId ?? (turn.initiatorKind === "subject" ? turn.initiatorSubjectId : null)) ) { throw new HumanInputResponseValidationError( "HUMAN_AUTH_REQUIRED", "Only the human who started this work can answer its Skill review.", ); } const boundaryOwnsRequest = session.status === "requires_action" && turn?.status === "requires_action" && turn.id === request.turnId && turn.executionGeneration === request.turnGeneration; if (!boundaryOwnsRequest) { return { action: "conflict", request: mapSessionHumanInputRequest(request), events: [], workflowWakeRevision: null, } as const; } if ( await hasAcceptedRequiresActionAdvance(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: turn.id, turnGeneration: turn.executionGeneration, triggerEventId: turn.triggerEventId, }) ) { return { action: "conflict", request: mapSessionHumanInputRequest(request), events: [], workflowWakeRevision: null, } as const; } const now = new Date(); const expired = request.expiresAt !== null && request.expiresAt.getTime() <= now.getTime(); if (input.expireOnly && !expired) { return { action: "conflict", request: mapSessionHumanInputRequest(request), events: [], workflowWakeRevision: null, } as const; } let response: HumanInputResponse = expired ? { outcome: "expired" } : validateHumanInputResponse( mapSessionHumanInputRequest(request), input.response, secretAnswerQuestionIds, ); // "Let the agent decide" is the person's choice: an agent or the // system cannot hand the decision back to the asking agent this way // (it would skip a request that cannot be skipped and tell the agent // a person chose it). if ( response.outcome === "skipped" && response.agentDecides && !["human", "api"].includes( childRequiresActionRespondedByKindFor(input.respondedBy, input.respondedByKind), ) ) { throw new HumanInputResponseValidationError( "SKIP_NOT_ALLOWED", "Only a person can let the agent decide. Answer the question, or skip it if skipping is allowed.", ); } if ( hasSkillReview && !expired && (response.outcome !== "answered" || response.answers.length !== 1 || response.answers[0]!.values.length !== 1 || !["save", "skip"].includes(response.answers[0]!.values[0]!) || Boolean(response.answers[0]!.other?.trim())) ) { throw new HumanInputResponseValidationError( "INVALID_RESPONSE", "Choose Save or Don't save for this Skill review.", ); } if (response.outcome === "answered" && secretAnswers.length > 0) { if ( secretAnswers.some((answer) => answer.saveTo === "user") && input.canonicalHumanSession !== true && input.privateSecretAnswerAuthorized !== true ) { throw new HumanInputResponseValidationError( "HUMAN_AUTH_REQUIRED", "Saving to Only me needs a person signed in.", ); } if (!input.secretWriteContext) { throw new Error("Secret answers need the responder's vault write context"); } // Written before the response row so a vault failure rolls back the // whole answer; the stored response and event hold references only. const saved = await applyPreparedSecretAnswersInTransaction( tx as unknown as Database, input.secretWriteContext, { sessionId: input.sessionId, turnId: request.turnId, questions: request.questions, answers: secretAnswers, }, ); response = { ...response, answers: response.answers.map((answer) => { const secret = saved.get(answer.questionId); return secret ? { ...answer, values: [secret.reference], secret } : answer; }), }; } const [updated] = await tx .update(schema.sessionHumanInputRequests) .set({ status: response.outcome, response, respondedBy: expired ? "system:expired" : input.respondedBy, skillReviewHumanAuthorized: !expired && hasSkillReview && input.canonicalHumanSession === true, respondedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionHumanInputRequests.id, request.id), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.turnGeneration, turn.executionGeneration), ), ) .returning(); if (!updated) { if (secretAnswers.length > 0) { // Unreachable under the row lock; never commit vault writes for a lost answer. throw new SessionControlInvariantError( `Human-input request ${request.id} changed while saving its secret answers`, ); } return { action: "conflict", request: mapSessionHumanInputRequest(request), events: [], workflowWakeRevision: null, } as const; } if (!expired && hasSkillReview) { await confirmSkillHumanResponse(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.respondedBy, requestId: request.id, }); } await applySessionResponseMcpCredentialUpdatesInTransaction( tx as unknown as Database, input, ); // Bounded responder kind (never a subject id): lets the conversation // say who answered, and the parent notice report the same. const respondedByKind = expired ? ("system" as const) : childRequiresActionRespondedByKindFor(input.respondedBy, input.respondedByKind); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: turn.id, turnGeneration: turn.executionGeneration, turnAssociation: "current", sequence: session.lastSequence + 1, type: "user.humanInputResponse", payload: { requestId: request.id, response, respondedByKind }, clientEventId: expired ? null : (input.clientEventId ?? null), occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append human-input response"); await enqueueChildRequiresActionResolvedOutboxTx( tx as unknown as Database, input.workspaceId, session, { turnId: turn.id, turnGeneration: turn.executionGeneration, requestId: request.id, approvalId: null, outcome: response.outcome, respondedByKind, }, ); await mirrorSessionRealtimeContextInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sourceKind: "human_input_response", sourceId: event.id, turnId: turn.id, channel: response.outcome === "answered" || response.outcome === "skipped" ? "speakable" : null, text: renderRealtimeHumanInputResponseContext({ requestId: request.id, questions: request.questions, response, }), payload: { requestId: request.id, outcome: response.outcome, sourceEventId: event.id, }, now, }); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, session.id)); const workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, reason: "approval_decision", }, ); const mappedEvent = mapEvent(event); const result = { request: mapSessionHumanInputRequest(updated), events: [mappedEvent], workflowWakeRevision, }; return { action: "accepted", event: mappedEvent, ...result } as const; }), ); } export async function expireSessionHumanInputRequest( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; requestId: string; }, ): Promise { return await acceptSessionHumanInputResponse(db, { ...input, response: { outcome: "skipped" }, respondedBy: "system:expired", expireOnly: true, }); } export async function getHumanInputResumeForEvent( db: Database, workspaceId: string, sessionId: string, event: Pick, ): Promise<{ requestId: string; toolCallId: string; response: HumanInputResponse; } | null> { if (event.type !== "user.humanInputResponse") return null; const requestId = (event.payload as { requestId?: unknown }).requestId; if (typeof requestId !== "string") return null; const request = await getSessionHumanInputRequest(db, workspaceId, sessionId, requestId); return request?.response ? { requestId: request.id, toolCallId: request.toolCallId, response: request.response, } : null; } export class SessionBackgroundCommandAdoptionFencedError extends Error { readonly name = "SessionBackgroundCommandAdoptionFencedError"; constructor(public readonly reason: TurnAttemptFenceRejectReason) { super(`Background command adoption rejected by turn-attempt fence (${reason})`); } } /** Transfer one exact Connected Machine operation from a live turn attempt to * its session. The canonical write fence gives adoption a total order with * Steer, session/workspace Pause, terminal Cancel, and quiescent tree deletion: * an earlier adoption is visible to later control, while earlier control makes * this stale attempt fail before a session-owned row can appear. */ export async function adoptConnectedMachineSessionBackgroundCommand( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; command: string; /** Record an operation the turn already reported as failed because its * machine stopped answering. It enters the ledger with a stop request and * needs only proof that this exact attempt launched it: recording a stop * grants nothing, so Pause, cancellation or a finished attempt must not * leave the operation owned by a turn that can no longer stop it. */ abandoned?: boolean; }, ) { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // A Connected Machine locator may retain both the owning workspace and // a distinct physical origin workspace. Lock both prefixes in stable // order before the canonical attempt fence so deletion of either side // cannot cross or deadlock the adoption transaction. await lockBackgroundCommandWorkspaceLifecycle( tx, [input.workspaceId, input.controlWorkspaceId], "share", ); if (input.abandoned) { const [attempt] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.accountId, input.accountId), eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.turnId, input.turnId), eq(schema.sessionTurnAttempts.executionGeneration, input.executionGeneration), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ) .limit(1); if (!attempt) throw new SessionBackgroundCommandAdoptionFencedError("not_found"); return await insertConnectedMachineSessionBackgroundCommandInTransaction(tx, input); } const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, }); if (!fence.allowed) { throw new SessionBackgroundCommandAdoptionFencedError(fence.reason); } if (fence.session.accountId !== input.accountId) { throw new SessionBackgroundCommandAdoptionFencedError("attempt_changed"); } return await insertConnectedMachineSessionBackgroundCommandInTransaction(tx, input); }), ); } /** Record one exact Connected Machine or compute operation that a request * outside any turn (a direct terminal or file request) abandoned because its * machine stopped answering or its agent connection was replaced. The row * starts with a stop request bound to the exact enrollment, connection * instance and operation, so the reconciler alone decides its outcome: it * stops the operation if that runner answers again and settles it once the * runner is provably retired. Recording a stop grants nothing, so no turn * fence is needed; the workspace lifecycle locks order it against deletion. */ export async function recordAbandonedDirectConnectedMachineCommand( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; command: string; }, ) { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockBackgroundCommandWorkspaceLifecycle( tx, [input.workspaceId, input.controlWorkspaceId], "share", ); return await insertConnectedMachineSessionBackgroundCommandInTransaction(tx, { ...input, abandoned: true, }); }), ); } /** Transfer one exact managed retained process from a live turn attempt to its * session. Retaining the provider process and backgrounding it are deliberately * separate: a provider yield only preserves physical ownership; this adoption * occurs immediately before the running receipt becomes model-visible. */ export async function adoptManagedSessionBackgroundCommand( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; processId: string; expected: SandboxRetainedProcessIdentity; command: string; }, ) { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await lockBackgroundCommandWorkspaceLifecycle(tx, [input.workspaceId], "share"); const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, }); if (!fence.allowed) { throw new SessionBackgroundCommandAdoptionFencedError(fence.reason); } const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if ( fence.session.accountId !== input.accountId || !process || process.state !== "active" || process.ownerActorKind !== "turn" || process.ownerActorId !== input.attemptId || process.ownerTurnId !== input.turnId || process.ownerAttemptId !== input.attemptId || process.ownerExecutionGeneration !== input.executionGeneration || process.sandboxGroupId !== fence.session.sandboxGroupId || !retainedProcessMatchesSettlementIdentity(process, input.expected) ) { throw new SessionBackgroundCommandAdoptionFencedError("attempt_changed"); } return await insertManagedSessionBackgroundCommandInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, commandId: input.processId, retainedProcessId: input.processId, command: input.command, turnId: input.turnId, attemptId: input.attemptId, executionGeneration: input.executionGeneration, }); }), ); } /** Recover the missed receipt when a turn closes after retaining a legacy * Modal command. Unknown observation is not exit proof or a reason to block * subsequent turns: preserve the original process and adopt its background * lifetime. The exact reaper claim replaces the now-closed attempt's fence. */ export async function recoverManagedSessionBackgroundCommand( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; reconciliationClaimId: string; }, ) { return await withSessionActivityRlsContext(db, input, async (tx) => { const session = await lockWorkspaceMutationSessionTx(tx, input.workspaceId, input.sessionId); const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if ( session.accountId !== input.accountId || !process || process.state !== "active" || process.reconcileClaimId !== input.reconciliationClaimId || !retainedProcessMatchesSettlementIdentity(process, input.expected) || process.providerBackend !== "modal" || process.routeTargetId !== null || process.providerCommand?.kind !== "modal-router-v1" || process.providerCommand.supervision || process.ownerActorKind !== "turn" || !process.ownerAttemptId || !process.ownerTurnId || process.ownerActorId !== process.ownerAttemptId || process.ownerExecutionGeneration === null ) return null; const [owner] = await tx .select({ state: schema.sessionTurnAttempts.state }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.accountId, input.accountId), eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.id, process.ownerAttemptId), eq(schema.sessionTurnAttempts.turnId, process.ownerTurnId), eq(schema.sessionTurnAttempts.executionGeneration, process.ownerExecutionGeneration), ), ) .limit(1); if (owner?.state !== "closed") return null; const [existing] = await tx .select({ id: schema.sessionBackgroundCommands.id }) .from(schema.sessionBackgroundCommands) .where(eq(schema.sessionBackgroundCommands.retainedProcessId, process.id)) .limit(1); if (existing) return null; const command = await insertManagedSessionBackgroundCommandInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, commandId: process.id, retainedProcessId: process.id, turnId: process.ownerTurnId, attemptId: process.ownerAttemptId, executionGeneration: process.ownerExecutionGeneration, command: `Retained command ${process.providerSessionId}; execution outcome unknown after interrupted turn. Inspect the existing execution; it has not been replayed.`, }); const control = await evaluateSessionWriteAdmissionControl( tx, input.workspaceId, input.sessionId, { lock: "none", lockedSession: session, }, ); const stopping = process.cancellationRequestedAt !== null || control.state !== "active"; if (stopping) await tx .update(schema.sessionBackgroundCommands) .set({ state: "stopping", cancelRequestedAt: process.cancellationRequestedAt ?? new Date(), cancelRequestedBy: "system:retained-command-recovery", }) .where(eq(schema.sessionBackgroundCommands.id, command.id)); await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${input.sessionId}`, reason: "retained_command_background_recovery", }); return { ...command, state: stopping ? ("stopping" as const) : command.state, }; }); } export type InstallOrReadTurnExecutionPolicyForAttemptResult = | { accepted: true; installed: boolean; policy: TurnExecutionPolicyV1; turn: SessionTurn; } | { accepted: false; reason: TurnAttemptFenceRejectReason; }; /** * Freeze a legacy turn's execution identity at its first admitted attempt, or * return the policy already accepted for this logical turn. The exact active * attempt owns this mutation; malformed present metadata fails closed and a * replay never replaces an existing valid policy. */ export async function installOrReadTurnExecutionPolicyForAttempt( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; policyForAbsent: TurnExecutionPolicyV1; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, }); if (!fence.allowed) { return { accepted: false as const, reason: fence.reason }; } const existing = readTurnExecutionPolicyV1(fence.turn.metadata); if (existing.kind === "valid") { return { accepted: true as const, installed: false, policy: existing.policy, turn: mapSessionTurn(fence.turn), }; } const policy = TurnExecutionPolicyV1.parse(input.policyForAbsent); const [updated] = await tx .update(schema.sessionTurns) .set({ metadata: metadataWithTurnExecutionPolicyV1(fence.turn.metadata, policy), updatedAt: new Date(), }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), eq(schema.sessionTurns.status, "running"), eq(schema.sessionTurns.executionGeneration, input.executionGeneration), eq(schema.sessionTurns.activeAttemptId, input.attemptId), ), ) .returning(); if (!updated) { throw new Error("Turn execution policy owner changed while its row was locked"); } return { accepted: true as const, installed: true, policy, turn: mapSessionTurn(updated), }; }), ); } type SessionContextChannel = { /** Error-message subject, for example "Skill catalog". */ label: string; /** Turn metadata key freezing the snapshot for every attempt of the turn. */ metadataKey: string; /** Literal content prefix that identifies this channel in stored history. */ contentPrefix: string; read: (item: Record) => string | null; item: (text: string) => Record; /** Texts the model reads the same way; defaults to exact equality. */ same?: (left: string, right: string) => boolean; }; const SKILL_CATALOG_CHANNEL: SessionContextChannel = { label: "Skill catalog", metadataKey: "opengeniSkillCatalogHistoryId", contentPrefix: SKILL_CATALOG_CONTEXT_PREFIX, read: readSkillCatalogContext, item: skillCatalogContextItem, }; const REPOSITORY_SKILLS_CHANNEL: SessionContextChannel = { label: "Repository skills", metadataKey: "opengeniRepositorySkillsHistoryId", contentPrefix: REPOSITORY_SKILLS_CONTEXT_PREFIX, read: readRepositorySkillsContext, item: repositorySkillsContextItem, }; const WORKSPACE_GOVERNANCE_CHANNEL: SessionContextChannel = { label: "Workspace governance", metadataKey: "opengeniWorkspaceGovernanceHistoryId", contentPrefix: WORKSPACE_GOVERNANCE_CONTEXT_PREFIX, read: readWorkspaceGovernanceContext, item: workspaceGovernanceContextItem, }; const WORKSPACE_FILESYSTEM_CHANNEL: SessionContextChannel = { label: "Workspace filesystem", metadataKey: "opengeniWorkspaceFilesystemHistoryId", contentPrefix: WORKSPACE_FILESYSTEM_CONTEXT_PREFIX, read: readWorkspaceFilesystemContext, item: workspaceFilesystemContextItem, }; const AGENT_INSTRUCTIONS_CHANNEL: SessionContextChannel = { label: "Agent instructions", metadataKey: "opengeniAgentInstructionsHistoryId", contentPrefix: AGENT_INSTRUCTIONS_CONTEXT_PREFIX, read: readAgentInstructionsContext, item: agentInstructionsContextItem, same: sameAgentInstructionsContext, }; /** Persist the current catalog once per logical turn; retries reuse its exact snapshot. */ export async function ensureSessionSkillCatalog( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; catalog: string; /** * The catalog lists no Skill: write nothing unless an earlier index must * be replaced, and return "" when the session never saw one. */ omitWhenEmpty?: boolean; }, ): Promise { const { catalog, omitWhenEmpty, ...scope } = input; return ( (await ensureSessionContextSnapshot( db, { ...scope, text: catalog, ...(omitWhenEmpty ? { omitWhenAbsent: true } : {}) }, SKILL_CATALOG_CHANNEL, )) ?? "" ); } /** * Persist the repository Skill index the run discovered in the live * workspace, once per logical turn, as a history item before the turn's first * history item (with that turn's id). Retries reuse the turn's snapshot even * when the workspace changed meanwhile. Nothing is written while the newest * item already shows the same index. Null means this run did not index the * workspace (a deferred run): nothing is written, and the turn keeps what the * model already reads, so a later attempt of the turn cannot add an item * between its requests. Returns the model-visible index, or null when there * is none. * * Discovery runs inside the model run, after this turn's history was loaded, * so the run shows the returned item at the same place itself (see the * runtime's `publishRepositorySkills`). */ export async function ensureSessionRepositorySkills( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; index: string | null; }, ): Promise { const { index, ...scope } = input; return await ensureSessionContextSnapshot( db, { ...scope, text: index }, REPOSITORY_SKILLS_CHANNEL, ); } /** * Persist the rendered workspace governance once per logical turn, as a * history item before the turn that first sees a new value. Retries reuse the * turn snapshot. Null means no governance applies: nothing is written unless * earlier governance must be explicitly withdrawn. Returns the model-visible * governance, or null when none is visible. */ export async function ensureSessionWorkspaceGovernance( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; governance: string | null; }, ): Promise { const { governance, ...scope } = input; const visible = await ensureSessionContextSnapshot( db, { ...scope, text: governance ?? WORKSPACE_GOVERNANCE_NONE, omitWhenAbsent: governance === null, }, WORKSPACE_GOVERNANCE_CHANNEL, ); return visible === null || visible === WORKSPACE_GOVERNANCE_NONE ? null : visible; } /** * Persist the active workspace's filesystem layout once per logical turn, as * a history item before the turn that first sees a new layout (for example * after the session moved to another machine). Retries reuse the turn * snapshot. Null means the turn has no sandbox: nothing is written and the * model keeps the layout it last read. Returns the model-visible layout. */ export async function ensureSessionWorkspaceFilesystem( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; layout: string | null; }, ): Promise { const { layout, ...scope } = input; return await ensureSessionContextSnapshot( db, { ...scope, text: layout }, WORKSPACE_FILESYSTEM_CHANNEL, ); } /** * The agent revision baked into a chat's system prompt * (`sessions.agent_prompt_revision`) and its instructions. Null for every chat * not bound to an agent revision, which never gets the agent layer. A deleted * agent (its revisions go with it) or a missing revision reads as * `instructions: null`, so the chat continues as a plain chat. */ export type SessionAgentPrompt = { agentId: string | null; revision: number; instructions: string | null; /** * Organization agent chats only: the version the chat runs this turn * (`agent_version`, frozen per turn). `revision` is then the version whose * Instructions are in the system prompt (`agent_prompt_version`). */ orgVersion?: number; /** * Organization agent worker chats only (a chat started by another chat): * after a move they get the new version's Instructions only when that * version shares them with workers. */ workerChat?: true; }; /** Turn metadata key freezing the prompt revision for every attempt of a turn. */ const AGENT_PROMPT_REVISION_METADATA_KEY = "opengeniAgentPromptRevision"; /** Turn metadata key freezing the organization agent version for every attempt of a turn. */ export const ORG_AGENT_VERSION_METADATA_KEY = "opengeniOrgAgentVersion"; /** * Freeze a positive integer in the turn's metadata on its first attempt; * later attempts read the frozen value back. Fenced to the live attempt. */ async function freezeTurnMetadataInteger( db: Database, input: { accountId: string; workspaceId: string; sessionId: string }, turn: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string }, key: string, value: number, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: turn.turnId, executionGeneration: turn.expectedExecutionGeneration, attemptId: turn.expectedAttemptId, }); if (!fence.allowed) throw new Error("Agent prompt attempt is fenced"); const frozen = fence.turn.metadata[key]; if (frozen !== undefined) { if (typeof frozen !== "number" || !Number.isSafeInteger(frozen) || frozen < 1) throw new Error(`Invalid ${key} receipt`); return frozen; } await tx .update(schema.sessionTurns) .set({ metadata: { ...fence.turn.metadata, [key]: value }, updatedAt: new Date() }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, turn.turnId), ), ); return value; }), ); } /** * The organization agent version a chat runs, read once per turn: the first * attempt records it in the turn's metadata (`opengeniOrgAgentVersion`) and * retries reuse it, so a publish move between attempts never changes a turn's * tools or logins. Null for every chat that runs no organization agent. */ export async function readSessionOrgAgentVersion( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turn?: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string }; }, ): Promise<{ agentId: string; version: number } | null> { const [row] = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, (scopedDb) => rawRows<{ agent_id: string | null; agent_version: number | null }>( scopedDb, sql`select s.agent_id::text as agent_id, s.agent_version from sessions s where s.workspace_id = ${input.workspaceId}::uuid and s.id = ${input.sessionId}::uuid`, ), ); if (!row?.agent_id || row.agent_version === null || row.agent_version === undefined) return null; const version = input.turn ? await freezeTurnMetadataInteger( db, input, input.turn, ORG_AGENT_VERSION_METADATA_KEY, Number(row.agent_version), ) : Number(row.agent_version); return { agentId: row.agent_id, version }; } /** * An Only me agent serves only its owner's Only me chats. A chat shared * later, or one whose agent became Only me, continues as a plain chat. * `a` is the agent; the session is read by id. */ function boundAgentServesChatSql(input: { workspaceId: string; sessionId: string }): SQL { return sql`(a.visibility = 'workspace' or exists ( select 1 from sessions chat where chat.workspace_id = ${input.workspaceId}::uuid and chat.id = ${input.sessionId}::uuid and chat.visibility = 'user_private' and chat.owner_subject_id = a.owner_subject_id))`; } /** * The bound agent's rows, read as the system: the session's binding to its * agent, with {@link boundAgentServesChatSql} for prompt reads, is the * authorization, whoever the turn acts for. */ async function readBoundAgentRows>( db: Database, input: { accountId: string; workspaceId: string }, query: SQL, ): Promise { return await withoutSessionRlsActor(() => withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => (await rawRows(scopedDb, query))[0], ), ); } /** * Pass `turn` from a turn attempt: the first attempt records the revision in * the turn's metadata and later attempts reuse it, so every attempt of a turn * builds the same system prompt even after an earlier attempt's compaction * folded a newer revision into the session. */ export async function readSessionAgentPrompt( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turn?: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string }; }, ): Promise { const scope = { accountId: input.accountId, workspaceId: input.workspaceId }; const session = await withRlsContext(db, scope, async (scopedDb) => { const [row] = await rawRows<{ agent_id: string | null; revision: number | null; agent_version: number | null; agent_prompt_version: number | null; worker_chat: boolean | null; }>( scopedDb, sql`select s.agent_id::text as agent_id, s.agent_prompt_revision as revision, s.agent_version, s.agent_prompt_version, (s.parent_session_id is not null) as worker_chat from sessions s where s.workspace_id = ${input.workspaceId}::uuid and s.id = ${input.sessionId}::uuid`, ); return row; }); if ( session && session.agent_id && session.agent_version !== null && session.agent_version !== undefined ) { return await readSessionOrgAgentPrompt(db, input, { agentId: session.agent_id, version: Number(session.agent_version), promptVersion: session.agent_prompt_version === null || session.agent_prompt_version === undefined ? null : Number(session.agent_prompt_version), workerChat: session.worker_chat === true, }); } if (!session || session.revision === null || session.revision === undefined) return null; let revision = Number(session.revision); const turn = input.turn; if (turn) { revision = await withRlsContext(db, scope, async (scopedDb) => scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: turn.turnId, executionGeneration: turn.expectedExecutionGeneration, attemptId: turn.expectedAttemptId, }); if (!fence.allowed) throw new Error("Agent prompt attempt is fenced"); const frozen = fence.turn.metadata[AGENT_PROMPT_REVISION_METADATA_KEY]; if (frozen !== undefined) { if (typeof frozen !== "number" || !Number.isSafeInteger(frozen) || frozen < 1) throw new Error("Invalid agent prompt revision receipt"); return frozen; } await tx .update(schema.sessionTurns) .set({ metadata: { ...fence.turn.metadata, [AGENT_PROMPT_REVISION_METADATA_KEY]: revision }, updatedAt: new Date(), }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, turn.turnId), ), ); return revision; }), ); } const agentId = session.agent_id ?? null; const row = agentId ? await readBoundAgentRows<{ instructions: string }>( db, scope, sql`select r.instructions from agent_revisions r join agents a on a.workspace_id = r.workspace_id and a.id = r.agent_id where r.workspace_id = ${input.workspaceId}::uuid and r.agent_id = ${agentId}::uuid and r.revision = ${revision}::integer and ${boundAgentServesChatSql(input)}`, ) : undefined; return { agentId, revision, instructions: row?.instructions ?? null }; } /** * An organization agent chat's prompt layer: the Instructions of * `agent_prompt_version` (null = no agent layer, a worker chat whose agent * does not share them), with both versions frozen for every attempt of the * turn. Versions are immutable, so an archived agent keeps its Instructions. */ async function readSessionOrgAgentPrompt( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turn?: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string }; }, session: { agentId: string; version: number; promptVersion: number | null; workerChat: boolean; }, ): Promise { if (session.promptVersion === null) return null; let revision = session.promptVersion; let orgVersion = session.version; if (input.turn) { revision = await freezeTurnMetadataInteger( db, input, input.turn, AGENT_PROMPT_REVISION_METADATA_KEY, revision, ); orgVersion = await freezeTurnMetadataInteger( db, input, input.turn, ORG_AGENT_VERSION_METADATA_KEY, orgVersion, ); } const row = await readOrgAgentVersion(db, { accountId: input.accountId, workspaceId: input.workspaceId, agentId: session.agentId, version: revision, }); return { agentId: session.agentId, revision, instructions: row?.instructions ?? null, orgVersion, ...(session.workerChat ? { workerChat: true } : {}), }; } /** * Deliver an edit of the chat's agent made since its system prompt was built: * once per logical turn, as a developer history item before the turn that * first sees the new revision. Retries reuse the turn's snapshot. Nothing is * written while the newest item (or, without one, the system prompt) already * shows the current instructions; a revision that changed only other fields * shows nothing new. A deleted agent withdraws an earlier edit item and the * chat continues as a plain chat; an agent whose current revision cannot be * read changes nothing. Returns the model-visible item text, or null when the * system prompt alone applies. */ export async function ensureSessionAgentInstructions( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; prompt: SessionAgentPrompt; }, ): Promise { const { prompt, ...scope } = input; if (prompt.orgVersion !== undefined && prompt.agentId) { // An organization agent chat moved to a newer version: its Instructions // arrive as a history item until compaction folds them into the prompt. const current = await readOrgAgentVersion(db, { accountId: input.accountId, workspaceId: input.workspaceId, agentId: prompt.agentId, version: prompt.orgVersion, }).catch(() => null); // A worker chat keeps the Instructions it has when the version it moved // to does not share them with workers; nothing new is written. const shared = current !== null && (prompt.workerChat !== true || orgAgentConfigSharesInstructions(current.config)); return await ensureSessionContextSnapshot( db, { ...scope, text: shared && current ? agentInstructionsContextText({ kind: "revision", revision: current.version, instructions: current.instructions, }) : null, baselineText: agentInstructionsContextText( prompt.instructions === null ? { kind: "deleted" } : { kind: "revision", revision: prompt.revision, instructions: prompt.instructions }, ), }, AGENT_INSTRUCTIONS_CHANNEL, ); } const current = prompt.agentId ? await readBoundAgentRows<{ revision: number; instructions: string | null }>( db, input, sql`select a.current_revision as revision, r.instructions from agents a left join agent_revisions r on r.workspace_id = a.workspace_id and r.agent_id = a.id and r.revision = a.current_revision where a.workspace_id = ${input.workspaceId}::uuid and a.id = ${prompt.agentId}::uuid and ${boundAgentServesChatSql(input)}`, ) : undefined; return await ensureSessionContextSnapshot( db, { ...scope, text: !current ? agentInstructionsContextText({ kind: "deleted" }) : current.instructions === null || current.instructions === undefined ? null : agentInstructionsContextText({ kind: "revision", revision: Number(current.revision), instructions: current.instructions, }), baselineText: agentInstructionsContextText( prompt.instructions === null ? { kind: "deleted" } : { kind: "revision", revision: prompt.revision, instructions: prompt.instructions, }, ), }, AGENT_INSTRUCTIONS_CHANNEL, ); } async function ensureSessionContextSnapshot( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; /** * The current text, or null when it cannot be read: the turn then keeps * whatever the model already reads and nothing is written. */ text: string | null; /** Write nothing when the session has no earlier item of this channel. */ omitWhenAbsent?: boolean; /** * What the model already reads when the session has no earlier item of * this channel (its system prompt). Text the model reads the same way * writes nothing, and the turn is frozen without an item. */ baselineText?: string; }, channel: SessionContextChannel, ): Promise { const lower = channel.label.toLowerCase(); const same = channel.same ?? ((left: string, right: string) => left === right); return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) throw new Error(`${channel.label} attempt is fenced`); const scope = and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), ); const frozen = fence.turn.metadata[channel.metadataKey]; if (frozen !== undefined && frozen !== false && typeof frozen !== "string") throw new Error(`Invalid ${lower} receipt`); // A turn frozen without any item of this channel keeps seeing none. if (frozen === false) return null; const [previous] = await tx .select({ id: schema.sessionHistoryItems.id, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, }) .from(schema.sessionHistoryItems) .where( and( scope, typeof frozen === "string" ? eq(schema.sessionHistoryItems.id, frozen) : and( eq(schema.sessionHistoryItems.active, true), sql`${schema.sessionHistoryItems.item}->>'type' = 'message'`, sql`${schema.sessionHistoryItems.item}->>'role' = 'developer'`, sql`starts_with(${schema.sessionHistoryItems.item}->>'content', ${channel.contentPrefix})`, ), ), ) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); const previousText = previous ? channel.read(fromPostgresLosslessJson(previous.item, previous.itemCodecVersion)) : null; if (frozen !== undefined) { if (previousText === null) throw new Error(`Missing durable ${lower} snapshot`); return previousText; } const text = input.text; let historyId = previous?.id; if ( !previous && (text === null || input.omitWhenAbsent || (input.baselineText !== undefined && same(input.baselineText, text))) ) { await tx .update(schema.sessionTurns) .set({ metadata: { ...fence.turn.metadata, [channel.metadataKey]: false }, updatedAt: new Date(), }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), ), ); return null; } const written = text !== null && (previousText === null || !same(previousText, text)) ? text : null; if (written !== null) { const [boundary] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where( and( scope, eq(schema.sessionHistoryItems.active, true), eq(schema.sessionHistoryItems.turnId, input.turnId), ), ) .orderBy(asc(schema.sessionHistoryItems.position)) .limit(1); let position: number; if (boundary) { const [prior] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where(and(scope, lt(schema.sessionHistoryItems.position, boundary.position))) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); position = prior ? (prior.position + boundary.position) / 2 : boundary.position - 0.25; if (!(position < boundary.position) || (prior && !(position > prior.position))) throw new Error(`${channel.label} position exhausted`); } else { if (fence.turn.source !== "compaction") throw new Error(`${channel.label} requires durable accepted input`); const [tail] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where(scope) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); position = tail ? Math.floor(tail.position) + 1 : 0; } historyId = crypto.randomUUID(); await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( { id: historyId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position, item: channel.item(written), }, "item", "itemCodecVersion", ), ); } if (!historyId) throw new Error(`Missing ${lower} history identity`); await tx .update(schema.sessionTurns) .set({ metadata: { ...fence.turn.metadata, [channel.metadataKey]: historyId }, updatedAt: new Date(), }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), ), ); return written ?? previousText; }), ); } /** Install an effort update before accepted input, or at the maintenance tail, under the attempt fence. */ export async function ensureSessionReasoningConfiguration( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; effort: ConfigurationEffort; }, ): Promise { return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) throw new Error("Reasoning configuration attempt is fenced"); if (fence.turn.reasoningEffort !== input.effort) throw new Error("Reasoning configuration differs from accepted turn"); // Read only small control records and positions, never the full conversation. const scope = and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), eq(schema.sessionHistoryItems.active, true), ); const controls = await tx .select({ item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, }) .from(schema.sessionHistoryItems) .where( and( scope, sql`${schema.sessionHistoryItems.item}->>'type' = 'unknown'`, sql`${schema.sessionHistoryItems.item}->'opengeniReasoningConfiguration' IS NOT NULL`, ), ) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); const state = controls[0] ? readReasoningConfiguration( fromPostgresLosslessJson(controls[0].item, controls[0].itemCodecVersion), ) : null; if (state?.turnId === input.turnId || state?.effort === input.effort) return state.baselineEffort; const [boundary] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where(and(scope, eq(schema.sessionHistoryItems.turnId, input.turnId))) .orderBy(asc(schema.sessionHistoryItems.position)) .limit(1); let position: number; if (!boundary) { if (fence.turn.source !== "compaction") throw new Error("Reasoning update requires durable accepted input"); // Maintenance turns deliberately have no user message. Append before // the compaction trigger; include inactive rows when reserving a slot. const [tail] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), ), ) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); position = tail ? Math.floor(tail.position) + 1 : 0; } else { const [previous] = await tx .select({ position: schema.sessionHistoryItems.position }) .from(schema.sessionHistoryItems) .where(and(scope, lt(schema.sessionHistoryItems.position, boundary.position))) .orderBy(desc(schema.sessionHistoryItems.position)) .limit(1); position = previous ? (previous.position + boundary.position) / 2 : boundary.position - 0.25; if (!(position < boundary.position) || (previous && !(position > previous.position))) throw new Error("Reasoning configuration position exhausted"); } const baselineEffort = state?.baselineEffort ?? input.effort; await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position, item: reasoningConfigurationItem({ version: 1, baselineEffort, effort: input.effort, turnId: input.turnId, }), }, "item", "itemCodecVersion", ), ); return baselineEffort; }), ); } /** * Append conversation items (verbatim SDK AgentInputItems) to the session's * history. Idempotent on (workspace, session, position): concurrent or * repeated writers (streaming writes + turn-end reconciliation) converge * instead of duplicating. */ export async function appendSessionHistoryItems( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; modelToolOutputTruncationTokens?: number; items: Array<{ position: number; item: Record }>; /** Tool outputs already have durable timeline events; retire their receipts with history. */ completedToolCallIds?: string[]; /** * Receives the stored footprint of the rows this call inserted, measured by * PostgreSQL in the same statement, once the append has committed. */ onAppendedFootprint?: (delta: ActiveSessionHistoryFootprint) => void; }, ): Promise { if (input.items.length === 0 && !input.completedToolCallIds?.length) { return true; } let appendedFootprint: ActiveSessionHistoryFootprint | null = null; // One idempotent transaction: a deadlock/serialization victim rolled back // entirely, so it retries as a unit; it contains no external effect. const appended = await retryRlsPersistence( db, { accountId: input.accountId, workspaceId: input.workspaceId }, { stage: "session_history_append", correlationId: input.expectedAttemptId }, async (tx) => { appendedFootprint = null; const allowed = await lockTurnAttemptWriteFenceTx(tx, { rowProjection: "event", workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!allowed.allowed) return false; appendedFootprint = await appendSessionHistoryItemsInTransaction(tx, input, allowed); return true; }, ); // Assigned inside the retried transaction callback; the last attempt wins. const delta = appendedFootprint as ActiveSessionHistoryFootprint | null; if (appended && delta) input.onAppendedFootprint?.(delta); return appended; } /** Append under an existing exact-attempt fence; acknowledge the footprint only after commit. */ export async function appendSessionHistoryItemsInTransaction( tx: Database, input: Omit[1], "onAppendedFootprint">, allowed: Extract, ): Promise { assertPendingToolCallCheckpointScope( { ...input, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }, allowed, ); const inserted = input.items.length === 0 ? [] : await tx .insert(schema.sessionHistoryItems) .values( withLosslessContentWriteVersion( input.items.map((entry) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position: entry.position, // This is the canonical model-memory boundary. The pending-call // ledger and audit event may retain their separate raw/preview // forms, but conversation truth is always the bounded Codex form // without Responses output-only fields such as `status`. item: canonicalizePersistedHistoryItem( entry.item, input.modelToolOutputTruncationTokens, ), })), "item", "itemCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionHistoryItems.workspaceId, schema.sessionHistoryItems.sessionId, schema.sessionHistoryItems.position, ], }) .returning({ position: schema.sessionHistoryItems.position, turnId: schema.sessionHistoryItems.turnId, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, // Measured exactly as the active-history guard measures: // bytes of the ordered JSON text, shape of the jsonb projection // the insert trigger maintains. jsonBytes: sql`octet_length(${schema.sessionHistoryItems.item}::text)`, jsonNodes: jsonbNodeCountSql(sql`session_history_items.item`), jsonProperties: jsonbPropertyCountSql(sql`session_history_items.item`), }); // Rows skipped by ON CONFLICT were already stored, so only fresh inserts // add to the active footprint. const appendedFootprint = inserted.reduce( (total, row) => ({ jsonBytes: total.jsonBytes + Number(row.jsonBytes) + 1, rows: total.rows + 1, jsonNodes: total.jsonNodes + Number(row.jsonNodes), jsonProperties: total.jsonProperties + Number(row.jsonProperties), }), { jsonBytes: 0, rows: 0, jsonNodes: 0, jsonProperties: 0 }, ); const saved = inserted.map(({ position, turnId, item, itemCodecVersion }) => ({ position, turnId, item, itemCodecVersion, })); // A position conflict is idempotent only when the exact conversation // item is already there. Never acknowledge a different item as saved. // Fresh inserts already return their durable representation. Re-reading // numeric positions under RLS can scan the session's history while we // hold its write fence, so only fetch rows skipped by ON CONFLICT. const insertedPositions = new Set(saved.map((row) => row.position)); const conflictingPositions = input.items .map((entry) => entry.position) .filter((position) => !insertedPositions.has(position)); if (conflictingPositions.length > 0) saved.push( ...(await tx .select({ position: schema.sessionHistoryItems.position, turnId: schema.sessionHistoryItems.turnId, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), inArray(schema.sessionHistoryItems.position, conflictingPositions), ), )), ); const byPosition = new Map(saved.map((row) => [row.position, row])); for (const entry of input.items) { const row = byPosition.get(entry.position); if ( !row || row.turnId !== input.turnId || !isDeepStrictEqual( fromPostgresLosslessJson(row.item, row.itemCodecVersion), canonicalizePersistedHistoryItem(entry.item, input.modelToolOutputTruncationTokens), ) ) { throw new Error(`Conversation history persistence conflict at position ${entry.position}`); } } if (input.completedToolCallIds?.length) { await clearDurablePendingSessionToolCallsInTransaction( tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, callIds: input.completedToolCallIds, }, allowed, ); } return appendedFootprint; } export type PendingSessionToolCallInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; callId: string; callType: string; callItem: Record; modelToolOutputTruncationTokens?: number; }; function assertPendingToolOutputPolicyMatches( stored: number | null, supplied: number | undefined, callId: string, ): void { if (stored !== null && supplied !== undefined && stored !== supplied) { throw new Error( `SDK tool call ${callId} changed model tool-output policy from ${stored} to ${supplied}`, ); } } // Receipt inputs have already passed the strict JSON storage boundary. Compare // exact keys structurally: locale collation can equate distinct Unicode keys. function pendingToolCallItemsEqual(left: unknown, right: unknown): boolean { if (left === right) return true; if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false; if (Array.isArray(left) || Array.isArray(right)) { return ( Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => pendingToolCallItemsEqual(value, right[index])) ); } const keys = Object.keys(left); return ( keys.length === Object.keys(right).length && keys.every( (key) => Object.hasOwn(right, key) && pendingToolCallItemsEqual( (left as Record)[key], (right as Record)[key], ), ) ); } /** * Durably capture the raw SDK call item at the exact attempt boundary. This is * model-facing truth, deliberately separate from the session-event timeline. * The receipt belongs to the logical turn so an approval resume can * settle it from a newer attempt. Duplicate SDK delivery converges on the * unique (turn, call) identity. * The caller owns the transaction and has already acquired the exact attempt * fence. This lets the receipt share its timeline event's atomic checkpoint. */ export async function registerPendingSessionToolCallInTransaction( tx: Database, input: PendingSessionToolCallInput, fence: Extract, ): Promise<{ accepted: boolean; registered: boolean }> { assertPendingToolCallCheckpointScope(input, fence); const inserted = await tx .insert(schema.sessionPendingToolCalls) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, callId: input.callId, callType: input.callType, callItem: input.callItem, modelToolOutputTruncationTokens: input.modelToolOutputTruncationTokens ?? null, }, "callItem", "callItemCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionPendingToolCalls.workspaceId, schema.sessionPendingToolCalls.turnId, schema.sessionPendingToolCalls.callId, ], }) .returning({ id: schema.sessionPendingToolCalls.id }); if (inserted.length === 0) { const [pending] = await tx .select({ id: schema.sessionPendingToolCalls.id, accountId: schema.sessionPendingToolCalls.accountId, callType: schema.sessionPendingToolCalls.callType, callItem: schema.sessionPendingToolCalls.callItem, callItemCodecVersion: schema.sessionPendingToolCalls.callItemCodecVersion, modelToolOutputTruncationTokens: schema.sessionPendingToolCalls.modelToolOutputTruncationTokens, }) .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), eq(schema.sessionPendingToolCalls.callId, input.callId), ), ) .for("update") .limit(1); if ( !pending || pending.accountId !== input.accountId || pending.callType !== input.callType || !pendingToolCallItemsEqual( fromPostgresLosslessJson(pending.callItem, pending.callItemCodecVersion), input.callItem, ) ) { // A duplicate acknowledges only this exact call. It neither // replaces the originating attempt nor authorizes effect replay. throw new Error("Pending tool receipt conflicts with the registered call"); } assertPendingToolOutputPolicyMatches( pending.modelToolOutputTruncationTokens, input.modelToolOutputTruncationTokens, input.callId, ); if ( pending.modelToolOutputTruncationTokens === null && input.modelToolOutputTruncationTokens !== undefined ) { await tx .update(schema.sessionPendingToolCalls) .set({ modelToolOutputTruncationTokens: input.modelToolOutputTruncationTokens, }) .where(eq(schema.sessionPendingToolCalls.id, pending.id)); } } return { accepted: true, registered: inserted.length === 1 }; } function assertPendingToolCallCheckpointScope( input: Omit, fence: Extract, ): void { if ( fence.workspace.id !== input.workspaceId || fence.session.accountId !== input.accountId || fence.session.id !== input.sessionId || fence.turn.id !== input.turnId || fence.turn.executionGeneration !== input.executionGeneration || fence.attempt.id !== input.attemptId ) throw new Error("Pending tool checkpoint does not match its locked attempt"); } /** Root-handle entry point: each rollback retry starts a fresh fenced transaction. */ export async function registerPendingSessionToolCall( db: Database, input: PendingSessionToolCallInput, ): Promise<{ accepted: boolean; registered: boolean }> { const correlationId = crypto.randomUUID(); const registerOnce = async (attempt: number) => { try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, rowProjection: "event" }); if (!fence.allowed) return { accepted: false, registered: false }; return await registerPendingSessionToolCallInTransaction(tx, input, fence); }, ); } catch (error) { if (!isRetryableDatabaseTransportFailure(error)) throw error; // Stop before the shared SQLSTATE traversal can prefer an older nested // rollback over a transport/commit-ack failure. This private outcome is // converted to a sanitized error outside the retry helper, never success. return { transportFailure: error, attempt }; } }; // Only PostgreSQL-confirmed rollback can replay this transaction callback. // withRlsContext separately retries pool admission before callback entry, // where no receipt or external effect could exist yet. Re-enter RLS and // acquire the complete attempt fence each time; never include inference or tools. const result = await runIdempotentPersistenceTransaction( { stage: "pending_tool_registration", correlationId, maxAttempts: 3, onRetry: async ({ attempt }) => { await new Promise((resolve) => setTimeout(resolve, 25 * attempt)); }, }, registerOnce, ); if ("transportFailure" in result) { throw new SessionEventPersistenceError( { code: "db_failure", sqlState: null, stage: "pending_tool_registration", eventTypes: [], correlationId, attempts: result.attempt, retryOutcome: "not_retryable", database: safeDatabaseErrorFacts(result.transportFailure), }, result.transportFailure, ); } return result; } /** Record the raw SDK result without dropping the call receipt. */ export async function recordPendingSessionToolCallResultInTransaction( tx: Database, input: Omit & { resultItem: Record; /** Exact agent.toolCall.output value, separate from model-facing history. */ eventOutput?: unknown; /** Commit a durable async-video acceptance fence with this exact result. */ videoGenerationAcceptance?: { operationId: string; requestDigest: string; }; }, fence: Extract, ): Promise<{ accepted: boolean; recorded: boolean }> { assertPendingToolCallCheckpointScope(input, fence); const [pending] = await tx .select() .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), eq(schema.sessionPendingToolCalls.callId, input.callId), ), ) .for("update") .limit(1); if (!pending) return { accepted: true, recorded: false }; assertPendingToolOutputPolicyMatches( pending.modelToolOutputTruncationTokens, input.modelToolOutputTruncationTokens, input.callId, ); if ( pending.modelToolOutputTruncationTokens === null && input.modelToolOutputTruncationTokens !== undefined ) { await tx .update(schema.sessionPendingToolCalls) .set({ modelToolOutputTruncationTokens: input.modelToolOutputTruncationTokens, }) .where(eq(schema.sessionPendingToolCalls.id, pending.id)); } const resultType = TOOL_RESULT_TYPE_BY_CALL_TYPE[pending.callType]; if ( !resultType || historyItemType(input.resultItem) !== resultType || historyCallId(input.resultItem) !== input.callId ) { throw new Error(`SDK tool result does not settle ${pending.callType}:${input.callId}`); } const resultUpdate = withLosslessContentWriteVersion( { resultItem: input.resultItem, resultRecordedAt: new Date(), }, "resultItem", "resultItemCodecVersion", ); const update = Object.hasOwn(input, "eventOutput") ? withLosslessContentWriteVersion( { ...resultUpdate, // Kept only to replay the result's agent.toolCall.output event, which // is bounded on write anyway; store it within the same bound. A tool // can return far more than an event (or a single jsonb string, at // most 256 MiB) can hold, and that must not fail the turn. Bounding // the `{ value }` envelope keeps the value's own shape and records // any omission in a sibling `truncation` that replay carries over. eventOutput: boundSessionEventPayloadForWrite( "agent.toolCall.output", { value: input.eventOutput }, ), }, "eventOutput", "eventOutputCodecVersion", ) : resultUpdate; const recorded = await tx .update(schema.sessionPendingToolCalls) .set(update) .where( and( eq(schema.sessionPendingToolCalls.id, pending.id), sql`${schema.sessionPendingToolCalls.resultItem} is null`, ), ) .returning({ id: schema.sessionPendingToolCalls.id }); if (input.videoGenerationAcceptance) { const [operation] = await tx .select() .from(schema.videoGenerationOperations) .where( and( eq(schema.videoGenerationOperations.workspaceId, input.workspaceId), eq(schema.videoGenerationOperations.id, input.videoGenerationAcceptance.operationId), eq( schema.videoGenerationOperations.requestDigest, input.videoGenerationAcceptance.requestDigest, ), ), ) .for("update") .limit(1); if (!operation) throw new Error("Video generation acceptance operation disappeared"); await markVideoGenerationAcceptedInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, operation, toolCallId: input.callId, }); } else { // Admission and its accepted tool result are one causal boundary. If // reference preparation (or any other pre-submit work) failed, settle // the still-unaccepted operation in this same result transaction so // quota and managed credits cannot remain reserved. await cancelUnacceptedVideoGenerationsForToolCallsInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, toolCallIds: [input.callId], reason: "Video generation failed before it was accepted.", now: new Date(), }); } return { accepted: true, recorded: recorded.length === 1, }; } /** Standalone recovery/test callers retain a fresh, exact-attempt transaction. */ export async function recordPendingSessionToolCallResult( db: Database, input: Parameters[1], ): Promise<{ accepted: boolean; recorded: boolean }> { return await retryRlsPersistence( db, { accountId: input.accountId, workspaceId: input.workspaceId }, { stage: "session_pending_tool_call_result", correlationId: input.callId }, async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, rowProjection: "event" }); if (!fence.allowed) return { accepted: false, recorded: false }; return await recordPendingSessionToolCallResultInTransaction(tx, input, fence); }, ); } export type OpenSuffixInterruptionKind = "human_input" | "approval" | "interaction_intervention"; export type OpenSuffixPendingToolCall = { callId: string; callType: string; callItem: Record; interruptionKind: OpenSuffixInterruptionKind; tiedReasoningItems: Array>; resultItem: Record | null; modelToolOutputTruncationTokens: number | null; /** Private state of the MCP server question that paused this call, if any. */ mcpInputRequest?: Record | null; }; function asOpenSuffixInterruptionKind(value: string | null): OpenSuffixInterruptionKind | null { if (value === null) { return null; } if (value === "human_input" || value === "approval" || value === "interaction_intervention") { return value; } throw new Error(`Unknown pending-tool interruption kind: ${value}`); } /** * Bind unpaired interruption calls and their tied reasoning onto existing * pending receipts. Fail closed when any interruption call is missing. */ export async function attachOpenSuffixToPendingToolCalls( db: Database, input: Omit & { members: Array<{ callId: string; interruptionKind: OpenSuffixInterruptionKind; reasoningItems: Array>; /** The MCP server question that paused this call, kept outside events. */ mcpInputRequest?: Record; }>; }, ): Promise<{ accepted: boolean; attached: number }> { if (input.members.length === 0) { return { accepted: true, attached: 0 }; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { rowProjection: "event", workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, }); if (!fence.allowed) return { accepted: false, attached: 0 }; const ordered = [...input.members].sort((left, right) => left.callId.localeCompare(right.callId), ); let attached = 0; for (const member of ordered) { const [pending] = await tx .select() .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), eq(schema.sessionPendingToolCalls.callId, member.callId), ), ) .for("update") .limit(1); if (!pending) { throw new Error( `Open suffix interruption ${member.callId} has no pending tool-call receipt`, ); } if (pending.resultItem) { throw new Error( `Open suffix interruption ${member.callId} already has a recorded result`, ); } const existingKind = asOpenSuffixInterruptionKind(pending.interruptionKind); if (existingKind && existingKind !== member.interruptionKind) { throw new Error( `Open suffix interruption ${member.callId} changed kind from ${existingKind} to ${member.interruptionKind}`, ); } const updated = await tx .update(schema.sessionPendingToolCalls) .set( withLosslessContentWriteVersion( { interruptionKind: member.interruptionKind, tiedReasoningItems: member.reasoningItems, ...(member.mcpInputRequest ? { mcpInputRequest: member.mcpInputRequest } : {}), }, "tiedReasoningItems", "tiedReasoningItemsCodecVersion", ), ) .where(eq(schema.sessionPendingToolCalls.id, pending.id)) .returning({ id: schema.sessionPendingToolCalls.id }); if (updated.length === 1) { attached += 1; } } return { accepted: true, attached }; }), ); } /** Turn-scoped interruption suffix rows, including already-settled members. */ export async function listTurnOpenSuffixToolCalls( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, workspaceId), eq(schema.sessionPendingToolCalls.sessionId, sessionId), eq(schema.sessionPendingToolCalls.turnId, turnId), isNotNull(schema.sessionPendingToolCalls.interruptionKind), ), ) .orderBy(asc(schema.sessionPendingToolCalls.createdAt)); return rows.map((row) => { const interruptionKind = asOpenSuffixInterruptionKind(row.interruptionKind); if (!interruptionKind) { throw new Error(`Pending tool call ${row.callId} is missing interruption kind`); } return { callId: row.callId, callType: row.callType, callItem: row.callItem, interruptionKind, tiedReasoningItems: Array.isArray(row.tiedReasoningItems) ? row.tiedReasoningItems : [], resultItem: row.resultItem ?? null, modelToolOutputTruncationTokens: row.modelToolOutputTruncationTokens, mcpInputRequest: row.mcpInputRequest ?? null, }; }); }); } /** * Whether any tool-call receipt of the turn remains, interrupted or not. None * means every call the turn made is settled in durable history (an open * call's item lives only in its receipt until it is paired with a result), so * there is nothing left for an approval or human-input resume to settle. */ export async function turnHasPendingToolCalls( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.sessionPendingToolCalls.id }) .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, workspaceId), eq(schema.sessionPendingToolCalls.sessionId, sessionId), eq(schema.sessionPendingToolCalls.turnId, turnId), ), ) .limit(1); return row !== undefined; }); } /** * The interaction_request_human calls of a turn that hold an intervention: a * request recorded at a pause, or a wait attached to one. Any status counts; * a call not listed was refused (or never reached a pause). */ export async function listRecordedInteractionToolCallIds( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; toolCallIds: string[] }, ): Promise> { if (input.toolCallIds.length === 0) return new Set(); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ toolCallId: schema.interactionInterventions.originatingToolCallId }) .from(schema.interactionInterventions) .where( and( eq(schema.interactionInterventions.workspaceId, input.workspaceId), eq(schema.interactionInterventions.originatingSessionId, input.sessionId), eq(schema.interactionInterventions.originatingTurnId, input.turnId), inArray(schema.interactionInterventions.originatingToolCallId, input.toolCallIds), ), ); return new Set(rows.flatMap((row) => (row.toolCallId ? [row.toolCallId] : []))); }); } /** * The MCP server answered a resumed call with another question: replace the * paused call's stored question so the next approval answers the new one. The * call stays open; only the attempt that resumed it may write. */ export async function replacePendingToolCallMcpInputRequest( db: Database, input: Omit & { callId: string; mcpInputRequest: Record; }, ): Promise<{ accepted: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { rowProjection: "event", workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, }); if (!fence.allowed) return { accepted: false }; const updated = await tx .update(schema.sessionPendingToolCalls) .set({ mcpInputRequest: input.mcpInputRequest }) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), eq(schema.sessionPendingToolCalls.callId, input.callId), isNull(schema.sessionPendingToolCalls.resultItem), ), ) .returning({ id: schema.sessionPendingToolCalls.id }); if (updated.length !== 1) { throw new Error(`Paused call ${input.callId} is no longer open`); } return { accepted: true }; }), ); } /** * Remove completed receipts only after the full SDK call/result batch is * durable. Until then every raw result remains available to an attempt-ending * transaction, including reverse-completing parallel calls. */ export async function clearDurablePendingSessionToolCallsInTransaction( tx: Database, input: Omit & { callIds: string[]; }, fence: Extract, ): Promise<{ accepted: boolean; cleared: number }> { assertPendingToolCallCheckpointScope(input, fence); if (input.callIds.length === 0) return { accepted: true, cleared: 0 }; const pending = await tx .select() .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), inArray(schema.sessionPendingToolCalls.callId, input.callIds), sql`${schema.sessionPendingToolCalls.resultItem} is not null`, ), ) .for("update"); if (pending.length === 0) return { accepted: true, cleared: 0 }; const durableIds = await durableToolCallPairIdsTx(tx, input, pending); if (durableIds.length > 0) { await tx .delete(schema.sessionPendingToolCalls) .where(inArray(schema.sessionPendingToolCalls.id, durableIds)); } return { accepted: true, cleared: durableIds.length }; } export async function clearDurablePendingSessionToolCalls( db: Database, input: Parameters[1], ): Promise<{ accepted: boolean; cleared: number }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, rowProjection: "event" }); if (!fence.allowed) return { accepted: false, cleared: 0 }; return await clearDurablePendingSessionToolCallsInTransaction(tx, input, fence); }, ); } const DURABLE_TOOL_CALL_SCAN_PAGE = 32; /** * A pending call is durable once its call item and a later result item are in * the turn's history. The batch being cleared was just appended, so read the * turn newest-first a page at a time and stop as soon as every pending call is * proven: the cost follows the batch, not the whole turn transcript. A result * after any matching call item is a result after the earliest one, so the * newest-first proof is the same predicate as a whole-turn scan. Unproven * calls still read the whole turn before staying pending. */ async function durableToolCallPairIdsTx( tx: Pick, scope: { workspaceId: string; sessionId: string; turnId: string }, pending: Array<{ id: string; callId: string; callType: string }>, ): Promise { const unproven = new Map(); for (const call of pending) { const resultType = TOOL_RESULT_TYPE_BY_CALL_TYPE[call.callType]; if (resultType) unproven.set(call.callId, { id: call.id, callType: call.callType, resultType }); } // Pending calls whose result item was already seen at a later position. const resultSeen = new Set(); const durable: string[] = []; let before: number | null = null; while (unproven.size > 0) { const page = await readSessionHistoryToolIdentityPage( tx, scope, before, DURABLE_TOOL_CALL_SCAN_PAGE, ); // Positions are unique per session, so each row is strictly older than // every row already seen. for (const row of page) { const { callId, type } = row; if (callId === null || type === null) continue; const call = unproven.get(callId); if (!call) continue; if (type === call.callType && resultSeen.has(callId)) { durable.push(call.id); unproven.delete(callId); } else if (type === call.resultType) { resultSeen.add(callId); } } if (page.length < DURABLE_TOOL_CALL_SCAN_PAGE) break; before = page[page.length - 1]!.position; } return durable; } export async function getSessionHistoryItems( db: Database, workspaceId: string, sessionId: string, ): Promise }>> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ position: schema.sessionHistoryItems.position, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), ), ) .orderBy(schema.sessionHistoryItems.position); return rows.map(({ itemCodecVersion, ...row }) => ({ ...row, item: fromPostgresLosslessJson(row.item, itemCodecVersion), })); }); } /** * The LIVE conversation-truth read path: only active rows, position-ordered. * After a client-side context compaction this returns [retained user messages, * active summary]; with no compaction yet it equals * getSessionHistoryItems. The model-facing read path uses this so superseded * (summarized-away) prefix rows are excluded while the full transcript stays in * the table as an audit trail. */ export async function getActiveSessionHistoryItems( db: Database, workspaceId: string, sessionId: string, ): Promise< Array<{ id: string; position: number; item: Record; providerArtifactInvalidatedAt: Date | null; }> > { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ id: schema.sessionHistoryItems.id, position: schema.sessionHistoryItems.position, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, providerArtifactInvalidatedAt: schema.sessionHistoryItems.providerArtifactInvalidatedAt, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), eq(schema.sessionHistoryItems.active, true), ), ) .orderBy(schema.sessionHistoryItems.position); return rows.map(({ itemCodecVersion, ...row }) => ({ ...row, item: fromPostgresLosslessJson(row.item, itemCodecVersion), })); }); } /** Bounded finalized voice turns used only to resume a later realtime call. */ export async function getSessionRealtimeContinuityEntries( db: Database, workspaceId: string, sessionId: string, maximumEntries = 20, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [session] = await scopedDb .select({ accountId: schema.sessions.accountId }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!session) return []; return await listSessionRealtimeContinuityEntriesInTransaction(scopedDb, { accountId: session.accountId, workspaceId, sessionId, maximumEntries, }); }); } /** * Count of ACTIVE (live, model-facing) history rows for a session. This is the * length of the history the next turn is seeded from — the dual-write slice * index — which after a compaction is far smaller than the total persisted-row * count (countSessionHistoryItems still includes the superseded prefix). */ export async function countActiveSessionHistoryItems( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ count: sql`count(*)`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), eq(schema.sessionHistoryItems.active, true), ), ); return Number(row?.count ?? 0); }); } /** * Result-item types and the CALL type that settles each. Kept byte-for-byte in * sync with the runtime sanitizer's RESULT_TYPE_BY_CALL_TYPE and the repair * migration (0014). The repair, the read-path sanitizer, and this spec all share * one definition of a tool-call pair. */ const REPAIR_CALL_TYPE_BY_RESULT_TYPE: Record = { function_call_result: "function_call", computer_call_result: "computer_call", shell_call_output: "shell_call", apply_patch_call_output: "apply_patch_call", }; function repairCallIdOf(item: unknown): string | undefined { if (!item || typeof item !== "object") { return undefined; } const record = item as { callId?: unknown; call_id?: unknown }; if (typeof record.callId === "string") { return record.callId; } if (typeof record.call_id === "string") { return record.call_id; } return undefined; } function repairItemType(item: unknown): string | undefined { if (!item || typeof item !== "object") { return undefined; } const type = (item as { type?: unknown }).type; return typeof type === "string" ? type : undefined; } /** * Pure TypeScript SPEC for the one-time orphan repair (migration 0014), * mirroring its SQL WHERE clause so the deletion rule is unit-testable without a * database. Given the ACTIVE history rows of a single session in position order, * returns the indices of the orphaned tool-call RESULT rows the repair deletes. * * An orphan is a result-type row (function_call_result / computer_call_result / * shell_call_output / apply_patch_call_output) with no matching CALL of the * paired type, same correlation id (camelCase `callId` OR snake_case `call_id`), * at a STRICTLY EARLIER position in the same session. This is exactly the * session-bricking row the Responses API 400s on ("No tool call found for * function call output"). * * DANGLING CALLS (a call with no result yet) are intentionally NOT returned: a * call awaiting a not-yet-settled result is valid, not corruption. Only unpaired * results are removed. * * EXISTENCE, not consumption: like the migration's `NOT EXISTS (... earlier * call ...)`, a result is kept whenever ANY earlier matching call exists. A * second result that re-uses a call_id already settled earlier is therefore NOT * flagged here (a matching call still exists before it) — this conservative * choice matches the SQL exactly and never deletes a row whose call is present; * the read-path sanitizer (which consumes calls one-for-one) still drops such a * rare duplicate in-memory, so the model request stays valid regardless. * * Callers pass rows already ordered by position. The earlier-position test is * by array order (the SQL orders by the numeric position column, which the read * path also orders by), so identical inputs yield identical decisions. */ export function orphanedResultRowIndicesForRepair( activeRowsInPositionOrder: ReadonlyArray<{ item: Record }>, ): number[] { // call_ids of CALLs seen so far, per matching result type. A result is an // orphan unless a call of its paired type with the same id appeared earlier. const seenCallIdsByResultType = new Map>(); // Pre-index every call type to the result type(s) it can settle. const resultTypeByCallType: Record = {}; for (const [resultType, callType] of Object.entries(REPAIR_CALL_TYPE_BY_RESULT_TYPE)) { resultTypeByCallType[callType] = resultType; } const orphanIndices: number[] = []; activeRowsInPositionOrder.forEach((row, index) => { const type = repairItemType(row.item); const callId = repairCallIdOf(row.item); if (!type || !callId) { return; } const settlesResultType = resultTypeByCallType[type]; if (settlesResultType) { // This row is a CALL: record its id so a later matching result is paired. const seen = seenCallIdsByResultType.get(settlesResultType) ?? new Set(); seen.add(callId); seenCallIdsByResultType.set(settlesResultType, seen); return; } if (REPAIR_CALL_TYPE_BY_RESULT_TYPE[type]) { // This row is a RESULT: orphan unless an earlier matching call was seen. const seen = seenCallIdsByResultType.get(type); if (!seen || !seen.has(callId)) { orphanIndices.push(index); } } }); return orphanIndices; } export type ApplyContextCompactionResult = | { applied: true; supersededFrom: number; summaryPosition: number; events: SessionEvent[]; } | { applied: false; reason: TurnAttemptFenceRejectReason }; const RETAINED_ROW_TURN_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; function retainedRowTurnId( turnId: string | null | undefined, sessionTurnIds: ReadonlySet, ): string | null { return typeof turnId === "string" && sessionTurnIds.has(turnId) ? turnId : null; } /** Whether the chat runs an organization agent that has this version. */ async function sessionHasOrgAgentVersion( db: Database, input: { accountId: string; workspaceId: string; sessionId: string }, version: number, ): Promise { return await withoutSessionRlsActor(() => withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => withOrgAgentsVisible(scopedDb, async () => { const [row] = await rawRows<{ found: number }>( scopedDb, sql`select 1 as found from sessions s join agent_revisions r on r.account_id = s.account_id and r.workspace_id is null and r.agent_id = s.agent_id and r.revision = ${version}::integer where s.workspace_id = ${input.workspaceId}::uuid and s.id = ${input.sessionId}::uuid and s.agent_version is not null`, ); return Boolean(row); }), ), ); } /** * Atomically install the Codex-style replacement history for one exact turn * attempt. The old active rows remain as inactive audit evidence; the retained * user messages and summary receive fresh whole-number positions after every * existing row. A paused, replaced, recovered, or terminal attempt cannot * mutate conversation truth. * * `replacementTurnIds`, aligned with `replacementItems`, keeps the turn each * retained message came from, so a later compaction can still pair a request * with its own turn's answer. (Retained reply copies are passed as null and * record their turn in the item, so turn-keyed readers such as message forks * never see two rows of one reply.) An id that is not a turn of * this session is stored as null, like rows written without one. */ export async function applyContextCompaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; replacementItems: Array>; replacementTurnIds?: ReadonlyArray; summaryItem: Record; trailingItems?: Array>; clearRequestedCompaction?: boolean; /** * The replacement is a portable rebuild of a Codex remote_v2 session for * another model: switch the session to portable compaction with it. */ switchToPortableCompaction?: boolean; /** * Agent chats: the newest agent revision the summarized history showed. * It becomes the revision baked into the system prompt from the next turn * on (`sessions.agent_prompt_revision`), in the same transaction as the * replacement, because the edit items that carried it are not retained. */ agentPromptRevision?: number; eventPayload?: Record; }, ): Promise { if ( input.replacementTurnIds !== undefined && input.replacementTurnIds.length !== input.replacementItems.length ) { throw new Error("Compaction replacement turn ids must align with replacement items"); } let agentPromptRevision = input.agentPromptRevision; // Organization agent chats: the version folded into `agent_prompt_version`. let orgAgentPromptVersion: number | undefined; if (agentPromptRevision !== undefined) { if (!Number.isSafeInteger(agentPromptRevision) || agentPromptRevision < 1) throw new Error("Invalid agent prompt revision"); // Fold only a revision of the chat's own agent. Revisions are immutable // and go only with their agent, so the check cannot go stale before the // update below in any way that matters. const ownRevision = await readBoundAgentRows<{ found: number }>( db, input, sql`select 1 as found from sessions s join agent_revisions r on r.workspace_id = s.workspace_id and r.agent_id = s.agent_id and r.revision = ${agentPromptRevision}::integer where s.workspace_id = ${input.workspaceId}::uuid and s.id = ${input.sessionId}::uuid`, ); if (!ownRevision) agentPromptRevision = undefined; if (!ownRevision && (await sessionHasOrgAgentVersion(db, input, input.agentPromptRevision!))) { orgAgentPromptVersion = input.agentPromptRevision; } } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) { return { applied: false as const, reason: fence.reason }; } const [{ maxPosition } = { maxPosition: -1 }] = await tx .select({ maxPosition: sql`coalesce(max(${schema.sessionHistoryItems.position}), -1)`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), ), ); const supersededFrom = Math.floor(Number(maxPosition)) + 1; // Installing a successful summary is model progress, including a // maintenance turn that never enters the ordinary response stream. // Clear only provider recovery under the same locked attempt fence. if ( providerRecoveryCountFromTurnMetadata(fence.turn!.metadata) > 0 || fence.turn!.metadata?.[PROVIDER_RECOVERY_SUSPENDED_AT] !== undefined ) { await tx .update(schema.sessionTurns) .set({ metadata: metadataWithoutProviderRecoveryCount(fence.turn!.metadata), version: fence.turn!.version + 1, updatedAt: new Date(), }) .where(eq(schema.sessionTurns.id, input.turnId)); } await tx .update(schema.sessionHistoryItems) .set({ active: false }) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), eq(schema.sessionHistoryItems.active, true), ), ); const requestedTurnIds = [ ...new Set( (input.replacementTurnIds ?? []).filter( (turnId): turnId is string => typeof turnId === "string" && RETAINED_ROW_TURN_ID_PATTERN.test(turnId), ), ), ]; const sessionTurnIds = new Set( requestedTurnIds.length === 0 ? [] : ( await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), inArray(schema.sessionTurns.id, requestedTurnIds), ), ) ).map((row) => row.id), ); if (input.replacementItems.length > 0) { await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( input.replacementItems.map((item, index) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: retainedRowTurnId(input.replacementTurnIds?.[index], sessionTurnIds), position: supersededFrom + index, item: omitOutputOnlyHistoryItemFields(item), active: true, })), "item", "itemCodecVersion", ), ); } const summaryPosition = supersededFrom + input.replacementItems.length; await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position: summaryPosition, item: omitOutputOnlyHistoryItemFields(input.summaryItem), active: true, }, "item", "itemCodecVersion", ), ); if (input.trailingItems?.length) { await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( input.trailingItems.map((item, index) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: null, position: summaryPosition + 1 + index, item: omitOutputOnlyHistoryItemFields(item), active: true, })), "item", "itemCodecVersion", ), ); } const insertedEvents = input.eventPayload ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnGeneration: input.expectedExecutionGeneration, turnAttemptId: input.expectedAttemptId, turnAssociation: "current", sequence: fence.session.lastSequence + 1, type: "session.context.compacted", payload: { ...input.eventPayload, summaryPosition, // Where this compaction's live segment begins: a message // fork reconstructs the history live at an earlier message. replacementFromPosition: supersededFrom, }, occurredAt: new Date(), }, "payload", "payloadCodecVersion", ), ) .returning() : []; await tx .update(schema.sessions) .set({ // The active model input changed without an ordinary provider call. // Keep this field provider-only and let the first successful // post-compaction response install the next authoritative count. lastInputTokens: null, ...(input.clearRequestedCompaction ? { compactRequested: false, compactRequestTrigger: null } : {}), ...(input.switchToPortableCompaction ? { codexCompactionMode: "portable" } : {}), ...(insertedEvents.length > 0 ? { lastSequence: fence.session.lastSequence + insertedEvents.length, } : {}), updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); if (agentPromptRevision !== undefined) { // Only a chat already bound to an agent revision is folded, and only // forward: a plain chat never becomes an agent chat here, and a // retried attempt's compaction never moves the prompt back. await tx.execute(sql` update sessions set agent_prompt_revision = ${agentPromptRevision}::integer where workspace_id = ${input.workspaceId}::uuid and id = ${input.sessionId}::uuid and agent_id is not null and agent_prompt_revision < ${agentPromptRevision}::integer `); } if (orgAgentPromptVersion !== undefined) { // An organization agent chat whose prompt has an agent layer folds // the version its history showed; never past the version it runs. // A rollback publish moves to a lower version, so "forward" is // toward agent_version, not toward a higher number. await tx.execute(sql` update sessions set agent_prompt_version = ${orgAgentPromptVersion}::integer where workspace_id = ${input.workspaceId}::uuid and id = ${input.sessionId}::uuid and agent_id is not null and agent_version = ${orgAgentPromptVersion}::integer and agent_prompt_version is not null and agent_prompt_version <> ${orgAgentPromptVersion}::integer `); } return { applied: true as const, supersededFrom, summaryPosition, events: insertedEvents.map(mapEvent), }; }); }, ); } /** * Attempt-fenced visible start of a compaction provider call. Emitted before * the summarizer / remote-v2 request so the timeline can show progress while * the opaque checkpoint is being built. A fenced attempt writes nothing. */ export async function recordStartedContextCompaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; trigger: "auto" | "operator" | "proactive" | "overflow"; implementation?: string; estimatedTokensBefore?: number; /** One request-byte recovery per logical turn, including recovered attempts. */ requestSizeRecovery?: Record; }, ): Promise< | { recorded: true; events: SessionEvent[] } | { recorded: false; reason: TurnAttemptFenceRejectReason | "request_size_recovery_exhausted" } > { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) return { recorded: false as const, reason: fence.reason }; if (input.requestSizeRecovery) { if (fence.turn!.metadata.claudeRequestSizeRecoveryUsed === true) return { recorded: false as const, reason: "request_size_recovery_exhausted" as const }; await tx .update(schema.sessionTurns) .set({ metadata: { ...fence.turn!.metadata, claudeRequestSizeRecoveryUsed: true }, version: fence.turn!.version + 1, updatedAt: new Date(), }) .where(eq(schema.sessionTurns.id, input.turnId)); } const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnGeneration: input.expectedExecutionGeneration, turnAttemptId: input.expectedAttemptId, turnAssociation: "current", sequence: fence.session.lastSequence + 1, type: "session.context.compaction.started", payload: { trigger: input.trigger, ...(input.requestSizeRecovery ? { requestSize: input.requestSizeRecovery } : {}), ...(input.implementation ? { implementation: input.implementation } : {}), ...(typeof input.estimatedTokensBefore === "number" ? { estimatedTokensBefore: input.estimatedTokensBefore } : {}), }, occurredAt: new Date(), }, "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ lastSequence: fence.session.lastSequence + 1, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { recorded: true as const, events: inserted.map(mapEvent) }; }), ); } /** * Atomically record that an operator compaction request needed no replacement * and consume it. The exact running attempt owns both the visible event and * the clear, just like a successful replacement; a paused, recovered, or * superseded attempt can do neither and leaves the request pending. */ export async function recordSkippedContextCompaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; reason: | "no_history" | "replacement_not_smaller" | "replacement_exceeds_model_budget" | "replacement_unchanged" | "summarization_failed" /** * The attempt was cancelled (worker shutdown or another activity * cancellation) while the checkpoint request was in flight. Not a * provider or summarizer failure; the recovered attempt re-evaluates. */ | "interrupted"; /** * When false, record the visible skip even if no operator `/compact` is * pending (auto/overflow paths that already emitted `compaction.started`). * Defaults to true so idle-operator consumption stays request-gated. */ requirePendingRequest?: boolean; /** When false, leave `compactRequested` untouched. Defaults to true. */ clearRequestedCompaction?: boolean; /** * Closed, content-free identifiers of a definitive provider rejection * (`summarization_failed` only): HTTP status, error type/code, rejected * parameter path, provider request id. Never a provider message. */ providerRejection?: { httpStatus: number; type: string | null; code: string | null; param: string | null; requestId: string | null; }; /** * The provider's own error message (`summarization_failed` only), bounded * by the caller. Session events are the conversation's own data, readable * by the same people as the conversation. */ providerMessage?: string; }, ): Promise< | { recorded: true; events: SessionEvent[] } | { recorded: false; reason: TurnAttemptFenceRejectReason | "request_not_pending"; } > { const requirePendingRequest = input.requirePendingRequest !== false; const clearRequestedCompaction = input.clearRequestedCompaction !== false; return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) return { recorded: false as const, reason: fence.reason }; if (requirePendingRequest && !fence.session.compactRequested) { return { recorded: false as const, reason: "request_not_pending" as const, }; } const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnGeneration: input.expectedExecutionGeneration, turnAttemptId: input.expectedAttemptId, turnAssociation: "current", sequence: fence.session.lastSequence + 1, type: "session.context.compaction.skipped", payload: { reason: input.reason, ...(input.providerRejection && input.reason === "summarization_failed" ? { providerRejection: input.providerRejection } : {}), ...(input.providerMessage && input.reason === "summarization_failed" ? { providerMessage: input.providerMessage } : {}), }, occurredAt: new Date(), }, "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ ...(clearRequestedCompaction ? { compactRequested: false, compactRequestTrigger: null } : {}), lastSequence: fence.session.lastSequence + 1, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ...(clearRequestedCompaction ? [eq(schema.sessions.compactRequested, true)] : []), ), ); return { recorded: true as const, events: inserted.map(mapEvent) }; }), ); } /** * Whether a Steer is waiting for this session's running turn: a queued prompt * marked `delivery: "steer"` (human, API, or a queue row an agent steered) or * a pending Agent Steer instruction, or, while the running turn is a run of an * automation whose overlap is `steer`, a pending later run of that same * automation. Steer admission leaves a live attempt running, and the worker * reads this before each model request: a pending Steer is delivered at that * model-step boundary by settling the running turn `superseded` (reason * `steer`, `atModelStep`), after the completed step's tool calls and results * are recorded, so nothing in flight is cut off. The Steer then runs next on * the same history. * * This unlocked read only decides whether that settlement is worth trying. * The settlement's `requirePendingSteer` precondition re-checks the same * predicate under the session lock, so a Steer withdrawn in between leaves * the turn running. */ export async function hasPendingSteerForTurn( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await pendingSteerExists(scopedDb, input.workspaceId, input.sessionId, input.turnId), ); } /** The single predicate for a Steer waiting for a running turn's next model step. */ async function pendingSteerExists( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { const [steerPrompt] = await db .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.status, "queued"), ne(schema.sessionTurns.id, turnId), sql`${schema.sessionTurns.metadata} ->> 'delivery' = 'steer'`, ), ) .limit(1); if (steerPrompt) { // A queued Steer that waits for the personal machine's owner cannot run, // so it must not hand the owner's running turn over to it. const owner = await sessionMachineOwnerSubject(db, { accountId: null, workspaceId, sessionId, }); if (owner === null) return true; const [runnableSteer] = await db .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.status, "queued"), ne(schema.sessionTurns.id, turnId), sql`${schema.sessionTurns.metadata} ->> 'delivery' = 'steer'`, notWaitingForMachineOwnerSql(owner), ), ) .limit(1); if (runnableSteer) return true; } const [agentSteer] = await db .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .limit(1); if (agentSteer) return true; return await pendingAutomationSteerExists(db, workspaceId, sessionId, turnId); } /** * A later run of the automation that owns the running turn waits in the chat, * and that automation hands its running turn over (`overlapPolicy: "steer"`). * Only the automation's own turn yields: a person's turn, a goal continuation * or another automation's run never matches, so they finish first and the run * is delivered after them as usual. The waiting run must be deliverable as it * stands (dispatched with its accepted execution, the claim's own preclaim * rule), so a run the claim would refuse never ends the turn for nothing. */ async function pendingAutomationSteerExists( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { const turns = schema.sessionTurns; const runs = schema.scheduledTaskRuns; const tasks = schema.scheduledTasks; const updates = schema.sessionSystemUpdates; const [row] = await rawRows<{ present: number }>( db, sql`select 1 as present from ${turns} running_turn join ${runs} running_run on running_run.workspace_id = running_turn.workspace_id and running_run.id = running_turn.scheduled_task_run_id join ${tasks} task on task.workspace_id = running_run.workspace_id and task.id = running_run.task_id where running_turn.workspace_id = ${workspaceId} and running_turn.session_id = ${sessionId} and running_turn.id = ${turnId} and task.overlap_policy = 'steer' and task.status = 'active' and task.deleted_at is null and exists ( select 1 from ${updates} waiting join ${runs} waiting_run on waiting_run.workspace_id = waiting.workspace_id and waiting_run.id = waiting.scheduled_task_run_id where waiting.workspace_id = running_turn.workspace_id and waiting.session_id = running_turn.session_id and waiting.kind = 'scheduled_occurrence' and waiting.state = 'pending' and waiting_run.task_id = task.id and waiting_run.id <> running_run.id and waiting_run.status = 'dispatched' and waiting_run.accepted_execution_snapshot is not null ) limit 1`, ); return row !== undefined; } /** * Read the durable handoff condition immediately after one exact compaction * landmark settles. Steer admission deliberately leaves the active attempt * unfenced while its latest compaction event is `started`; the worker calls * this at the first safe boundary after `compacted`/`skipped` and supersedes * the ordinary turn before another model request can begin. * * The later terminal settlement remains the authority fence. This read only * decides whether that settlement is needed, so a concurrent Pause/Cancel or a * Steer admitted after the landmark can still win and make the caller stale. */ export async function hasPendingSteerAfterContextCompaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [ownership] = await scopedDb .select({ sessionActiveTurnId: schema.sessions.activeTurnId, turnStatus: schema.sessionTurns.status, turnSource: schema.sessionTurns.source, turnGeneration: schema.sessionTurns.executionGeneration, turnActiveAttemptId: schema.sessionTurns.activeAttemptId, attemptState: schema.sessionTurnAttempts.state, attemptGeneration: schema.sessionTurnAttempts.executionGeneration, }) .from(schema.sessions) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessions.workspaceId), eq(schema.sessionTurns.sessionId, schema.sessions.id), eq(schema.sessionTurns.id, input.turnId), ), ) .innerJoin( schema.sessionTurnAttempts, and( eq(schema.sessionTurnAttempts.workspaceId, schema.sessionTurns.workspaceId), eq(schema.sessionTurnAttempts.turnId, schema.sessionTurns.id), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if ( !ownership || ownership.sessionActiveTurnId !== input.turnId || ownership.turnStatus !== "running" || ownership.turnSource === "compaction" || ownership.turnGeneration !== input.executionGeneration || ownership.turnActiveAttemptId !== input.attemptId || ownership.attemptGeneration !== input.executionGeneration || !["claimed", "running"].includes(ownership.attemptState) ) { return false; } const [latestCompaction] = await scopedDb .select({ type: schema.sessionEvents.type }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.turnGeneration, input.executionGeneration), eq(schema.sessionEvents.turnAttemptId, input.attemptId), inArray(schema.sessionEvents.type, [ "session.context.compaction.started", "session.context.compacted", "session.context.compaction.skipped", ]), ), ) .orderBy(desc(schema.sessionEvents.sequence), desc(schema.sessionEvents.id)) .limit(1); if ( latestCompaction?.type !== "session.context.compacted" && latestCompaction?.type !== "session.context.compaction.skipped" ) { return false; } return await pendingSteerExists(scopedDb, input.workspaceId, input.sessionId, input.turnId); }, ); } /** * The next free WHOLE-NUMBER history position for a session: one past the * largest existing position (active or superseded), floored so the synthetic * summary's fractional half-step never shifts the count. The dual-write * watermark uses this to append new rows at fresh absolute positions, decoupled * from the in-memory history length (which, after a compaction, is far shorter * than the total persisted-row count and so cannot serve as the next position). */ export async function nextSessionHistoryPosition( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ maxPosition: sql`max(${schema.sessionHistoryItems.position})`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), ), ); const max = row?.maxPosition; return max === null || max === undefined ? 0 : Math.floor(Number(max)) + 1; }); } /** Persist socket refusal before HTTP dispatch, under the current attempt fence. * Every recovery path and worker replacement then inherits the same turn policy. */ export async function markSessionTurnModelTransportHttpOnly( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; }, ): Promise { return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, rowProjection: "event" }); if (!fence.allowed) return false; await tx .update(schema.sessionTurns) .set({ metadata: sql`${schema.sessionTurns.metadata} || '{"persistentModelTransportHttpOnly":true}'::jsonb`, }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), ), ); return true; }), ); } /** * Replace the input-token count for the most recent authoritative terminal * response. Null means that response supplied no usable final-call count, so * the next turn must not reuse an older response's value for compaction. */ export async function setSessionLastInputTokensForTurnAttempt( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; lastInputTokens: number | null; }, ): Promise { return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const fence = await lockTurnAttemptWriteFenceTx(tx, { rowProjection: "event", workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!fence.allowed) return false; await setSessionLastInputTokensInTransaction(tx, fence, input.lastInputTokens); return true; }); }); } /** The caller owns the exact session/turn/attempt locks through commit. */ export async function setSessionLastInputTokensInTransaction( tx: Database, fence: Extract, lastInputTokens: number | null, ): Promise { await tx .update(schema.sessions) .set({ lastInputTokens, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, fence.workspace.id), eq(schema.sessions.id, fence.session.id), ), ); } /** The neutral boundary left as the sole active history row after a clear. */ export function clearedContextMarkerItem(): Record { return { type: "message", role: "user", content: "[context cleared]" }; } export type ClearSessionContextResult = { /** Active history rows superseded (active=true -> false). */ supersededItems: number; /** Position of the inserted neutral boundary marker. */ markerPosition: number; }; export class SessionContextBusyError extends Error { constructor(public readonly status: string) { super(`session is ${status}; Pause must settle before context can be cleared`); this.name = "SessionContextBusyError"; } } /** * Clear a session's conversation context in ONE transaction, audit-preserving * and idempotent: * * (a) supersede every active session_history_items row (active=true -> false). * Nothing is deleted — the full transcript stays as an audit trail, same * pattern as applyContextCompaction. * (b) insert ONE active neutral boundary marker at max(position)+1. Ordinary * inference reads only this canonical history store; SDK RunState remains * reserved for an approval that paused mid-turn, and the API forbids a * clear while such an approval or active turn exists. * * Also clears last_input_tokens because no provider has observed the new * context yet. * * Idempotent: a re-run supersedes the (now sole, already-marker) active row, * inserts another marker at the next position. The post-condition (one active * marker row) holds. */ export async function clearSessionContext( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const [workspace] = await tx .select({ id: schema.workspaces.id }) .from(schema.workspaces) .where(eq(schema.workspaces.id, input.workspaceId)) .for("update") .limit(1); if (!workspace) throw new Error(`Workspace not found: ${input.workspaceId}`); const [session] = await tx .select({ status: schema.sessions.status, activeTurnId: schema.sessions.activeTurnId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("no key update") .limit(1); if (!session) throw new Error(`Session not found: ${input.sessionId}`); if ( session.activeTurnId !== null || !["idle", "failed", "cancelled"].includes(session.status) ) { throw new SessionContextBusyError(session.status); } const supersededRows = await tx .update(schema.sessionHistoryItems) .set({ active: false }) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), eq(schema.sessionHistoryItems.active, true), ), ) .returning({ id: schema.sessionHistoryItems.id }); const [{ maxPosition } = { maxPosition: -1 }] = await tx .select({ maxPosition: sql`coalesce(max(${schema.sessionHistoryItems.position}), -1)`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), ), ); const markerPosition = Number(maxPosition) + 1; await tx .insert(schema.sessionHistoryItems) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: null, position: markerPosition, item: clearedContextMarkerItem(), active: true, }, "item", "itemCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionHistoryItems.workspaceId, schema.sessionHistoryItems.sessionId, schema.sessionHistoryItems.position, ], }); await tx .update(schema.sessions) .set({ lastInputTokens: null, updatedAt: new Date() }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { supersededItems: supersededRows.length, markerPosition }; }); }, ); } export async function countSessionHistoryItems( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ count: sql`count(*)`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), ), ); return Number(row?.count ?? 0); }); } /** * Set the operator /compact request flag. The worker honors it before the next * turn (forced portable compaction) and clears it. Idempotent: repeated * requests collapse to one pending compaction. An operator request always * relabels a pending request as `operator`; the label never changes what runs. */ export async function requestSessionCompaction( db: Database, workspaceId: string, sessionId: string, ): Promise<{ wakeRevision: number; temporalWorkflowId: string }> { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { const [session] = await scopedDb .select({ accountId: schema.sessions.accountId, temporalWorkflowId: schema.sessions.temporalWorkflowId, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .for("no key update") .limit(1); if (!session) throw new Error(`Session not found: ${sessionId}`); return await setSessionCompactionRequestInTransaction(scopedDb, { accountId: session.accountId, workspaceId, sessionId, temporalWorkflowId: session.temporalWorkflowId, trigger: "operator", }); }); } async function setSessionCompactionRequestInTransaction( scopedDb: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string | null; trigger: schema.CompactRequestTrigger; }, ): Promise<{ wakeRevision: number; temporalWorkflowId: string }> { await scopedDb .update(schema.sessions) .set({ compactRequested: true, compactRequestTrigger: input.trigger, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); const temporalWorkflowId = input.temporalWorkflowId ?? `session-${input.sessionId}`; const wakeRevision = await enqueueSessionWorkflowWakeInTransaction(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId, reason: "compaction_requested", }); return { wakeRevision, temporalWorkflowId }; } export type IdleSessionCompactionRequestResult = | { requested: true; wakeRevision: number; temporalWorkflowId: string } | { requested: false; reason: | "not_found" | "not_idle" | "child_session" | "already_requested" | "below_threshold" | "active_goal" | "input_wait" | "pending_delayed_wake"; }; /** * Request a `proactive` checkpoint for a session that just went idle at its * automatic compaction threshold, so the compaction runs now instead of in * front of the next message. It reuses the operator request exactly: the same * durable flag, workflow wake, and born-running `source="compaction"` * maintenance execution, never prompt-queue work. * * Everything is rechecked under the session row lock: the session must still * be idle with no active turn, be a root session, have no pending request, and * hold a provider-reported `last_input_tokens` at or above the threshold. A * session that already moved on (a queued or running turn) keeps its ordinary * pre-inference threshold check instead. A pending operator request is never * relabeled. * * A session with an active goal or a held `wait_for_input` is also left alone: * its next continuation or awaited input compacts at the ordinary threshold * check, and this request's wake must not pull that obligation's future-dated * wake (`goal_idle_backoff`, `session_input_wait_deadline`) forward or let * maintenance claim ahead of it. */ export async function requestIdleSessionCompactionIfDue( db: Database, input: { workspaceId: string; sessionId: string; thresholdTokens: number }, ): Promise { return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => { const [session] = await scopedDb .select({ accountId: schema.sessions.accountId, temporalWorkflowId: schema.sessions.temporalWorkflowId, status: schema.sessions.status, activeTurnId: schema.sessions.activeTurnId, parentSessionId: schema.sessions.parentSessionId, compactRequested: schema.sessions.compactRequested, lastInputTokens: schema.sessions.lastInputTokens, inputWaitTurnId: schema.sessions.inputWaitTurnId, inputWaitUntil: schema.sessions.inputWaitUntil, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("no key update") .limit(1); if (!session) return { requested: false, reason: "not_found" }; if (session.status !== "idle" || session.activeTurnId !== null) { return { requested: false, reason: "not_idle" }; } if (session.parentSessionId !== null) return { requested: false, reason: "child_session" }; if (session.compactRequested) return { requested: false, reason: "already_requested" }; const [activeGoal] = await scopedDb .select({ id: schema.sessionGoals.id }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), eq(schema.sessionGoals.status, "active"), ), ) .limit(1); if (activeGoal) return { requested: false, reason: "active_goal" }; const wait = await sessionInputWaitStateTx(scopedDb, input.workspaceId, input.sessionId, { inputWaitTurnId: session.inputWaitTurnId, inputWaitUntil: session.inputWaitUntil, }); if (wait.disposition === "held" || wait.disposition === "timeout") { return { requested: false, reason: "input_wait" }; } // The wake outbox holds one row per session and coalescing pulls an // undelivered wake's deadline to now. A future-dated undelivered wake // belongs to another producer's pacing (a retry or backoff); never move it. // The margin absorbs clock skew between the host that stamped an // immediate wake and the database. const [delayedWake] = await scopedDb .select({ sessionId: schema.sessionWorkflowWakeOutbox.sessionId }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), sql`${schema.sessionWorkflowWakeOutbox.wakeRevision} > ${schema.sessionWorkflowWakeOutbox.deliveredRevision}`, sql`${schema.sessionWorkflowWakeOutbox.nextAttemptAt} > now() + interval '5 seconds'`, ), ) .limit(1); if (delayedWake) return { requested: false, reason: "pending_delayed_wake" }; if ( !(input.thresholdTokens > 0) || session.lastInputTokens === null || session.lastInputTokens < input.thresholdTokens ) { return { requested: false, reason: "below_threshold" }; } const requested = await setSessionCompactionRequestInTransaction(scopedDb, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId, trigger: "proactive", }); return { requested: true, ...requested }; }); } /** Who asked for the pending compaction, or null when none is pending. A * request written by an older binary carries no label and reads as operator. */ export async function sessionCompactionRequestTrigger( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [session] = await scopedDb .select({ compactRequested: schema.sessions.compactRequested, compactRequestTrigger: schema.sessions.compactRequestTrigger, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (session?.compactRequested !== true) return null; return session.compactRequestTrigger ?? "operator"; }); } /** * Prepare a Codex remote_v2 session for a turn on another provider's model. * Without a Codex checkpoint in its active history the session switches to * portable compaction at once. With one, which only Codex can read, this * requests a forced compaction instead: the turn's pre-turn compaction * rebuilds a portable summary from the stored transcript and switches the * session in the same transaction that installs it, so a failed rebuild is * simply requested again by the next such turn. A portable session is left * untouched (null). With `attempt`, the write happens only while that exact * turn attempt still owns the session ("fenced" otherwise), so a stale or * superseded claim never converts the chat. */ export async function convertSessionToPortableCompactionForModelSwitch( db: Database, workspaceId: string, sessionId: string, attempt?: { turnId: string; executionGeneration: number; attemptId: string }, ): Promise< { codexCompactionMode: "remote_v2" | "portable"; compactRequested: boolean } | null | "fenced" > { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { if (attempt) { const fence = await lockTurnAttemptWriteFenceTx(scopedDb as unknown as Database, { workspaceId, sessionId, ...attempt, }); if (!fence.allowed) return "fenced"; } const checkpoint = sql`exists ( select 1 from session_history_items history where history.workspace_id = ${workspaceId} and history.session_id = ${sessionId} and history.active = true and history.item ->> 'type' = 'compaction' and jsonb_typeof(history.item -> 'encrypted_content') = 'string' and history.item ->> 'encrypted_content' <> '' )`; const [converted] = await scopedDb .update(schema.sessions) .set({ codexCompactionMode: sql`case when ${checkpoint} then 'remote_v2' else 'portable' end`, compactRequested: sql`${schema.sessions.compactRequested} or ${checkpoint}`, // A request this conversion creates is operator-labeled (NULL); only a // request already pending keeps its own label, so a stale label copied // by a fork can never relabel it. compactRequestTrigger: sql`case when ${schema.sessions.compactRequested} then ${schema.sessions.compactRequestTrigger} else null end`, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), eq(schema.sessions.codexCompactionMode, "remote_v2"), ), ) .returning({ codexCompactionMode: schema.sessions.codexCompactionMode, compactRequested: schema.sessions.compactRequested, }); if (!converted) return null; return { codexCompactionMode: converted.codexCompactionMode === "portable" ? "portable" : "remote_v2", compactRequested: converted.compactRequested, }; }); } /** Read the durable /compact request without consuming it. The exact current * turn attempt clears the flag in the same transaction that installs the new * active history, so a failed or superseded summarizer cannot lose the request. */ export async function isSessionCompactionRequested( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [session] = await scopedDb .select({ compactRequested: schema.sessions.compactRequested }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return session?.compactRequested === true; }); } /** * Persist the session's sandbox recovery descriptor (the small versioned * envelope used to reattach / snapshot-restore / rebuild the sandbox), * decoupled from the RunState blob. */ export async function upsertSandboxSessionEnvelope( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; envelope: Record; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .insert(schema.sandboxSessionEnvelopes) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, envelope: input.envelope, }, "envelope", "envelopeCodecVersion", ), ) .onConflictDoUpdate({ target: [ schema.sandboxSessionEnvelopes.workspaceId, schema.sandboxSessionEnvelopes.sessionId, ], set: withLosslessContentWriteVersion( { envelope: input.envelope, updatedAt: new Date() }, "envelope", "envelopeCodecVersion", ), }); }, ); } export async function getSandboxSessionEnvelope( db: Database, workspaceId: string, sessionId: string, ): Promise | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ envelope: schema.sandboxSessionEnvelopes.envelope, envelopeCodecVersion: schema.sandboxSessionEnvelopes.envelopeCodecVersion, }) .from(schema.sandboxSessionEnvelopes) .where( and( eq(schema.sandboxSessionEnvelopes.workspaceId, workspaceId), eq(schema.sandboxSessionEnvelopes.sessionId, sessionId), ), ) .limit(1); return row ? fromPostgresLosslessJson(row.envelope, row.envelopeCodecVersion) : null; }); } // ============================================================================ // Session recordings — the durable index for the "agent films itself proving // the fix" loop. One row per recording; insert at start, update at // finalize (available with the storage_key) or failure. Read-side feeds the // list route + the signed-URL replay route (storage_key is the source of truth). // ============================================================================ export type SessionRecordingState = (typeof schema.sessionRecordingStateValues)[number]; export type SessionRecordingMode = (typeof schema.sessionRecordingModeValues)[number]; export type SessionRecordingCodec = (typeof schema.sessionRecordingCodecValues)[number]; export type SessionRecordingRow = { id: string; workspaceId: string; sessionId: string; turnId: string | null; state: SessionRecordingState; mode: SessionRecordingMode; codec: SessionRecordingCodec; storageKey: string | null; sizeBytes: number | null; durationSeconds: number | null; width: number; height: number; reason: string | null; createdAt: Date; finalizedAt: Date | null; }; function mapRecording(row: typeof schema.sessionRecordings.$inferSelect): SessionRecordingRow { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, turnId: row.turnId, state: row.state, mode: row.mode, codec: row.codec, storageKey: row.storageKey, sizeBytes: row.sizeBytes === null || row.sizeBytes === undefined ? null : Number(row.sizeBytes), durationSeconds: row.durationSeconds === null || row.durationSeconds === undefined ? null : Number(row.durationSeconds), width: row.width, height: row.height, reason: row.reason === null ? null : fromPostgresLosslessText(row.reason, row.reasonCodecVersion), createdAt: row.createdAt, finalizedAt: row.finalizedAt, }; } export async function insertRecording( db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; turnId?: string | null; mode: SessionRecordingMode; codec: SessionRecordingCodec; width: number; height: number; reason?: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.sessionRecordings) .values( withLosslessContentWriteVersion( { id: input.id, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId ?? null, state: "recording", mode: input.mode, codec: input.codec, width: input.width, height: input.height, reason: input.reason ?? null, }, "reason", "reasonCodecVersion", ), ) .returning(); return mapRecording(row!); }, ); } export async function updateSessionRecording( db: Database, input: { accountId: string; workspaceId: string; recordingId: string; state: SessionRecordingState; storageKey?: string | null; sizeBytes?: number | null; durationSeconds?: number | null; reason?: string | null; finalized?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const set: Partial = { state: input.state, }; if (input.storageKey !== undefined) set.storageKey = input.storageKey; if (input.sizeBytes !== undefined) set.sizeBytes = input.sizeBytes; if (input.durationSeconds !== undefined) set.durationSeconds = input.durationSeconds; if (input.reason !== undefined) { set.reason = input.reason; set.reasonCodecVersion = LOSSLESS_CONTENT_CODEC_VERSION; } if (input.finalized || input.state === "available" || input.state === "failed") { set.finalizedAt = new Date(); } const [row] = await scopedDb .update(schema.sessionRecordings) .set(set) .where( and( eq(schema.sessionRecordings.workspaceId, input.workspaceId), eq(schema.sessionRecordings.id, input.recordingId), ), ) .returning(); return row ? mapRecording(row) : null; }, ); } /** * Hard-delete a recording row. Used to DISCARD an on-turn recording that captured * NO computer-use activity (a plain text turn): the row was inserted at * `beginRecording` (state "recording") but the turn never drove the desktop, so it * is removed entirely rather than surfaced as a phantom recording or a failure. No * other table FK-references session_recordings, so the delete is self-contained. */ export async function deleteRecording( db: Database, input: { accountId: string; workspaceId: string; recordingId: string; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .delete(schema.sessionRecordings) .where( and( eq(schema.sessionRecordings.workspaceId, input.workspaceId), eq(schema.sessionRecordings.id, input.recordingId), ), ); }, ); } /** * Close an attempt-owned recording that could not reach the atomic turn * settlement. The accepted recording.started event is the durable ownership * receipt: cleanup is allowed only for the exact turn generation and attempt * that created this recording id. No timeline event is emitted from this * hygiene path. */ export async function abandonRecordingForTurnAttempt( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; recordingId: string; disposition: "failed" | "discard"; reason: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [recording] = await tx .select({ id: schema.sessionRecordings.id }) .from(schema.sessionRecordings) .where( and( eq(schema.sessionRecordings.accountId, input.accountId), eq(schema.sessionRecordings.workspaceId, input.workspaceId), eq(schema.sessionRecordings.sessionId, input.sessionId), eq(schema.sessionRecordings.turnId, input.turnId), eq(schema.sessionRecordings.id, input.recordingId), eq(schema.sessionRecordings.mode, "on-turn"), inArray(schema.sessionRecordings.state, ["recording", "finalizing"]), ), ) .for("update") .limit(1); if (!recording) return false; const [started] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.turnGeneration, input.executionGeneration), eq(schema.sessionEvents.turnAttemptId, input.attemptId), eq(schema.sessionEvents.turnAssociation, "current"), eq(schema.sessionEvents.type, "recording.started"), eq(sql`${schema.sessionEvents.payload} ->> 'recordingId'`, input.recordingId), ), ) .limit(1); if (!started) return false; if (input.disposition === "discard") { await tx .delete(schema.sessionRecordings) .where(eq(schema.sessionRecordings.id, recording.id)); } else { await tx .update(schema.sessionRecordings) .set( withLosslessContentWriteVersion( { state: "failed", reason: input.reason.slice(0, 2_000), finalizedAt: new Date(), }, "reason", "reasonCodecVersion", ), ) .where(eq(schema.sessionRecordings.id, recording.id)); } return true; }), ); } export async function getSessionRecording( db: Database, workspaceId: string, recordingId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionRecordings) .where( and( eq(schema.sessionRecordings.workspaceId, workspaceId), eq(schema.sessionRecordings.id, recordingId), ), ) .limit(1); return row ? mapRecording(row) : null; }); } export async function listSessionRecordings( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionRecordings) .where( and( eq(schema.sessionRecordings.workspaceId, workspaceId), eq(schema.sessionRecordings.sessionId, sessionId), ), ) .orderBy(desc(schema.sessionRecordings.createdAt)); return rows.map(mapRecording); }); } // ============================================================================ // Channel-A interactive PTY sessions (P4.4) — the ptyId <-> exec-session-id map. // The ONLY new persistent state Channel A needs; FS/Git reads persist nothing. // ============================================================================ export type SandboxPtySessionRow = { id: string; accountId: string; workspaceId: string; sessionId: string; leaseId: string | null; sandboxGroupId: string | null; retainedProcessId: string | null; openAdmissionId: string | null; execSessionId: number | null; leaseEpoch: number; providerBackend: string | null; providerInstanceId: string | null; routeKind: "home" | "active" | null; routeTargetId: string | null; routeEpoch: number | null; cols: number; rows: number; shell: string; cwd: string; status: "open" | "closed"; openedBy: string; lastInputAt: string; createdAt: string; closedAt: string | null; }; export type SandboxPtyProcessIdentity = { leaseId: string; sandboxGroupId: string; retainedProcessId: string; openAdmissionId: string; execSessionId: number; leaseEpoch: number; providerBackend: string; providerInstanceId: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; }; export type SandboxOpenPtySessionRow = Omit< SandboxPtySessionRow, keyof SandboxPtyProcessIdentity | "status" > & SandboxPtyProcessIdentity & { status: "open" }; function mapPtySession(row: typeof schema.sandboxPtySessions.$inferSelect): SandboxPtySessionRow { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, leaseId: row.leaseId ?? null, sandboxGroupId: row.sandboxGroupId ?? null, retainedProcessId: row.retainedProcessId ?? null, openAdmissionId: row.openAdmissionId ?? null, execSessionId: row.execSessionId ?? null, leaseEpoch: row.leaseEpoch, providerBackend: row.providerBackend ?? null, providerInstanceId: row.providerInstanceId ?? null, routeKind: (row.routeKind as "home" | "active" | null) ?? null, routeTargetId: row.routeTargetId ?? null, routeEpoch: row.routeEpoch ?? null, cols: row.cols, rows: row.rows, shell: row.shell, cwd: row.cwd, status: row.status as "open" | "closed", openedBy: row.openedBy, lastInputAt: row.lastInputAt.toISOString(), createdAt: row.createdAt.toISOString(), closedAt: row.closedAt ? row.closedAt.toISOString() : null, }; } function mapOpenPtySession( row: typeof schema.sandboxPtySessions.$inferSelect, ): SandboxOpenPtySessionRow { const mapped = mapPtySession(row); if ( mapped.status !== "open" || mapped.leaseId === null || mapped.sandboxGroupId === null || mapped.retainedProcessId === null || mapped.openAdmissionId === null || mapped.execSessionId === null || mapped.execSessionId <= 0 || mapped.providerBackend === null || mapped.providerInstanceId === null || mapped.routeKind === null || mapped.routeEpoch === null ) { throw new Error("Open PTY row lacks exact retained-process identity"); } return mapped as SandboxOpenPtySessionRow; } function exactPtyIdentityPredicates(identity: SandboxPtyProcessIdentity): SQL[] { return [ eq(schema.sandboxPtySessions.leaseId, identity.leaseId), eq(schema.sandboxPtySessions.sandboxGroupId, identity.sandboxGroupId), eq(schema.sandboxPtySessions.retainedProcessId, identity.retainedProcessId), eq(schema.sandboxPtySessions.openAdmissionId, identity.openAdmissionId), eq(schema.sandboxPtySessions.execSessionId, identity.execSessionId), eq(schema.sandboxPtySessions.leaseEpoch, identity.leaseEpoch), eq(schema.sandboxPtySessions.providerBackend, identity.providerBackend), eq(schema.sandboxPtySessions.providerInstanceId, identity.providerInstanceId), eq(schema.sandboxPtySessions.routeKind, identity.routeKind), identity.routeTargetId === null ? isNull(schema.sandboxPtySessions.routeTargetId) : eq(schema.sandboxPtySessions.routeTargetId, identity.routeTargetId), eq(schema.sandboxPtySessions.routeEpoch, identity.routeEpoch), ]; } export async function insertPtySession( db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; identity: SandboxPtyProcessIdentity; cols: number; rows: number; shell: string; cwd: string; openedBy: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.sandboxPtySessions) .values({ id: input.id, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, leaseId: input.identity.leaseId, sandboxGroupId: input.identity.sandboxGroupId, retainedProcessId: input.identity.retainedProcessId, openAdmissionId: input.identity.openAdmissionId, execSessionId: input.identity.execSessionId, leaseEpoch: input.identity.leaseEpoch, providerBackend: input.identity.providerBackend, providerInstanceId: input.identity.providerInstanceId, routeKind: input.identity.routeKind, routeTargetId: input.identity.routeTargetId, routeEpoch: input.identity.routeEpoch, cols: input.cols, rows: input.rows, shell: input.shell, cwd: input.cwd, status: "open", openedBy: input.openedBy, }) .returning(); return mapOpenPtySession(row!); }, ); } /** Read an OPEN PTY row by ptyId. Returns null when absent or already closed. */ export async function getOpenPtySession( db: Database, input: { workspaceId: string; sessionId: string; ptyId: string }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sandboxPtySessions) .where( and( eq(schema.sandboxPtySessions.workspaceId, input.workspaceId), eq(schema.sandboxPtySessions.sessionId, input.sessionId), eq(schema.sandboxPtySessions.id, input.ptyId), eq(schema.sandboxPtySessions.status, "open"), ), ) .limit(1); return row ? mapOpenPtySession(row) : null; }); } /** Refresh activity/geometry only when the full retained-process identity still * matches. A numeric provider locator or PTY UUID alone is never authority. */ export async function updatePtySessionActivity( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; ptyId: string; identity: SandboxPtyProcessIdentity; cols?: number; rows?: number; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const set: Partial = { lastInputAt: new Date(), }; if (input.cols !== undefined) set.cols = input.cols; if (input.rows !== undefined) set.rows = input.rows; const [row] = await scopedDb .update(schema.sandboxPtySessions) .set(set) .where( and( eq(schema.sandboxPtySessions.workspaceId, input.workspaceId), eq(schema.sandboxPtySessions.sessionId, input.sessionId), eq(schema.sandboxPtySessions.id, input.ptyId), eq(schema.sandboxPtySessions.status, "open"), ...exactPtyIdentityPredicates(input.identity), ), ) .returning(); return row ? mapOpenPtySession(row) : null; }, ); } /** Mark a PTY closed (idempotent — a double close on a closed row is a no-op). */ export async function closePtySession( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; ptyId: string; identity: SandboxPtyProcessIdentity; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .update(schema.sandboxPtySessions) .set({ status: "closed", closedAt: new Date() }) .where( and( eq(schema.sandboxPtySessions.workspaceId, input.workspaceId), eq(schema.sandboxPtySessions.sessionId, input.sessionId), eq(schema.sandboxPtySessions.id, input.ptyId), eq(schema.sandboxPtySessions.status, "open"), ...exactPtyIdentityPredicates(input.identity), ), ) .returning(); return row ? mapPtySession(row) : null; }, ); } /** List a session's OPEN PTYs (reattach + reap). */ export async function listOpenPtySessions( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sandboxPtySessions) .where( and( eq(schema.sandboxPtySessions.workspaceId, workspaceId), eq(schema.sandboxPtySessions.sessionId, sessionId), eq(schema.sandboxPtySessions.status, "open"), ), ) .orderBy(desc(schema.sandboxPtySessions.createdAt)); return rows.map(mapOpenPtySession); }); } // ============================================================================ // Sandbox singleton lease — the SOLE enforcer of one-box-per-group (P1.1). // // Group-keyed (workspace_id, sandbox_group_id) from the start. The sole // double-spawn guard is the UNIQUE (workspace_id, sandbox_group_id) index + // plain SELECT … FOR UPDATE (block, NOT skip-locked) + the cold->warming CAS // inside that row lock. lease_epoch is integer (returns a JS number) but every // read is Number()-coerced defensively. Mirrors the atomic turn-admission // withWorkspaceRls/withRlsContext -> scopedDb.transaction -> tx.execute(sql``) // pattern (the row type goes on the sql tag, not on .execute). // ============================================================================ export type SandboxLeaseLiveness = "cold" | "warming" | "warm" | "draining"; export type LeaseHolderKind = "turn" | "viewer" | "direct" | "process" | "interaction"; export type SandboxProviderExistence = | "not_created" | "creating" | "exists" | "missing" | "unknown"; export type SandboxArchiveAvailability = "none" | "available" | "unverified" | "invalid"; export type SandboxRestoreStatus = | "not_required" | "pending" | "restoring" | "verifying" | "ready" | "degraded" | "unrecoverable"; export type SandboxWorkspaceReadiness = | "unknown" | "not_ready" | "ready" | "degraded" | "unrecoverable"; export type SandboxTarArchiveRevision = TarWorkspaceArchiveDescriptor; export type SandboxNativeSnapshotRevision = NativeSnapshotDescriptor; export type SandboxArchiveRevision = WorkspaceArchiveDescriptor; export type SandboxRecoveryState = { provider: { status: SandboxProviderExistence; instanceId: string | null; observedAt: string | null; diagnostic?: string; }; archive: { status: SandboxArchiveAvailability; current: SandboxArchiveRevision | null; previous: SandboxArchiveRevision | null; }; restore: { status: SandboxRestoreStatus; rematerializationId: string | null; selectedRevision: string | null; startedAt: string | null; completedAt: string | null; failureCode?: string; retryable?: boolean; }; workspace: { status: SandboxWorkspaceReadiness; verifiedRevision: string | null; verifiedAt: string | null; }; /** Provider-specific proof that an elected recovery owner may replace only * the disposable execution wrapper while retaining the same workspace. */ continuity?: SandboxProviderContinuityRecovery; /** A provider disappeared while a non-cancellable capture response could * still settle. The cold lease retains this exact source/lineage receipt so a * late verified archive can repair recovery without reopening the old box. */ lateArchiveCapture?: { version: 1; captureId: string; providerRequestId: string; sourceLeaseId: string; sourceLeaseEpoch: number; sourceInstanceId: string; sourceWorkspaceGeneration: number; recordedAt: string; }; }; export type SandboxProviderCreateAttempt = { version: 1; operationId: string; leaseEpoch: number; providerBindingKey: string; rematerializationId: string | null; selectedRevision: string | null; imageId: string | null; imageRef: string | null; appId: string; providerName: string; requestSha256: string; startedAt: string; instanceId: string | null; }; // The snake_case raw shape returned by the raw sql`` lease queries. lease_epoch // comes back as a number for an integer column, but we type it number|string // and Number()-coerce so the same code is correct regardless of column type. // Typed with an index signature so it satisfies db.execute>. type LeaseRow = { provider_create_attempt?: SandboxProviderCreateAttempt | null; unobservable_command_drain_ids?: string[] | null; id: string; account_id: string; workspace_id: string; sandbox_group_id: string; liveness: SandboxLeaseLiveness; refcount: number; turn_holders: number; viewer_holders: number; instance_id: string | null; backend: string; os: string; image: string | null; rig_version_id: string | null; data_plane_url: string | null; terminal_data_plane_url: string | null; controller_data_plane_url: string | null; lease_epoch: number | string; workspace_generation: number | string; archive_generation: number | string | null; archive_capture_id: string | null; archive_capture_operation_id: string | null; archive_capture_provider_request_id: string | null; archive_capture_provider_replay_safe: boolean; archive_capture_takeover_safe: boolean; archive_capture_attempt: number | string | null; archive_capture_generation: number | string | null; archive_capture_started_at: Date | string | null; archive_capture_deadline_at: Date | string | null; /** Transaction-local PostgreSQL-clock projection used only by bounded waiters. */ archive_capture_remaining_ms?: number | string | null; archive_capture_published_at: Date | string | null; archive_capture_concurrent_capture_id?: string | null; untracked_writer_since?: Date | string | null; drain_capture_failures?: number | string | null; drain_capture_failure_epoch?: number | string | null; drain_capture_first_failed_at?: Date | string | null; drain_capture_last_failed_at?: Date | string | null; deadline_forced_admission_ids?: string[] | null; reaper_hold_id: string | null; reaper_hold_until: Date | string | null; reaper_hold_reason: string | null; resume_backend_id: string | null; resume_state: Record | null; last_meter_at: Date | string | null; last_meter_tick: number; provider_created_at: Date | string | null; provider_deadline_at: Date | string | null; rotation_requested_at: Date | string | null; rotation_reason: "provider_deadline" | "operator" | "teardown_claim" | null; group_end_requested_at?: Date | string | null; compute_asleep_since?: Date | string | null; compute_handing_off_since?: Date | string | null; current_checkpoint_artifact_id: string | null; previous_checkpoint_artifact_id: string | null; shared_preparation_lease_epoch: number | string | null; shared_preparation_instance_id: string | null; shared_preparation_spec_hash: string | null; shared_preparation_status: "running" | "completed" | "failed" | null; shared_preparation_claim_id: string | null; shared_preparation_owner_attempt_id: string | null; shared_preparation_attempt: number | string | null; shared_preparation_revision: number | string; shared_preparation_started_at: Date | string | null; shared_preparation_deadline_at: Date | string | null; shared_preparation_settled_at: Date | string | null; expires_at: Date | string; } & Record; export interface LeaseSnapshot { /** Consent is not archive completeness; begin/commit revalidate the receipt. */ historicalRecoveryAuthorized?: boolean; /** Exact audited decision to continue a definitively lost workspace on a new * EMPTY box. The spawner hydrates nothing and commits in fresh mode. */ freshWorkspaceRecoveryId?: string; /** Exact idle-only enrollment. Commands remain active until provider stop. */ unobservableCommandDrainIds?: string[] | null; id: string; sandboxGroupId: string; liveness: SandboxLeaseLiveness; refcount: number; turnHolders: number; viewerHolders: number; instanceId: string | null; backend: string; os: string; // The container image the group box runs (Modal image ref / docker image). Null // for a legacy/cold row (image unknown). Shared state: all the box's sessions run // this image; a resume resolving a different image conflicts (B3). image: string | null; // The frozen rig version the group box was created under (M3). Like `image`, // shared state: a resume resolving a DIFFERENT rig_version_id conflicts (solo // rotates through durable capture, N-holders throw SandboxRigConflictError). Null = rig unknown // (legacy/cold row or a rig-less session), which never conflicts. rigVersionId: string | null; dataPlaneUrl: string | null; // The cached ttyd pty-ws tunnel URL (7681), separate from dataPlaneUrl (the // 6080 desktop tunnel). Null until mintTerminalStream resolves + records it. terminalDataPlaneUrl: string | null; /** Cached browserd controller tunnel (7682), fenced to this lease epoch and * provider instance. Null until the first controller provisioning/resolution. */ controllerDataPlaneUrl: string | null; leaseEpoch: number; /** Monotonic filesystem mutation intent for the exact live workspace. */ workspaceGeneration: number; /** Generation captured by the current verified archive, or null when no * generation-complete archive exists. */ archiveGeneration: number | null; /** True only when the current verified archive represents the exact current * workspace generation. This is numeric/boolean truth, never archive content. */ archiveComplete: boolean; /** Earliest attach of a viewer or interaction (writers that bypass * generation admissions) that no capture taken with none attached has * covered yet. Null when every such write is in the archive. */ untrackedWriterSince: Date | null; /** Compute only: since when the current sandbox's host has said it is * handing it off, during which it may refuse wakes for a short while. Null * while it says nothing of the kind. */ computeHandingOffSince?: Date | null; /** Consecutive settled drain snapshot failures of THIS lease epoch since * its last published save (zero after a new box or a save). Drives the * drain retry backoff and its alerts. */ drainCaptureFailures?: SandboxDrainCaptureFailures; /** Exact provider capture currently holding the lease-local admission gate. */ archiveCapture: { id: string; operationId: string; providerRequestId: string; providerReplaySafe: boolean; takeoverSafe: boolean; attempt: number; workspaceGeneration: number; startedAt: Date; deadlineAt: Date; /** Durable proof that this exact draining capture already published a * verified current-generation archive. Null while capture is outstanding. */ publishedAt: Date | null; } | null; /** Bounded exact operator hold. Active holds stop reaper capture/teardown but * deliberately do not stop a user from re-arming a resumable drain. */ reaperHold: { id: string; until: Date; reason: string; } | null; resumeBackendId: string | null; resumeState: Record | null; /** Provider/archive/restore/workspace truth, deliberately separate from the * lease liveness and epoch fields above. Legacy envelopes project to * conservative unknown/unverified values. */ recovery: SandboxRecoveryState; providerCreateAttempt?: SandboxProviderCreateAttempt | null; /** Conservative provider creation clock. Modal's hard timeout is measured * from this instant and cannot be extended by resume. */ providerCreatedAt: Date | null; /** Durable deadline for replacing this physical provider instance. */ providerDeadlineAt: Date | null; /** Once set, new holders and new filesystem mutations are fenced while the * current holders quiesce and the reaper creates a successor. */ rotationRequestedAt: Date | null; rotationReason: "provider_deadline" | "operator" | "teardown_claim" | null; /** A chat or workspace deletion ended this compute lease's group: its * sandbox is deleted without a workspace capture. */ groupEndRequestedAt: Date | null; currentCheckpointArtifactId: string | null; previousCheckpointArtifactId: string | null; expiresAt: Date; } export interface LiveModalSandboxLeaseAttribution { leaseId: string; workspaceId: string; sandboxGroupId: string; instanceId: string | null; liveness: SandboxLeaseLiveness; } /** * The named, explicit opt-out from the organization plan limits. Only a test * fixture that exercises lease mechanics without plan bounds may use it; * every product caller passes the deployment's limits (sandboxPlanLimits). */ export type SandboxPlanLimitsOptOut = "unbounded_test_fixture"; /** * acquireLease input. `sandboxPlanLimits` is required, so no caller can start * or keep a box outside the plan, standing and fleet bounds by omission. */ export type AcquireLeaseInput = Omit & { /** Organization-wide limits by plan tier (sandboxPlanLimits(settings)), or * the named test-fixture opt-out. */ sandboxPlanLimits: SandboxPlanLimits | SandboxPlanLimitsOptOut; }; interface AcquireLeaseAdmissionInput { accountId: string; workspaceId: string; // The group's identity (sessions.sandbox_group_id; == session id for a // singleton group). The lease is per-group, not per-session. sandboxGroupId: string; kind: LeaseHolderKind; // Globally unique durable turn-attempt id (turn) | viewer connection id // (viewer). A workflow-local activity id is not a valid turn holder id. holderId: string; subjectId?: string | null; // the attributing session within the group /** Viewer holders only (0281): the authenticated viewer subject recorded on * the holder row - identity only, never a secret value. */ viewerSubjectId?: string; /** Viewer holders only (0281): the session authority epoch observed at * attach, mirrored into the scoped stream token's claims. */ viewerAuthorityEpoch?: number; backend: string; // sessions.sandbox_backend /** Explicit compute policy at this admission boundary. Omission is legacy * usage-only; only a priced credits backend needs prepaid admission. */ warmBilling?: { mode: "usage_only" | "shadow" | "credits"; rateMicrosPerSecond: number }; os?: string; // default 'linux' // The container image this run resolves (Modal image ref / docker image). Stamped on // the cold-create + folded onto a warming/CAS; a warm/draining/warming box already // running a DIFFERENT image is a shared-state conflict (B3): a SOLO holder requests // durable capture-and-drain rotation, N-holders throw SandboxImageConflictError. Omitted // (null/undefined) -> image is not enforced (legacy/cold rows, selfhosted). image?: string | null; /** Deployment/workspace pins select only a cold-create image. Reuse preserves * the existing warming/warm/draining group's image under the lease row lock. * Omission retains required image matching for explicit image changes (B3). * Capture, rotation, epoch and rig-version fences remain independent. */ imagePolicy?: "require_match" | "new_creates_only"; /** Direct control of an already-owned interaction instance. Admit only that * live provider, retaining its image across deployment changes. Never spawn * or rotate a replacement for this request. Capture/rotation fences still apply. */ retainedInstanceId?: string; // The frozen rig version this run rides (M3). Stamped on the cold-create + CAS // and conflicted exactly like `image`: a live multi-holder box under a DIFFERENT // rig version throws SandboxRigConflictError; a solo holder requests durable // capture-and-drain rotation. Omitted (null/undefined) -> rig is not enforced (rig-less // sessions never stamp or conflict; legacy/cold rows read null = compatible). rigVersionId?: string | null; leaseTtlMs: number; // refresh window for expires_at (turn-heartbeat cadence) // Expiry stamped only while a cold->warming spawner is allowed to create the // provider box before any instance_id exists. Warm/draining/attached refreshes // must continue using leaseTtlMs. warmingLeaseTtlMs?: number; // Optional epoch fence for a re-establishing turn holder: when set, the // turn-arrival increment is gated on lease_epoch == expectedEpoch (split-brain). expectedEpoch?: number; /** Bounded wait for an exact provider-native capture claim to settle. The * transaction is released between retries; every retry re-reads the lease. * The same wait also covers a requested provider rotation. The legacy field * name is retained at the API boundary so rolling workers remain compatible. */ captureWaitMs?: number; /** Optional owner cancellation for the transition wait. No holder exists * while a capture/rotation fence is observed, so cancellation is leak-free. */ waitSignal?: AbortSignal; /** Viewer holders only: the most boxes this workspace may keep warm with a * viewer and no turn holder. A new viewer that would start, re-arm or adopt * one more such box is refused with SandboxViewerBoxLimitError; joining a box * another viewer or a turn already holds is always admitted. Omitted or 0 = * no limit. */ viewerOnlyBoxLimit?: number; /** Organization-wide limits by plan tier (resolveSandboxPlanTier). Viewer * holders are refused beyond the tier's viewer-only limits with * SandboxViewerBoxLimitError; electing a new box beyond its running-box * limit is refused (non-turn holders) or capacity-blocked (turns). Omitted * only for the explicit test-fixture opt-out (AcquireLeaseInput). */ sandboxPlanLimits?: SandboxPlanLimits; /** Whether this deployment has subscription plans * (settings.subscriptionPlansEnabled). Without them a plan-less * organization (`none`) is not unpaid: none of the unpaid-only bounds or * fleet limits apply to it (sandboxPlanTierUnpaid). Omitted = on. */ subscriptionPlansEnabled?: boolean; /** Fleet-wide bounds on unpaid compute (OPENGENI_SANDBOX_FLEET_LIMITS_JSON), * applied with sandboxPlanLimits to a new box of an unpaid organization: * the young-organization running limit, the unpaid running cap and box-time * budget, and fleet pressure. Omitted = none. */ sandboxFleetLimits?: SandboxFleetLimits; /** The person on whose behalf the box is held (`user:`): the viewer, * the terminal or browser user, or the human who started the turn. With * sandboxPlanLimits, their other organizations count toward the per-person * bounds and a restricted one restricts this organization too * (resolveSandboxComputeStanding). Defaults to viewerSubjectId. */ actingSubjectId?: string | null; /** Called when a standing read failed and admission fell back (fails * open); callers record it. Without it the fallback is logged. */ onComputeStandingFallback?: SandboxComputeStandingFallback | undefined; /** Viewer holders only: for this long after the reaper released a box's * viewers for the viewer idle window, refuse (`viewer_idle`) an attach to * it unless the attach reports interaction after that release or a turn * used the session since. After it, any attach is admitted, so an older * client or another person can warm the box again. The person-facing attach * route sets it to the idle window when the idle drain is on; 0 or omitted * never refuses. */ viewerIdleReattachRefusalMs?: number; /** Viewer holders only: how long ago the attaching page last saw real user * interaction, when the client reports it (see * normalizeViewerInteractionAgeMs). Recorded on the holder. */ viewerInteractionAgeMs?: number | null; } export type AcquireLeaseResult = // Caller WON the cold->warming CAS: it is the spawner (any pool worker). Must // resume-by-id from resume_state, expose the stream port, then call // commitWarmingToWarm. No owner process is started. // // `sandboxPlanTier` is the organization's plan tier when the admission // resolved it (sandboxPlanLimits given): the spawner creates the box with // that tier's resource ceilings (settingsForSandboxPlanTier). | { role: "spawner"; lease: LeaseSnapshot; sandboxPlanTier?: string; sandboxPaidHistory?: true } // Box live or being built by someone else: attach (and, for warming, wait). | { role: "attached"; lease: LeaseSnapshot; sandboxPlanTier?: string; sandboxPaidHistory?: true } // Re-armed a draining lease back to warm (box never torn down). | { role: "rearmed"; lease: LeaseSnapshot } // Durable recovery truth says this cold group cannot safely materialize. No // holder is registered and no provider create is licensed. | { role: "blocked"; code: "restore_degraded" | "restore_unrecoverable"; lease: LeaseSnapshot; } // A true epoch supersession is distinct from an in-progress lifecycle // transition. Capture/rotation fences are transient and callers wait/retry; // only `superseded` means this exact epoch can never be acquired. | { role: "fenced"; reason: | "superseded" | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress" // A turn electing a new box while its organization already runs the // most boxes its plan allows. No holder is registered and no provider // create is licensed; the turn parks and retries later. | "organization_sandbox_capacity"; lease: LeaseSnapshot; /** organization_sandbox_capacity only: the plan's running-box limit. */ organizationBoxLimit?: number; /** Remaining durable capture budget from PostgreSQL's clock. Present only * for an exact active capture; callers cap it at the lifecycle ceiling. */ captureRemainingMs?: number; }; export type SandboxSharedPreparationSnapshot = { status: "running" | "completed" | "failed"; leaseEpoch: number; instanceId: string; specHash: string; claimId: string; ownerAttemptId: string; attempt: number; revision: number; startedAt: Date; deadlineAt: Date; settledAt: Date | null; }; export type ClaimSandboxSharedPreparationInput = { accountId: string; workspaceId: string; sandboxGroupId: string; expectedLeaseEpoch: number; expectedInstanceId: string; specHash: string; holderId: string; claimId: string; ownerAttemptId: string; timeoutMs: number; }; export type ClaimSandboxSharedPreparationResult = | { role: "owner" | "joined" | "reused"; preparation: SandboxSharedPreparationSnapshot; } | { role: "fenced"; lease: LeaseSnapshot | null }; function validateSandboxSharedPreparationIdentity(input: ClaimSandboxSharedPreparationInput): void { if (!Number.isSafeInteger(input.expectedLeaseEpoch) || input.expectedLeaseEpoch < 0) { throw new Error("Sandbox shared preparation lease epoch is invalid"); } if (!input.expectedInstanceId.trim()) { throw new Error("Sandbox shared preparation provider instance is invalid"); } if (!input.holderId.trim()) { throw new Error("Sandbox shared preparation lease holder is invalid"); } if (!/^sha256:[0-9a-f]{64}$/u.test(input.specHash)) { throw new Error("Sandbox shared preparation specification hash is invalid"); } if ( !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test( input.claimId, ) ) { throw new Error("Sandbox shared preparation claim id is invalid"); } if ( !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test( input.ownerAttemptId, ) ) { throw new Error("Sandbox shared preparation owner attempt id is invalid"); } if ( !Number.isSafeInteger(input.timeoutMs) || input.timeoutMs < 1_000 || input.timeoutMs > 3_600_000 ) { throw new Error("Sandbox shared preparation timeout is invalid"); } } function sandboxSharedPreparationFromLeaseRow( row: LeaseRow, ): SandboxSharedPreparationSnapshot | null { if ( row.shared_preparation_status === null || row.shared_preparation_lease_epoch === null || row.shared_preparation_instance_id === null || row.shared_preparation_spec_hash === null || row.shared_preparation_claim_id === null || row.shared_preparation_owner_attempt_id === null || row.shared_preparation_attempt === null || row.shared_preparation_started_at === null || row.shared_preparation_deadline_at === null ) { return null; } return { status: row.shared_preparation_status, leaseEpoch: Number(row.shared_preparation_lease_epoch), instanceId: row.shared_preparation_instance_id, specHash: row.shared_preparation_spec_hash, claimId: row.shared_preparation_claim_id, ownerAttemptId: row.shared_preparation_owner_attempt_id, attempt: Number(row.shared_preparation_attempt), revision: Number(row.shared_preparation_revision), startedAt: row.shared_preparation_started_at instanceof Date ? row.shared_preparation_started_at : new Date(row.shared_preparation_started_at), deadlineAt: row.shared_preparation_deadline_at instanceof Date ? row.shared_preparation_deadline_at : new Date(row.shared_preparation_deadline_at), settledAt: row.shared_preparation_settled_at === null ? null : row.shared_preparation_settled_at instanceof Date ? row.shared_preparation_settled_at : new Date(row.shared_preparation_settled_at), }; } function sandboxSharedPreparationMatches( row: LeaseRow, input: Pick< ClaimSandboxSharedPreparationInput, "expectedLeaseEpoch" | "expectedInstanceId" | "specHash" >, ): boolean { return ( Number(row.shared_preparation_lease_epoch) === input.expectedLeaseEpoch && row.shared_preparation_instance_id === input.expectedInstanceId && row.shared_preparation_spec_hash === input.specHash ); } /** * Claim, join, or reuse immutable setup for one exact physical sandbox. The * provider operation remains outside the transaction; the claim deadline and * box-local idempotency marker make a lost owner recoverable without sharing * any turn-private credential or file material. */ export async function claimSandboxSharedPreparation( db: Database, input: ClaimSandboxSharedPreparationInput, ): Promise { validateSandboxSharedPreparationIdentity(input); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || row.liveness !== "warm" || Number(row.lease_epoch) !== input.expectedLeaseEpoch || row.instance_id !== input.expectedInstanceId ) { return { role: "fenced" as const, lease: row ? mapLeaseRow(row) : null, }; } const holderRows = await tx.execute<{ present: boolean }>(sql` select exists ( select 1 from sandbox_lease_holders where lease_id = ${row.id} and kind = 'turn' and holder_id = ${input.holderId} ) as present `); if (holderRows[0]?.present !== true) { return { role: "fenced" as const, lease: mapLeaseRow(row) }; } const current = sandboxSharedPreparationFromLeaseRow(row); const exact = sandboxSharedPreparationMatches(row, input); if (exact && current?.status === "completed") { return { role: "reused" as const, preparation: current }; } if (exact && current?.status === "running" && current.deadlineAt.getTime() > Date.now()) { return { role: current.claimId === input.claimId ? ("owner" as const) : ("joined" as const), preparation: current, }; } const updatedRows = await tx.execute(sql` update sandbox_leases set shared_preparation_lease_epoch = ${input.expectedLeaseEpoch}, shared_preparation_instance_id = ${input.expectedInstanceId}, shared_preparation_spec_hash = ${input.specHash}, shared_preparation_status = 'running', shared_preparation_claim_id = ${input.claimId}, shared_preparation_owner_attempt_id = ${input.ownerAttemptId}, shared_preparation_attempt = ${exact ? Number(row.shared_preparation_attempt ?? 0) + 1 : 1}, shared_preparation_revision = shared_preparation_revision + 1, shared_preparation_started_at = now(), shared_preparation_deadline_at = now() + (${String(input.timeoutMs)} || ' milliseconds')::interval, shared_preparation_settled_at = null, updated_at = now() where id = ${row.id} and lease_epoch = ${input.expectedLeaseEpoch} and instance_id = ${input.expectedInstanceId} and liveness = 'warm' returning * `); const updated = updatedRows[0]; return updated ? { role: "owner" as const, preparation: sandboxSharedPreparationFromLeaseRow(updated)!, } : { role: "fenced" as const, lease: mapLeaseRow(row) }; }), ); } export async function readSandboxSharedPreparation( db: Database, input: Omit, ): Promise< { status: "available"; preparation: SandboxSharedPreparationSnapshot } | { status: "fenced" } > { if (!/^sha256:[0-9a-f]{64}$/u.test(input.specHash)) { throw new Error("Sandbox shared preparation specification hash is invalid"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` select lease.* from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and exists ( select 1 from sandbox_lease_holders holder where holder.lease_id = lease.id and holder.kind = 'turn' and holder.holder_id = ${input.holderId} ) `); const row = rows[0]; const preparation = row ? sandboxSharedPreparationFromLeaseRow(row) : null; if ( !row || row.liveness !== "warm" || Number(row.lease_epoch) !== input.expectedLeaseEpoch || row.instance_id !== input.expectedInstanceId || !preparation || !sandboxSharedPreparationMatches(row, input) ) { return { status: "fenced" as const }; } return { status: "available" as const, preparation }; }, ); } export async function settleSandboxSharedPreparation( db: Database, input: Omit & { outcome: "completed" | "failed"; }, ): Promise { if (!/^sha256:[0-9a-f]{64}$/u.test(input.specHash)) { throw new Error("Sandbox shared preparation specification hash is invalid"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set shared_preparation_status = ${input.outcome}, shared_preparation_revision = shared_preparation_revision + 1, shared_preparation_settled_at = now(), updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'warm' and lease_epoch = ${input.expectedLeaseEpoch} and instance_id = ${input.expectedInstanceId} and shared_preparation_lease_epoch = ${input.expectedLeaseEpoch} and shared_preparation_instance_id = ${input.expectedInstanceId} and shared_preparation_spec_hash = ${input.specHash} and shared_preparation_claim_id = ${input.claimId} and shared_preparation_status = 'running' and exists ( select 1 from sandbox_lease_holders holder where holder.lease_id = sandbox_leases.id and holder.kind = 'turn' and holder.holder_id = ${input.holderId} ) returning id `); return rows.length === 1; }, ); } // Thrown by callers that treat a fenced/superseded epoch as an error path. export class SandboxLeaseSupersededError extends Error { constructor( public readonly sandboxGroupId: string, public readonly leaseEpoch: number, public readonly diagnostic?: { backend: string; instanceId: string | null; liveness: SandboxLeaseLiveness; }, ) { super( `Sandbox lease superseded for group ${sandboxGroupId} (epoch ${leaseEpoch}` + `${diagnostic ? `, backend ${diagnostic.backend}, instance ${diagnostic.instanceId ?? "none"}, ${diagnostic.liveness}` : ""})`, ); this.name = "SandboxLeaseSupersededError"; } } export class SandboxLeaseTransitionError extends Error { readonly name = "SandboxLeaseTransitionError"; constructor( public readonly sandboxGroupId: string, public readonly leaseEpoch: number, public readonly reason: | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress" | "organization_sandbox_capacity", public readonly backend: string, public readonly instanceId: string | null, public readonly liveness: SandboxLeaseLiveness, /** organization_sandbox_capacity only: the plan's running-box limit. */ public readonly organizationBoxLimit?: number, ) { super( `Sandbox lifecycle transition still in progress for group ${sandboxGroupId} ` + `(epoch ${leaseEpoch}, reason ${reason}, backend ${backend}, ` + `instance ${instanceId ?? "none"}, ${liveness})`, ); } } export type SandboxViewerForceDrainReason = "balance" | "warm_cap"; export class SandboxViewerAdmissionBlockedError extends Error { readonly name = "SandboxViewerAdmissionBlockedError"; constructor( public readonly workspaceId: string, public readonly sandboxGroupId: string, public readonly reason: SandboxViewerForceDrainReason | "viewer_idle", ) { super( reason === "balance" ? "Sandbox viewer admission is blocked because the workspace has no managed credits" : reason === "viewer_idle" ? "Sandbox viewer admission is blocked because the sandbox was stopped after its page went unused; interact with the page to resume it" : "Sandbox viewer admission is blocked because the workspace warm allowance is exhausted", ); } } /** * A viewer would start or re-arm one more box that no turn holds, and the * workspace already keeps `limit` such viewer-only boxes warm. Turn-held boxes * never count and are never refused: this bounds compute a viewer alone keeps * running, not agent work. */ export type SandboxViewerBoxLimitScope = "workspace" | "organization" | "member"; export class SandboxViewerBoxLimitError extends Error { readonly name = "SandboxViewerBoxLimitError"; constructor( public readonly workspaceId: string, public readonly sandboxGroupId: string, public readonly limit: number, public readonly scope: SandboxViewerBoxLimitScope = "workspace", ) { super( `Sandbox viewer admission is blocked because the ${ scope === "member" ? "member" : scope } already keeps ${limit} sandboxes warm with no running task`, ); } } /** * Why a sandbox was refused under the plan's compute bounds: * * - `running`: one more box would exceed the organization's running-box * limit (`limit` boxes); * - `person_running`: the same across the acting person's limited * organizations (`limit` boxes); * - `closed`: the tier allows no sandbox (a held or denied organization that * has not paid); * - `daily_budget`: the organization or the acting person used today's box * time (`limit` seconds), until the next UTC day; * - `young_running`: an unpaid organization in its first day (fleet limits) * already runs `limit` boxes; * - `young_box_time`: an unpaid organization in its first day used the box * time new organizations get (`limit` seconds); * - `young_turnless`: an unpaid organization in its first day that never * started a turn used the box time it gets before one (`limit` seconds); * only holders other than a turn are refused, and only to start a box that * is not running (joining a running box works), so starting a chat works; * - `fleet_busy`: unpaid organizations together already run as many boxes as * the fleet allows (`limit`), or the fleet is under pressure; * - `fleet_daily_budget`: unpaid organizations together used today's fleet * box time (`limit` seconds), until the next UTC day; * - `card_required`: the card verification gate is on and this unpaid * organization has no verified card (its own, or one its acting owner * verified in another organization they run); only starting a box that is * not running is refused, so joining a running box works. */ export type SandboxOrganizationBoxLimitReason = | "running" | "person_running" | "closed" | "daily_budget" | "young_running" | "young_box_time" | "young_turnless" | "fleet_busy" | "fleet_daily_budget" | "card_required"; /** Refusals that come from the shared capacity of every unpaid organization * rather than the organization's own limits. */ export const SANDBOX_FLEET_REFUSAL_REASONS: readonly SandboxOrganizationBoxLimitReason[] = [ "fleet_busy", "fleet_daily_budget", ]; /** The person-facing explanation of a SandboxOrganizationBoxLimitError. */ export function sandboxOrganizationBoxLimitMessage( reason: SandboxOrganizationBoxLimitReason, limit: number, ): string { switch (reason) { case "closed": return "Sandboxes aren't available for this organization. Add credit or choose a paid plan to use them."; case "daily_budget": return `This organization (or you, across your organizations) has used today's ${Math.round( limit / 3600, )} sandbox hours on the Free plan. Sandboxes start again after midnight UTC; add credit or choose a paid plan to keep working now.`; case "person_running": return `You already run ${limit} sandboxes across your organizations, the most the Free plan allows; close one or wait for a task to finish`; case "running": return `Your organization already runs ${limit} sandboxes, the most its plan allows; close one or wait for a task to finish`; case "young_running": return `New organizations on the Free plan run ${limit === 1 ? "one sandbox" : `${limit} sandboxes`} at a time during their first day; close one or wait for a task to finish, or add credit to run more`; case "young_box_time": return `New organizations on the Free plan can use ${Math.round( limit / 3600, )} sandbox hours during their first day, and this one has. Sandboxes start again when it is a day old; add credit or choose a paid plan to keep working now.`; case "young_turnless": return `New organizations on the Free plan get ${Math.max( 1, Math.round(limit / 60), )} minutes of sandbox time before their first chat. Start a chat to keep using the sandbox, or add credit or choose a paid plan.`; case "fleet_busy": return "Free sandboxes are at capacity right now. Try again in a few minutes, or add credit or choose a paid plan to start one now."; case "fleet_daily_budget": return "Free sandboxes have reached today's limit. They start again after midnight UTC; add credit or choose a paid plan to start one now."; case "card_required": return "Sandboxes on the Free plan need a verified card. Add a card to continue; you won't be charged."; } } /** * A sandbox refused under the plan's compute bounds (see * SandboxOrganizationBoxLimitReason). Raised for holders that cannot wait * (viewer, direct, interaction) and, for `closed` and `daily_budget`, for a * turn that does not already hold the box: those do not free on their own, * so the turn fails with this message. A turn beyond a running-box limit * instead parks until a slot frees. */ export class SandboxOrganizationBoxLimitError extends Error { readonly name = "SandboxOrganizationBoxLimitError"; /** `sandbox_capacity_unpaid_busy` for the shared unpaid capacity, which * frees later; `sandbox_card_required` until the owner verifies a card; * `sandbox_compute_unavailable` for the organization's other bounds. */ readonly code: | "sandbox_compute_unavailable" | "sandbox_capacity_unpaid_busy" | "sandbox_card_required"; constructor( public readonly workspaceId: string, public readonly sandboxGroupId: string, public readonly limit: number, public readonly reason: SandboxOrganizationBoxLimitReason = "running", ) { super(sandboxOrganizationBoxLimitMessage(reason, limit)); this.code = SANDBOX_FLEET_REFUSAL_REASONS.includes(reason) ? "sandbox_capacity_unpaid_busy" : reason === "card_required" ? "sandbox_card_required" : "sandbox_compute_unavailable"; } } /** An organization's plan standing for one admission plus what the * free-compute bounds need beyond its own lease rows, read once before * admission (resolveSandboxComputeStanding) and reused under the lease lock. */ export type SandboxComputeStanding = { /** The plan tier admission applies, including a linked restriction. */ tier: string; /** Bought credit or had a paid subscription: a paying customer, outside the * unpaid-only bounds and on the standard resource class. */ paidHistory: boolean; /** The unpaid-only bounds (per person, daily box time, idle drain) apply. */ bounded: boolean; /** The acting person owns or administers this organization and another * unpaid one that its own held or denied decision restricts. */ linkedRestricted: boolean; /** The acting person owns this organization, so its boxes and box time are * theirs for the per-person bounds. */ personOwnsOrganization: boolean; /** Running boxes in the other unpaid organizations the acting person owns. */ personOtherRunningBoxes: number; /** Metered box seconds since the start of the UTC day. */ organizationBoxSecondsToday: number; /** The same across the unpaid organizations the acting person owns. */ personBoxSecondsToday: number; /** When the organization was created (null when unknown). */ organizationCreatedAt: Date | null; /** The card verification gate is on, the organization is bounded and * neither it nor its acting owner (in another organization they run) has a * verified card: starting a box is refused. */ cardRequired: boolean; /** The card is required, but its tier's `cardTrialBoxSeconds` is not used * yet: an agent turn may still start one box (see acquireLease). A failed * read leaves it false. */ cardTrial: boolean; /** The card is required, its tier sets a card trial and it is used: no * new holder joins a box no turn holds either. */ cardTrialSpent: boolean; }; /** Called when a standing read failed and admission fell back (fails open): * `organization` to the in-transaction tier only, `person` to the * organization's own bounds. */ export type SandboxComputeStandingFallback = ( error: unknown, part: "organization" | "person" | "fleet", ) => void; function reportSandboxComputeStandingFallback( onFallback: SandboxComputeStandingFallback | undefined, error: unknown, part: "organization" | "person" | "fleet", ): void { if (onFallback) { try { onFallback(error, part); } catch { // Reporting never changes admission. } return; } console.warn("sandbox compute standing read failed; admission falls back", { part, error: error instanceof Error ? error.message : String(error), }); } /** The most other organizations of one person the standing reads. */ const SANDBOX_STANDING_PERSON_ORGANIZATION_LIMIT = 25; /** The most further owned organizations searched for the owner's card. */ const SANDBOX_STANDING_CARD_ORGANIZATION_LIMIT = 500; function sandboxDailyBoxTimeSpent(limit: SandboxPlanLimit, standing: SandboxComputeStanding) { return ( (limit.boxSecondsPerOrganizationPerDay !== undefined && standing.organizationBoxSecondsToday >= limit.boxSecondsPerOrganizationPerDay) || (limit.boxSecondsPerPersonPerDay !== undefined && standing.personBoxSecondsToday >= limit.boxSecondsPerPersonPerDay) ); } function sandboxDailyBoxTimeLimitSeconds( limit: SandboxPlanLimit, standing: SandboxComputeStanding | null, ): number { if ( standing !== null && limit.boxSecondsPerOrganizationPerDay !== undefined && standing.organizationBoxSecondsToday >= limit.boxSecondsPerOrganizationPerDay ) { return limit.boxSecondsPerOrganizationPerDay; } return limit.boxSecondsPerPersonPerDay ?? limit.boxSecondsPerOrganizationPerDay ?? 0; } /** Metered box seconds of one organization since the start of the UTC day. * Needs the organization's account-only RLS context (no workspace), so every * workspace's meter counts. */ async function organizationBoxSecondsToday(tx: Database, accountId: string): Promise { const [row] = await rawRows<{ seconds: string | number | null }>( tx, sql`select coalesce(sum(quantity), 0)::bigint as seconds from usage_events where account_id = ${accountId}::uuid and event_type = 'sandbox.warm_seconds' and occurred_at >= (date_trunc('day', now() at time zone 'UTC') at time zone 'UTC')`, ); return Number(row?.seconds ?? 0); } /** Metered box seconds of one organization over its whole life (the card * trial budget). Needs the organization's account-only RLS context. */ async function organizationBoxSecondsTotal(tx: Database, accountId: string): Promise { const [row] = await rawRows<{ seconds: string | number | null }>( tx, sql`select coalesce(sum(quantity), 0)::bigint as seconds from usage_events where account_id = ${accountId}::uuid and event_type = 'sandbox.warm_seconds'`, ); return Number(row?.seconds ?? 0); } /** What a suspended organization is told when a cost path refuses it. */ export const ORGANIZATION_SUSPENDED_MESSAGE = "This organization is suspended after review, so it can't use paid resources. Add credit or contact support if you think this is a mistake."; /** Suspension is read on every cost path; reuse it briefly per process. */ const ORGANIZATION_SUSPENSION_TTL_MS = 30_000; const organizationSuspensionCache = new Map }>(); /** Forget cached suspensions (tests). */ export function resetOrganizationSuspensionCache(): void { organizationSuspensionCache.clear(); } /** * Whether an organization is suspended: a Free or plan-less organization with * no paid history (never bought credit, never had a paid subscription) whose * own promotion decision is `denied` while promotion enforcement is on, or one * the acting person (`user:`) owns or administers while they own or * administer such a suspended organization. Derived from the decision, so it * applies as soon as the organization is denied and clears as soon as the * decision is reversed or the organization pays; nothing is deleted and no * ledger is touched. Paid, Enterprise and host-provisioned organizations are * never suspended. A suspended organization's people can still sign in and buy * credit, which lifts it. */ export async function resolveOrganizationSuspension( db: Database, input: { accountId: string; subjectId?: string | null }, ): Promise { const subjectId = input.subjectId?.startsWith("user:") ? input.subjectId : null; const key = `${input.accountId}\u0000${subjectId ?? ""}`; const now = Date.now(); const cached = organizationSuspensionCache.get(key); if (cached && now - cached.at < ORGANIZATION_SUSPENSION_TTL_MS) return await cached.value; if (organizationSuspensionCache.size >= SANDBOX_PERSON_STANDING_CACHE_LIMIT) { organizationSuspensionCache.clear(); } const value = readOrganizationSuspension(db, { accountId: input.accountId, subjectId }); organizationSuspensionCache.set(key, { at: now, value }); value.catch(() => organizationSuspensionCache.delete(key)); return await value; } async function readOrganizationSuspension( db: Database, input: { accountId: string; subjectId: string | null }, ): Promise { const own = await withAccountRls(db, input.accountId, (tx) => resolveSandboxPlanStanding(tx, input.accountId), ); if (own.suspended) return true; if (own.paidHistory || (own.tier !== "free" && own.tier !== "none")) return false; if (input.subjectId === null) return false; const subjectId = input.subjectId; const memberships = await db.transaction(async (tx) => { await setSubjectRlsContext(tx as unknown as Database, subjectId); const [row] = await rawRows<{ result: unknown }>( tx, sql`select list_self_organization_memberships(${subjectId}) as result`, ); return Array.isArray(row?.result) ? (row.result as Array<{ organizationId?: unknown; role?: unknown; status?: unknown }>) : []; }); const administered = memberships.filter( (membership) => membership.status === "active" && (membership.role === "owner" || membership.role === "admin") && typeof membership.organizationId === "string", ); if (!administered.some((membership) => membership.organizationId === input.accountId)) { return false; } for (const organizationId of administered .map((membership) => membership.organizationId as string) .filter((candidate) => candidate !== input.accountId) .sort() .slice(0, SANDBOX_STANDING_PERSON_ORGANIZATION_LIMIT)) { const other = await withAccountRls(db, organizationId, (tx) => resolveSandboxPlanStanding(tx, organizationId), ); if (other.suspended) return true; } return false; } /** Metered box seconds of one organization since the start of the UTC day * (maintenance callers). */ export async function readOrganizationBoxSecondsToday( db: Database, accountId: string, ): Promise { return await withAccountRls(db, accountId, (tx) => organizationBoxSecondsToday(tx, accountId)); } /** * An organization's standing for one admission (see SandboxComputeStanding): * its plan tier, whether it has paid, its box time today when its tier bounds * that and, for an acting person (`user:`), the organizations they own or * administer. Only an unpaid-tier organization that never paid reads more than * its own tier: paid plans, `enterprise` and `embedded` read no ledger, no box * time and no person. * * The person's other organizations are read each under its own RLS context, * outside the admission transaction, so the cross-organization counts are a * snapshot: two simultaneous admissions in two organizations of one person can * both pass. The per-organization limits stay exact. A failed person read * falls back to the organization's own bounds (reported through * `onFallback`); a failed organization read throws, and acquireLease falls * back to the tier it reads under the lease lock. */ export async function resolveSandboxComputeStanding( db: Database, input: { accountId: string; limits: SandboxPlanLimits; actingSubjectId?: string | null; onFallback?: SandboxComputeStandingFallback | undefined; /** Whether this deployment has subscription plans * (settings.subscriptionPlansEnabled; default on). Without them a * plan-less organization (`none`) is not unpaid (sandboxPlanTierUnpaid). */ subscriptionPlansEnabled?: boolean | undefined; }, ): Promise { const plans = { subscriptionPlansEnabled: input.subscriptionPlansEnabled }; const own = await withAccountRls(db, input.accountId, async (tx) => { const standing = await resolveSandboxPlanStanding(tx, input.accountId, input.limits); const bounded = sandboxPlanTierUnpaid(standing.tier, plans) && !standing.paidHistory; // A Free or plan-less organization that never paid can be restricted // through its acting person, whether or not its tier is unpaid: without // subscription plans a plan-less organization is unbounded, but the // promotion decisions of its people still apply. const restrictable = UNPAID_SANDBOX_PLAN_TIERS.includes(standing.tier) && !standing.paidHistory; const limit = sandboxPlanLimitFor(input.limits, standing.tier); const needsSeconds = bounded && (limit.boxSecondsPerOrganizationPerDay !== undefined || limit.boxSecondsPerPersonPerDay !== undefined); return { standing, bounded, restrictable, seconds: needsSeconds ? await organizationBoxSecondsToday(tx, input.accountId) : 0, cardTrialBoxSeconds: limit.cardTrialBoxSeconds ?? 0, }; }); // Card verification gate (migration 1494): only a bounded organization, // only while the switch is on. A failed read fails open. let cardRequired = false; let cardTrial = false; let cardTrialSpent = false; if (own.bounded && (await readCardVerificationGate(db))) { try { cardRequired = (await withAccountRls(db, input.accountId, (tx) => readCardVerificationInTransaction(tx, input.accountId), )) === null; } catch (error) { reportSandboxComputeStandingFallback(input.onFallback, error, "organization"); } // The tier's card trial: box time its agent gets before the card. A // failed read grants no trial (the card is still asked for). if (cardRequired && own.cardTrialBoxSeconds > 0) { try { const used = await withAccountRls(db, input.accountId, (tx) => organizationBoxSecondsTotal(tx, input.accountId), ); cardTrial = used < own.cardTrialBoxSeconds; cardTrialSpent = !cardTrial; } catch (error) { reportSandboxComputeStandingFallback(input.onFallback, error, "organization"); } } } const result: SandboxComputeStanding = { tier: own.standing.tier, paidHistory: own.standing.paidHistory, bounded: own.bounded, linkedRestricted: false, personOwnsOrganization: false, personOtherRunningBoxes: 0, organizationBoxSecondsToday: own.seconds, personBoxSecondsToday: 0, organizationCreatedAt: own.standing.organizationCreatedAt, cardRequired, cardTrial, cardTrialSpent, }; const subjectId = input.actingSubjectId ?? null; if (!own.restrictable || subjectId === null || !subjectId.startsWith("user:")) return result; // A restricted organization needs no person facts: it is already closed. if (own.standing.tier === "restricted") return result; let person: SandboxPersonStanding; try { person = await cachedSandboxPersonStanding(db, { accountId: input.accountId, subjectId, limits: input.limits, ...plans, }); } catch (error) { reportSandboxComputeStandingFallback(input.onFallback, error, "person"); return result; } result.linkedRestricted = person.linkedRestricted; if (person.linkedRestricted) { result.tier = "restricted"; result.cardTrial = false; result.cardTrialSpent = false; } // Another organization of the same owner inherits the card they verified // for sandboxes (never for Free credit: one Free grant per card and person). if (result.cardRequired && person.ownsOrganization && person.cardVerifiedElsewhere) { result.cardRequired = false; result.cardTrial = false; result.cardTrialSpent = false; } result.personOwnsOrganization = person.ownsOrganization; result.personOtherRunningBoxes = person.otherRunningBoxes; result.personBoxSecondsToday = (person.ownsOrganization ? own.seconds : 0) + person.otherBoxSecondsToday; return result; } type SandboxPersonStanding = { linkedRestricted: boolean; ownsOrganization: boolean; /** The person verified a card in another organization they own or * administer. */ cardVerifiedElsewhere: boolean; otherRunningBoxes: number; otherBoxSecondsToday: number; }; /** A person's standing is read for every admission of their requests, and a * terminal or file browser makes many; reuse it briefly per process. */ const SANDBOX_PERSON_STANDING_TTL_MS = 15_000; const SANDBOX_PERSON_STANDING_CACHE_LIMIT = 2_000; const sandboxPersonStandingCache = new Map< string, { at: number; value: Promise } >(); /** Forget cached person standings (tests). */ export function resetSandboxPersonStandingCache(): void { sandboxPersonStandingCache.clear(); organizationPurchasedCreditCache.clear(); } async function cachedSandboxPersonStanding( db: Database, input: { accountId: string; subjectId: string; limits: SandboxPlanLimits; subscriptionPlansEnabled?: boolean | undefined; }, ): Promise { const key = `${input.accountId}\u0000${input.subjectId}`; const now = Date.now(); const cached = sandboxPersonStandingCache.get(key); if (cached && now - cached.at < SANDBOX_PERSON_STANDING_TTL_MS) return await cached.value; if (sandboxPersonStandingCache.size >= SANDBOX_PERSON_STANDING_CACHE_LIMIT) { sandboxPersonStandingCache.clear(); } const value = readSandboxPersonStanding(db, input); sandboxPersonStandingCache.set(key, { at: now, value }); value.catch(() => sandboxPersonStandingCache.delete(key)); return await value; } /** * The acting person's other organizations. A restriction follows them from * any organization they own or administer into this one, when they also own * or administer this one. Boxes and box time count toward their per-person * bounds only from organizations they own (the ones they created), so an * admin invited into a busy team organization is not bounded by their * teammates' work. */ async function readSandboxPersonStanding( db: Database, input: { accountId: string; subjectId: string; limits: SandboxPlanLimits; subscriptionPlansEnabled?: boolean | undefined; }, ): Promise { const subjectId = input.subjectId; const result: SandboxPersonStanding = { linkedRestricted: false, ownsOrganization: false, cardVerifiedElsewhere: false, otherRunningBoxes: 0, otherBoxSecondsToday: 0, }; const cardGate = await readCardVerificationGate(db); const memberships = await db.transaction(async (tx) => { await setSubjectRlsContext(tx as unknown as Database, subjectId); const [row] = await rawRows<{ result: unknown }>( tx, sql`select list_self_organization_memberships(${subjectId}) as result`, ); return Array.isArray(row?.result) ? (row.result as Array<{ organizationId?: unknown; role?: unknown; status?: unknown }>) : []; }); const administered = memberships.filter( (membership) => membership.status === "active" && (membership.role === "owner" || membership.role === "admin") && typeof membership.organizationId === "string", ); const administersThis = administered.some( (membership) => membership.organizationId === input.accountId, ); result.ownsOrganization = administered.some( (membership) => membership.organizationId === input.accountId && membership.role === "owner", ); const others = administered .filter((membership) => membership.organizationId !== input.accountId) .sort((left, right) => String(left.organizationId).localeCompare(String(right.organizationId))) .slice(0, SANDBOX_STANDING_PERSON_ORGANIZATION_LIMIT); for (const membership of others) { const organizationId = membership.organizationId as string; const owned = membership.role === "owner"; const other = await withAccountRls(db, organizationId, async (tx) => { if ( cardGate && !result.cardVerifiedElsewhere && (await subjectVerifiedCardInTransaction(tx, organizationId, subjectId)) ) { result.cardVerifiedElsewhere = true; } const standing = await resolveSandboxPlanStanding(tx, organizationId, input.limits); if (!sandboxPlanTierUnpaid(standing.tier, input) || standing.paidHistory) { return null; } const counts = owned ? await organizationWarmSandboxCounts(tx, { accountId: organizationId, subjectId: null, excludeLeaseId: null, }) : null; return { restricted: standing.tier === "restricted" && standing.ownDecision !== null && standing.ownDecisionFollowsPerson, runningBoxes: counts?.runningBoxes ?? 0, seconds: owned ? await organizationBoxSecondsToday(tx, organizationId) : 0, }; }); if (other === null) continue; // Only a person who runs this organization carries another one's // restriction into it; a member invited into someone else's organization // does not restrict it. if (other.restricted && administersThis) result.linkedRestricted = true; result.otherRunningBoxes += other.runningBoxes; result.otherBoxSecondsToday += other.seconds; } // The card follows its owner into every organization they own, not only // the ones the bounded loop above read. if (cardGate && !result.cardVerifiedElsewhere) { const remaining = administered .filter( (membership) => membership.organizationId !== input.accountId && membership.role === "owner" && !others.includes(membership), ) .slice(0, SANDBOX_STANDING_CARD_ORGANIZATION_LIMIT); for (const membership of remaining) { const organizationId = membership.organizationId as string; if ( await withAccountRls(db, organizationId, (tx) => subjectVerifiedCardInTransaction(tx, organizationId, subjectId), ) ) { result.cardVerifiedElsewhere = true; break; } } } return result; } /** The organization-wide count definer (1475, granted by 1479). */ export const ORGANIZATION_WARM_SANDBOX_COUNTS_ROUTINE = "opengeni_private.organization_warm_sandbox_counts_v1(uuid, text, uuid)"; /** The tier of a host-provisioned organization (a configured deployment, an * embedding host or the SDK bootstrap); unbounded unless configured. See * resolveSandboxPlanTier. */ export const SANDBOX_EMBEDDED_PLAN_TIER = "embedded"; /** Tiers outside the per-workspace viewer-only limit * (`OPENGENI_SANDBOX_MAX_VIEWER_ONLY_BOXES_PER_WORKSPACE`) and the reaper's * viewer-only drains: host-provisioned organizations and the `enterprise` * plan, which operators assign to organizations that must not be bounded. * Their plan-limit table entries still apply at admission. */ export function sandboxPlanTierExemptFromViewerOnlyBounds(tier: string): boolean { return tier === SANDBOX_EMBEDDED_PLAN_TIER || tier === "enterprise"; } /** The tier of a young Free self-serve organization, while the * `new` tier sets `organizationsYoungerThanMs`. */ export const SANDBOX_NEW_PLAN_TIER = "new"; /** managed_accounts.external_source values of self-serve organizations: a * person's signup and an additional organization they create. Any other * source is a host's. A guard test fails when a new account-creating path * introduces a source that is in neither this list nor its known host list. */ export const SELF_SERVE_ACCOUNT_SOURCES: readonly string[] = [ "better-auth:user", "opengeni:additional-organization", ]; /** * The plan tier whose sandbox limits apply to an organization: * * - `embedded` for an organization a host provisioned: its external source is * not a self-serve one (a configured or local deployment, an embedding * host or the SDK bootstrap). Nobody self-serve can set it, unlike a * workspace's external source, which never counts. Operators put any other * organization that must not be bounded on the `enterprise` plan. * - otherwise its plan key (a paid plan only while active, trialing or past * due), `none` without a plan row; * - `restricted` for a Free or plan-less organization whose promotion * decision is `held` or `denied`, while promotion enforcement is on, or * whose acting person owns or administers such an organization * (`linkedRestricted`), unless it bought credit (a top-up) or ever had a * paid subscription; * - `new` for any other Free organization created less than the `new` tier's * `organizationsYoungerThanMs` ago (only when `limits` is given and sets it). * * The tier is the organization's, whatever credential the caller holds * (browser session, API key, native token or service). * * Reads only the caller's own organization's rows under the current account * context. */ export async function resolveSandboxPlanTier( tx: Database, accountId: string, limits?: SandboxPlanLimits, options: { linkedRestricted?: boolean } = {}, ): Promise { return (await resolveSandboxPlanStanding(tx, accountId, limits, options)).tier; } /** An organization's plan tier plus the facts the free-compute bounds need. */ export type SandboxPlanStanding = { tier: string; /** Bought credit (a top-up) or ever had a paid subscription. Never * restricted or suspended. */ paidHistory: boolean; /** Its own promotion decision is held or denied while enforcement is on. */ ownDecision: "held" | "denied" | null; /** Whether that decision follows the person into the other organizations * they own or administer. A detector hold on an additional organization * (the rapid or linked rule, or a signup rule) holds only that * organization; a denial or any reviewer's decision follows the person. */ ownDecisionFollowsPerson: boolean; /** Restricted because its own decision is denied (not only held and not * only linked): the organization is suspended. See * resolveSandboxSuspension. */ suspended: boolean; /** When the organization was created (null when unknown); the fleet limits * bound a young unpaid organization's running boxes. */ organizationCreatedAt: Date | null; }; /** resolveSandboxPlanTier with the facts behind it. `linkedRestricted` * restricts a Free or plan-less organization with no paid history because the * acting person owns or administers another restricted organization. */ /** Whether an organization ever bought credit is read for unpaid-tier * organizations on admission paths; a purchase never un-happens, so a yes is * kept for the process's life (bounded) and a no for a minute. */ const ORGANIZATION_PURCHASED_CREDIT_NEGATIVE_TTL_MS = 60_000; const ORGANIZATION_PURCHASED_CREDIT_CACHE_LIMIT = 5_000; const organizationPurchasedCreditCache = new Map }>(); /** Forget cached purchase facts (tests). */ export function resetOrganizationPurchasedCreditCache(): void { organizationPurchasedCreditCache.clear(); } /** Any positive credit top-up (a purchase, never a grant) in the ledger. Needs * the organization's RLS context. */ async function organizationPurchasedCredit(tx: Database, accountId: string): Promise { const now = Date.now(); const cached = organizationPurchasedCreditCache.get(accountId); if (cached) { const value = await cached.value.catch(() => null); if ( value === true || (value === false && now - cached.at < ORGANIZATION_PURCHASED_CREDIT_NEGATIVE_TTL_MS) ) { return value; } } if (organizationPurchasedCreditCache.size >= ORGANIZATION_PURCHASED_CREDIT_CACHE_LIMIT) { organizationPurchasedCreditCache.clear(); } const value = rawRows<{ purchased: boolean }>( tx, sql`select exists (select 1 from credit_ledger_entries entry where entry.account_id = ${accountId}::uuid and entry.type = 'credit_topup' and entry.amount_micros > 0) as purchased`, ).then((rows) => rows[0]?.purchased === true); organizationPurchasedCreditCache.set(accountId, { at: now, value }); value.catch(() => organizationPurchasedCreditCache.delete(accountId)); return await value; } export async function resolveSandboxPlanStanding( tx: Database, accountId: string, limits?: SandboxPlanLimits, options: { linkedRestricted?: boolean } = {}, ): Promise { const newTierAgeMs = limits ? (sandboxPlanLimitFor(limits, SANDBOX_NEW_PLAN_TIER).organizationsYoungerThanMs ?? 0) : 0; const [row] = await rawRows<{ plan_key: string | null; status: string | null; decision: string | null; decision_actor: string | null; additional_organization: boolean | null; enforcement: boolean | null; hosted_account: boolean | null; young: boolean | null; stripe_subscription: boolean | null; created_at: Date | string | null; }>( tx, sql`select plan.plan_key, plan.status, decision.decision, decision.actor as decision_actor, exists (select 1 from managed_accounts account where account.id = organization.account_id and account.external_source = 'opengeni:additional-organization') as additional_organization, (select account.created_at from managed_accounts account where account.id = organization.account_id) as created_at, (select enforcement.enabled from promotion_enforcement enforcement where enforcement.singleton) as enforcement, (${newTierAgeMs}::bigint > 0 and exists (select 1 from managed_accounts account where account.id = organization.account_id and account.created_at > now() - (${newTierAgeMs}::bigint * interval '1 millisecond') )) as young, exists (select 1 from managed_accounts account where account.id = organization.account_id and account.external_source is not null and account.external_source not in (${sql.join( SELF_SERVE_ACCOUNT_SOURCES.map((source) => sql`${source}`), sql`, `, )})) as hosted_account, plan.stripe_subscription_id is not null as stripe_subscription from (select ${accountId}::uuid as account_id) organization left join organization_plans plan on plan.account_id = organization.account_id left join promotion_decisions decision on decision.account_id = organization.account_id`, ); const organizationCreatedAt = row?.created_at == null ? null : new Date(row.created_at); if (row?.hosted_account === true) { return { tier: SANDBOX_EMBEDDED_PLAN_TIER, paidHistory: false, ownDecision: null, ownDecisionFollowsPerson: false, suspended: false, organizationCreatedAt, }; } const planKey = row?.plan_key ?? null; let tier: string; if (planKey === null) tier = "none"; else if (planKey === "free" || planKey === "enterprise") tier = planKey; else if (["active", "trialing", "past_due"].includes(row?.status ?? "")) tier = planKey; else tier = "free"; // Paid history matters only for an unpaid tier; a paid, Enterprise or // host-provisioned organization never reads the ledger here. const paidHistory = row?.stripe_subscription === true || ((tier === "free" || tier === "none") && (await organizationPurchasedCredit(tx, accountId))); const ownDecision = row?.enforcement === true && (row?.decision === "held" || row?.decision === "denied") ? row.decision : null; const ownDecisionFollowsPerson = ownDecision !== null && !( ownDecision === "held" && row?.decision_actor === "service:promotion-detector" && row?.additional_organization === true ); // Restricted only without paid history: a person who bought credit or paid // for a plan is never cut off by a review decision. if ( (tier === "free" || tier === "none") && !paidHistory && (ownDecision !== null || options.linkedRestricted === true) ) { return { tier: "restricted", paidHistory, ownDecision, ownDecisionFollowsPerson, suspended: ownDecision === "denied", organizationCreatedAt, }; } if (tier === "free" && row?.young === true) { return { tier: SANDBOX_NEW_PLAN_TIER, paidHistory, ownDecision, ownDecisionFollowsPerson, suspended: false, organizationCreatedAt, }; } return { tier, paidHistory, ownDecision, ownDecisionFollowsPerson, suspended: false, organizationCreatedAt, }; } export function sandboxPlanLimitFor(limits: SandboxPlanLimits, tier: string): SandboxPlanLimit { return Object.hasOwn(limits, tier) ? (limits[tier] ?? {}) : {}; } /** resolveSandboxPlanTier for maintenance callers, in the RLS context of one * of the organization's workspaces. */ export async function resolveSandboxPlanTierInWorkspace( db: Database, input: { accountId: string; workspaceId: string; limits?: SandboxPlanLimits }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await resolveSandboxPlanTier(scopedDb, input.accountId, input.limits), ); } /** resolveSandboxPlanStanding for maintenance callers, in the RLS context of * one of the organization's workspaces. */ export async function resolveSandboxPlanStandingInWorkspace( db: Database, input: { accountId: string; workspaceId: string; limits?: SandboxPlanLimits }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await resolveSandboxPlanStanding(scopedDb, input.accountId, input.limits), ); } type OrganizationWarmSandboxCounts = { viewerOnlyBoxes: number; subjectViewerOnlyBoxes: number; runningBoxes: number; }; /** 1475 created the definer withheld; 1479 grants it and readiness requires * it. */ async function organizationWarmSandboxCounts( tx: Database, input: { accountId: string; subjectId: string | null; excludeLeaseId: string | null }, ): Promise { const [row] = await rawRows<{ viewer_only_boxes: number; subject_viewer_only_boxes: number; running_boxes: number; }>( tx, sql`select viewer_only_boxes, subject_viewer_only_boxes, running_boxes from opengeni_private.organization_warm_sandbox_counts_v1( ${input.accountId}::uuid, ${input.subjectId}::text, ${input.excludeLeaseId}::uuid)`, ); return { viewerOnlyBoxes: Number(row?.viewer_only_boxes ?? 0), subjectViewerOnlyBoxes: Number(row?.subject_viewer_only_boxes ?? 0), runningBoxes: Number(row?.running_boxes ?? 0), }; } /** * Serialize sandbox-limit counts for one organization. Taken last in an * admission, after the lease's own locks; its holder then waits only for its * own lease row, so no admission can wait on a lock this one holds. */ async function enforceSandboxFleetLimits( tx: Database, input: { fleet: SandboxFleetAdmission; leaseId: string; workspaceId: string; sandboxGroupId: string; onFallback: SandboxComputeStandingFallback | undefined; }, ): Promise { const { fleet, workspaceId, sandboxGroupId } = input; const refuse = (reason: "fleet_busy" | "fleet_daily_budget", limit: number): never => { throw new SandboxOrganizationBoxLimitError(workspaceId, sandboxGroupId, limit, reason); }; const dailyBudget = fleet.limits.unpaidBoxSecondsPerDay; if (dailyBudget !== undefined) { if (fleet.boxSecondsFailed) refuse("fleet_busy", 0); if (fleet.boxSecondsToday !== null && fleet.boxSecondsToday >= dailyBudget) { refuse("fleet_daily_budget", dailyBudget); } } if (fleet.limits.pressureEngageWarmBoxes !== undefined && fleet.pressure.failed) { refuse("fleet_busy", 0); } const pressureCap = fleet.pressure.engaged && fleet.limits.pressureUnpaidRunningBoxes !== undefined ? fleet.limits.pressureUnpaidRunningBoxes : undefined; const caps = [fleet.limits.unpaidRunningBoxes, pressureCap].filter( (cap): cap is number => cap !== undefined, ); if (caps.length === 0) return; const cap = Math.min(...caps); // Under pressure with no new unpaid box allowed, nothing needs counting. if (cap === 0) refuse("fleet_busy", 0); let counts: SandboxUnpaidFleetCounts | null; try { // Not granted yet (1486 withholds it): the running cap waits for its // grant, and no admission takes the fleet lock for nothing. if (!(await sandboxUnpaidFleetAvailable(tx))) return; await lockSandboxUnpaidFleet(tx); counts = await readSandboxUnpaidFleet(tx, { excludeLeaseId: input.leaseId, withBoxSeconds: false, }); } catch (error) { reportSandboxComputeStandingFallback(input.onFallback, error, "fleet"); return refuse("fleet_busy", cap); } if (counts === null) return; if (counts.runningBoxes >= cap) refuse("fleet_busy", cap); } async function lockOrganizationSandboxLimit(tx: Database, accountId: string): Promise { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended( ${`sandbox-organization-box-limit:${accountId}`}, 0 ))`, ); } export class SandboxPaidComputeAdmissionError extends Error { readonly name = "SandboxPaidComputeAdmissionError"; constructor( public readonly workspaceId: string, public readonly sandboxGroupId: string, message = "Insufficient workspace credits to admit paid sandbox compute", ) { super(message); } } type SandboxWarmBillingSnapshot = { mode: "usage_only" | "shadow" | "credits"; rateMicrosPerSecond: number; accountId: string; workspaceId: string; attribution?: CreditDebitAttribution; stopChargeAt?: string; }; export class SandboxDebitAttributionUnavailableError extends SandboxPaidComputeAdmissionError { readonly code = "credit_debit_attribution_unavailable"; constructor(workspaceId: string, sandboxGroupId: string) { super(workspaceId, sandboxGroupId); this.message = "Paid sandbox compute has no frozen initiating attribution"; } } function warmBillingSnapshot( row: Pick, ): SandboxWarmBillingSnapshot | null { const value = row.resume_state?.opengeniWarmBilling; if (!value || typeof value !== "object") return null; const snapshot = value as SandboxWarmBillingSnapshot; return (snapshot.mode === "usage_only" || snapshot.mode === "shadow" || snapshot.mode === "credits") && Number.isFinite(snapshot.rateMicrosPerSecond) && snapshot.rateMicrosPerSecond >= 0 && (snapshot.stopChargeAt === undefined || (typeof snapshot.stopChargeAt === "string" && Number.isFinite(Date.parse(snapshot.stopChargeAt)))) && snapshot.accountId === row.account_id && snapshot.workspaceId === row.workspace_id && (snapshot.attribution === undefined || CreditDebitAttribution.safeParse(snapshot.attribution).success) ? snapshot : null; } /** * The exact durable attempt holder is the worker's admission receipt. Direct, * viewer and interaction requests instead carry host-authenticated context. * Neither subjectId (a session disclosure label) nor a creator is a human. */ async function sandboxWarmAdmissionAttribution( tx: Database, input: AcquireLeaseAdmissionInput, ): Promise { if (input.kind === "turn" && input.holderId.startsWith("turn-attempt:")) { const attemptId = input.holderId.slice("turn-attempt:".length); if (!z.uuid().safeParse(attemptId).success) return { kind: "unknown" }; const rows = await tx.execute<{ turn_id: string; initiating_human_subject_id: string | null; }>(sql`SELECT t.id AS turn_id, t.initiating_human_subject_id FROM session_turn_attempts a JOIN session_turns t ON t.id=a.turn_id AND t.account_id=a.account_id AND t.workspace_id=a.workspace_id AND t.session_id=a.session_id JOIN sessions s ON s.id=t.session_id AND s.account_id=t.account_id AND s.workspace_id=t.workspace_id WHERE a.id=${attemptId}::uuid AND a.account_id=${input.accountId}::uuid AND a.workspace_id=${input.workspaceId}::uuid AND s.sandbox_group_id=${input.sandboxGroupId}::uuid`); if (!rows[0]) return { kind: "unknown" }; return CreditDebitAttribution.parse({ kind: "turn", turnId: rows[0].turn_id, initiatingHumanSubjectId: rows[0].initiating_human_subject_id, }); } return currentCreditDebitAttribution(); } /** * Fence the warm-time meter BEFORE requesting provider stop, including free * and shadow usage. The immutable cutoff survives a stop-success/settlement- * failure retry. A failed stop can undercount an idle retry, never count time * after the provider stopped. */ export async function markWarmBillingStopCutoff( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number }, ): Promise { return withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [row] = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); if ( !row || Number(row.lease_epoch) !== input.expectedEpoch || row.liveness !== "draining" || (Number(row.refcount) !== 0 && !row.unobservable_command_drain_ids?.length) ) return null; const snapshot = warmBillingSnapshot(row); if (row.resume_state?.opengeniWarmBilling && !snapshot) throw new Error("sandbox warm billing snapshot is invalid"); if (snapshot?.stopChargeAt) return new Date(snapshot.stopChargeAt); const [stamped] = await tx.execute<{ cutoff: string }>(sql` update sandbox_leases set resume_state = jsonb_set(coalesce(resume_state, '{}'::jsonb), '{opengeniWarmBilling}', coalesce(resume_state->'opengeniWarmBilling', jsonb_build_object('mode', 'usage_only', 'rateMicrosPerSecond', 0, 'accountId', account_id, 'workspaceId', workspace_id)) || jsonb_build_object('stopChargeAt', clock_timestamp()), true), updated_at = now() where id = ${row.id} returning resume_state #>> '{opengeniWarmBilling,stopChargeAt}' as cutoff `); if (!stamped || !Number.isFinite(Date.parse(stamped.cutoff))) throw new Error("sandbox warm billing stop cutoff was not saved"); return new Date(stamped.cutoff); }), ); } export class SandboxLeaseRecoveryBlockedError extends Error { readonly name = "SandboxLeaseRecoveryBlockedError"; constructor( public readonly sandboxGroupId: string, public readonly leaseEpoch: number, public readonly code: "restore_degraded" | "restore_unrecoverable", public readonly recovery: SandboxRecoveryState, ) { super( `Sandbox ${sandboxGroupId} recovery is ${code === "restore_degraded" ? "degraded" : "unrecoverable"} at epoch ${leaseEpoch}`, ); } } // IMAGE IS SHARED STATE (B3): thrown when a resume resolves an image DIFFERENT from // the one the live shared box was created with AND other holders are still on the box. // A shared box is ONE filesystem; recreating it on a new image would yank the running // filesystem out from under the OTHER sessions, so we refuse. The turn activity surfaces // holder never hits this — acquireLease requests a reaper-owned durable rotation instead. export class SandboxBackendConflictError extends Error { readonly name = "SandboxBackendConflictError"; constructor( public readonly sandboxGroupId: string, public readonly actualBackend: string, public readonly requestedBackend: string, ) { super( `Sandbox group ${sandboxGroupId} still owns provider work on ${actualBackend}; cannot use ${requestedBackend} until it is cold`, ); } } export class SandboxImageConflictError extends Error { constructor( public readonly sandboxGroupId: string, public readonly currentImage: string, public readonly requestedImage: string, ) { super( `Sandbox group ${sandboxGroupId} runs image ${currentImage}; this run resolves image ${requestedImage}. ` + `A shared box requires one image — spawn with sandbox:'new' for an isolated box or use the same sandbox environment.`, ); this.name = "SandboxImageConflictError"; } } // RIG IS SHARED STATE (M3): thrown when a resume resolves a rig version DIFFERENT from // the one the live shared box was set up under AND other holders are still on the box. // A rig bakes setup/tooling into the ONE shared filesystem; recreating it on a different // rig would yank that filesystem out from under the other sessions, so we refuse. The // turn activity surfaces this as an actionable error. A SOLO holder never hits this — // acquireLease requests a reaper-owned durable rotation instead. Mirrors // SandboxImageConflictError. export class SandboxRigConflictError extends Error { constructor( public readonly sandboxGroupId: string, public readonly currentRigVersionId: string, public readonly requestedRigVersionId: string, ) { super( `Sandbox group ${sandboxGroupId} was set up for rig version ${currentRigVersionId}; this run resolves rig version ${requestedRigVersionId}. ` + `A shared box requires one rig — spawn with sandbox:'new' for an isolated box or bind the group's rig.`, ); this.name = "SandboxRigConflictError"; } } /** True when `/workspace` may hold writes that bypassed generation * admissions and no capture covers yet: a viewer or interaction attached since * the last capture taken with none attached (`untrackedWriterSince`), or a * viewer, or a holder that is neither a turn nor a viewer (an interaction * controller among them), attached now. Such a box is not proven clean by a * complete archive; the capture claim decides exactly. */ export function leaseMayHaveUntrackedWriters( lease: Pick & Partial>, ): boolean { return ( (lease.untrackedWriterSince ?? null) !== null || lease.viewerHolders > 0 || lease.refcount > lease.turnHolders + lease.viewerHolders ); } function mapLeaseRow(row: LeaseRow): LeaseSnapshot { const workspaceGeneration = Number(row.workspace_generation); const archiveGeneration = row.archive_generation === null ? null : Number(row.archive_generation); const recovery = recoveryStateFromLeaseRow(row); return { unobservableCommandDrainIds: row.unobservable_command_drain_ids ?? null, id: row.id, sandboxGroupId: row.sandbox_group_id, liveness: row.liveness, refcount: Number(row.refcount), turnHolders: Number(row.turn_holders), viewerHolders: Number(row.viewer_holders), instanceId: row.instance_id, backend: row.backend, os: row.os, image: row.image ?? null, rigVersionId: row.rig_version_id ?? null, dataPlaneUrl: row.data_plane_url, terminalDataPlaneUrl: row.terminal_data_plane_url ?? null, controllerDataPlaneUrl: row.controller_data_plane_url ?? null, // Defensive coercion: integer returns a number, but coerce regardless so the // fence comparison stays exact even if the column type ever drifts to int8. leaseEpoch: Number(row.lease_epoch), workspaceGeneration, archiveGeneration, archiveComplete: recovery.archive.status === "available" && archiveGeneration !== null && archiveGeneration === workspaceGeneration, untrackedWriterSince: row.untracked_writer_since === null || row.untracked_writer_since === undefined ? null : row.untracked_writer_since instanceof Date ? row.untracked_writer_since : new Date(row.untracked_writer_since), computeHandingOffSince: row.compute_handing_off_since ? new Date(row.compute_handing_off_since) : null, archiveCapture: row.archive_capture_id === null || row.archive_capture_operation_id === null || row.archive_capture_provider_request_id === null || row.archive_capture_attempt === null || row.archive_capture_generation === null || row.archive_capture_started_at === null || row.archive_capture_deadline_at === null ? null : { id: row.archive_capture_id, operationId: row.archive_capture_operation_id, providerRequestId: row.archive_capture_provider_request_id, providerReplaySafe: row.archive_capture_provider_replay_safe, takeoverSafe: row.archive_capture_takeover_safe, attempt: Number(row.archive_capture_attempt), workspaceGeneration: Number(row.archive_capture_generation), startedAt: row.archive_capture_started_at instanceof Date ? row.archive_capture_started_at : new Date(row.archive_capture_started_at), deadlineAt: row.archive_capture_deadline_at instanceof Date ? row.archive_capture_deadline_at : new Date(row.archive_capture_deadline_at), publishedAt: row.archive_capture_published_at === null ? null : row.archive_capture_published_at instanceof Date ? row.archive_capture_published_at : new Date(row.archive_capture_published_at), }, drainCaptureFailures: drainCaptureFailuresFromLeaseRow(row), reaperHold: row.reaper_hold_id === null || row.reaper_hold_until === null || row.reaper_hold_reason === null ? null : { id: row.reaper_hold_id, until: row.reaper_hold_until instanceof Date ? row.reaper_hold_until : new Date(row.reaper_hold_until), reason: row.reaper_hold_reason, }, resumeBackendId: row.resume_backend_id, resumeState: row.resume_state, recovery, providerCreateAttempt: row.provider_create_attempt ?? null, providerCreatedAt: row.provider_created_at === null ? null : row.provider_created_at instanceof Date ? row.provider_created_at : new Date(row.provider_created_at), providerDeadlineAt: row.provider_deadline_at === null ? null : row.provider_deadline_at instanceof Date ? row.provider_deadline_at : new Date(row.provider_deadline_at), rotationRequestedAt: row.rotation_requested_at === null ? null : row.rotation_requested_at instanceof Date ? row.rotation_requested_at : new Date(row.rotation_requested_at), rotationReason: row.rotation_reason, groupEndRequestedAt: row.group_end_requested_at == null ? null : new Date(row.group_end_requested_at), currentCheckpointArtifactId: row.current_checkpoint_artifact_id, previousCheckpointArtifactId: row.previous_checkpoint_artifact_id, expiresAt: row.expires_at instanceof Date ? row.expires_at : new Date(row.expires_at), }; } export type SandboxDrainCaptureFailures = { count: number; firstFailedAt: Date | null; lastFailedAt: Date | null; }; function drainCaptureFailuresFromLeaseRow(row: LeaseRow): SandboxDrainCaptureFailures { const count = Number(row.drain_capture_failures ?? 0); if ( row.drain_capture_failure_epoch === null || row.drain_capture_failure_epoch === undefined || Number(row.drain_capture_failure_epoch) !== Number(row.lease_epoch) || !Number.isSafeInteger(count) || count <= 0 ) { return { count: 0, firstFailedAt: null, lastFailedAt: null }; } const date = (value: Date | string | null | undefined) => value === null || value === undefined ? null : value instanceof Date ? value : new Date(value); return { count, firstFailedAt: date(row.drain_capture_first_failed_at), lastFailedAt: date(row.drain_capture_last_failed_at), }; } function hasResumableLeaseInstance(row: LeaseRow): boolean { const envelope = row.resume_state && typeof row.resume_state === "object" ? row.resume_state : undefined; const declared = envelope?.[OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD]; // The lease column is authoritative. Merely finding an address is // insufficient: a stale envelope for a predecessor must never make the // current drain re-armable. const state = envelope?.sessionState && typeof envelope.sessionState === "object" ? (envelope.sessionState as Record) : envelope; const providerState = state?.providerState; if (!providerState || typeof providerState !== "object" || Array.isArray(providerState)) { return typeof declared === "string" && declared.length > 0 && declared === row.instance_id; } const record = providerState as Record; const fields = SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND[row.backend as SandboxBackend]; if (!fields) return false; const legacyIdentities = fields.flatMap((field) => { const value = record[field]; return typeof value === "string" && value.length > 0 ? [value] : []; }); if (typeof declared === "string" && declared.length > 0) { return ( declared === row.instance_id && legacyIdentities.every((identity) => identity === row.instance_id) ); } return ( legacyIdentities.length > 0 && legacyIdentities.every((identity) => identity === row.instance_id) ); } function leaseBackendRequiresResumableInstance(row: LeaseRow): boolean { const fields = SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND[row.backend as SandboxBackend]; // Fail closed for an unknown/new provider until its exact address contract is // registered. `none` is intentionally the sole providerless backend today. return fields === undefined || fields.length > 0; } function hasRearmableWorkspace(row: LeaseRow): boolean { // Pre-recovery envelopes retain their existing provider-identity checks. // Once readiness is recorded, an address alone cannot override that state: // a creator may have died after attribution but before workspace verification. if (row.resume_state?.opengeniRecovery === undefined) return true; const recovery = recoveryStateFromLeaseRow(row); return ( recovery.provider.status === "exists" && recovery.provider.instanceId === row.instance_id && recovery.workspace.status === "ready" && (recovery.restore.status === "not_required" || recovery.restore.status === "ready") ); } function archiveCaptureRemainingMs( row: Pick, ): number | null { if (row.archive_capture_remaining_ms === null || row.archive_capture_remaining_ms === undefined) { return null; } const remainingMs = Number(row.archive_capture_remaining_ms); return Number.isSafeInteger(remainingMs) && remainingMs >= 0 && remainingMs <= SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS ? remainingMs : null; } function providerlessLeaseBackendPredicateSql() { const providerlessBackends = Object.entries(SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND) .filter(([, fields]) => fields.length === 0) .map(([backend]) => backend); if (providerlessBackends.length === 0) return sql`false`; return sql`backend in (${sql.join( providerlessBackends.map((backend) => sql`${backend}`), sql`, `, )})`; } function legacyLeaseProviderIdentityPredicateSql(predicate: "matches" | "conflicts") { const providerState = sql`case when pg_catalog.jsonb_typeof(coalesce( resume_state #> '{sessionState,providerState}', resume_state #> '{providerState}' )) = 'object' then coalesce( resume_state #> '{sessionState,providerState}', resume_state #> '{providerState}' ) else '{}'::jsonb end`; const comparison = predicate === "matches" ? sql`=` : sql`<>`; const branches = Object.entries(SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND).flatMap( ([backend, fields]) => fields.length === 0 ? [] : [ sql`when backend = ${backend} then exists ( select 1 from pg_catalog.jsonb_each_text(${providerState}) as provider_identity(key, value) where provider_identity.key in (${sql.join( fields.map((field) => sql`${field}`), sql`, `, )}) and provider_identity.value ${comparison} instance_id )`, ], ); return sql`case ${sql.join(branches, sql` `)} else false end`; } function legacyLeaseProviderIdentityMatchesSql() { return legacyLeaseProviderIdentityPredicateSql("matches"); } function legacyLeaseProviderIdentityConflictsSql() { return legacyLeaseProviderIdentityPredicateSql("conflicts"); } function hasCompleteWorkspaceArchive(row: LeaseRow): boolean { const workspaceGeneration = Number(row.workspace_generation); const archiveGeneration = row.archive_generation === null ? null : Number(row.archive_generation); return ( recoveryStateFromLeaseRow(row).archive.status === "available" && !currentWorkspaceArchiveWasAbandoned(row) && Number.isSafeInteger(workspaceGeneration) && workspaceGeneration >= 0 && archiveGeneration !== null && Number.isSafeInteger(archiveGeneration) && archiveGeneration === workspaceGeneration ); } /** No filesystem discontinuity: an earlier failed restore can be tried again * against the same current archive. Explicit public recovery retains its own * immutable selection and consent lifecycle. */ function canRevalidateCurrentWorkspaceArchive(row: LeaseRow): boolean { return row.public_recovery === null && hasCompleteWorkspaceArchive(row); } function parseArchiveRevision(value: unknown): SandboxArchiveRevision | null { return parseWorkspaceArchiveDescriptor(value); } function recoveryStateFromLeaseRow(row: LeaseRow): SandboxRecoveryState { const resume = row.resume_state && typeof row.resume_state === "object" ? row.resume_state : undefined; const sessionState = resume?.sessionState && typeof resume.sessionState === "object" ? (resume.sessionState as Record) : undefined; const currentArchivePresent = workspaceArchivePayloadPresent(sessionState); const previousArchivePresent = (typeof sessionState?.workspaceArchivePrev === "string" && sessionState.workspaceArchivePrev.length > 0) || parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchivePrevRef) !== null; const current = parseArchiveRevision(sessionState?.workspaceArchiveMeta); const previous = parseArchiveRevision(sessionState?.workspaceArchivePrevMeta); const archiveStatus: SandboxArchiveAvailability = currentArchivePresent ? current ? "available" : "unverified" : previousArchivePresent ? "unverified" : "none"; const explicit = resume?.opengeniRecovery && typeof resume.opengeniRecovery === "object" ? (resume.opengeniRecovery as Partial) : undefined; const providerInput = explicit?.provider; const restoreInput = explicit?.restore; const workspaceInput = explicit?.workspace; const lateCaptureInput = explicit?.lateArchiveCapture; const continuityInput = explicit?.continuity; const providerStatus = providerInput?.status; const provider: SandboxRecoveryState["provider"] = { status: providerStatus === "not_created" || providerStatus === "creating" || providerStatus === "exists" || providerStatus === "missing" || providerStatus === "unknown" ? providerStatus : row.liveness === "warming" ? "creating" : row.instance_id ? "unknown" : "not_created", instanceId: typeof providerInput?.instanceId === "string" || providerInput?.instanceId === null ? providerInput.instanceId : row.instance_id, observedAt: typeof providerInput?.observedAt === "string" || providerInput?.observedAt === null ? providerInput.observedAt : null, ...(typeof providerInput?.diagnostic === "string" ? { diagnostic: providerInput.diagnostic } : {}), }; const restoreStatus = restoreInput?.status; const restore: SandboxRecoveryState["restore"] = { status: restoreStatus === "not_required" || restoreStatus === "pending" || restoreStatus === "restoring" || restoreStatus === "verifying" || restoreStatus === "ready" || restoreStatus === "degraded" || restoreStatus === "unrecoverable" ? restoreStatus : row.liveness === "cold" && archiveStatus === "available" ? "pending" : row.liveness === "cold" && archiveStatus === "unverified" ? "degraded" : "not_required", rematerializationId: typeof restoreInput?.rematerializationId === "string" ? restoreInput.rematerializationId : null, selectedRevision: typeof restoreInput?.selectedRevision === "string" ? restoreInput.selectedRevision : null, startedAt: typeof restoreInput?.startedAt === "string" ? restoreInput.startedAt : null, completedAt: typeof restoreInput?.completedAt === "string" ? restoreInput.completedAt : null, ...(typeof restoreInput?.failureCode === "string" ? { failureCode: restoreInput.failureCode } : {}), ...(typeof restoreInput?.retryable === "boolean" ? { retryable: restoreInput.retryable } : {}), }; const workspaceStatus = workspaceInput?.status; const workspace: SandboxRecoveryState["workspace"] = { status: workspaceStatus === "unknown" || workspaceStatus === "not_ready" || workspaceStatus === "ready" || workspaceStatus === "degraded" || workspaceStatus === "unrecoverable" ? workspaceStatus : row.liveness === "cold" && archiveStatus === "available" ? "not_ready" : row.liveness === "cold" && archiveStatus === "unverified" ? "degraded" : "unknown", verifiedRevision: typeof workspaceInput?.verifiedRevision === "string" ? workspaceInput.verifiedRevision : null, verifiedAt: typeof workspaceInput?.verifiedAt === "string" ? workspaceInput.verifiedAt : null, }; const lateArchiveCapture = lateCaptureInput?.version === 1 && typeof lateCaptureInput.captureId === "string" && typeof lateCaptureInput.providerRequestId === "string" && typeof lateCaptureInput.sourceLeaseId === "string" && Number.isSafeInteger(lateCaptureInput.sourceLeaseEpoch) && lateCaptureInput.sourceLeaseEpoch >= 0 && typeof lateCaptureInput.sourceInstanceId === "string" && lateCaptureInput.sourceInstanceId.length > 0 && Number.isSafeInteger(lateCaptureInput.sourceWorkspaceGeneration) && lateCaptureInput.sourceWorkspaceGeneration >= 0 && typeof lateCaptureInput.recordedAt === "string" ? { version: 1 as const, captureId: lateCaptureInput.captureId, providerRequestId: lateCaptureInput.providerRequestId, sourceLeaseId: lateCaptureInput.sourceLeaseId, sourceLeaseEpoch: lateCaptureInput.sourceLeaseEpoch, sourceInstanceId: lateCaptureInput.sourceInstanceId, sourceWorkspaceGeneration: lateCaptureInput.sourceWorkspaceGeneration, recordedAt: lateCaptureInput.recordedAt, } : null; const continuity = continuityInput?.version === 1 && continuityInput.backend === "docker" && continuityInput.kind === "docker_workspace" && typeof continuityInput.sourceInstanceId === "string" && continuityInput.sourceInstanceId.length > 0 && typeof continuityInput.continuityKey === "string" && continuityInput.continuityKey.startsWith("/") && continuityInput.continuityKey.length <= 4096 ? { version: 1 as const, backend: "docker" as const, kind: "docker_workspace" as const, sourceInstanceId: continuityInput.sourceInstanceId, continuityKey: continuityInput.continuityKey, } : null; return { provider, archive: { status: archiveStatus, current, previous }, restore, workspace, ...(continuity ? { continuity } : {}), ...(lateArchiveCapture ? { lateArchiveCapture } : {}), }; } function resumeStateWithRecovery( resumeState: Record | null, recovery: SandboxRecoveryState, ): Record { return { ...(resumeState ?? {}), opengeniRecovery: recovery }; } const WORKSPACE_ARCHIVE_SESSION_KEYS = [ "workspaceArchive", "workspaceArchiveMeta", "workspaceArchiveRef", "workspaceArchivePrev", "workspaceArchivePrevMeta", "workspaceArchivePrevRef", "workspaceArchiveAt", ] as const; /** A pending system decision to continue a definitively lost managed sandbox on * a new EMPTY workspace. It lives on the lease so every cold/warming rebuild of * resume_state carries it until the exact empty publication verifies it. */ const FRESH_WORKSPACE_RECOVERY_KEY = "opengeniFreshWorkspaceRecovery"; type FreshWorkspaceRecoveryMarker = { version: 1; operationId: string; sessionId: string; status: "accepted" | "verified"; authorizedAt: string; verifiedAt?: string; source?: "explicit"; /** Retained for forensics, never an implicit recovery source after reset. */ abandonedRevision?: string; }; function freshWorkspaceRecoveryMarker( resumeState: Record | null | undefined, ): FreshWorkspaceRecoveryMarker | null { const value = resumeState?.[FRESH_WORKSPACE_RECOVERY_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const marker = value as Record; return marker.version === 1 && typeof marker.operationId === "string" && UUID_PATTERN.test(marker.operationId) && typeof marker.sessionId === "string" && (marker.status === "accepted" || marker.status === "verified") && typeof marker.authorizedAt === "string" ? (marker as FreshWorkspaceRecoveryMarker) : null; } function pendingFreshWorkspaceRecovery( resumeState: Record | null | undefined, ): FreshWorkspaceRecoveryMarker | null { const marker = freshWorkspaceRecoveryMarker(resumeState); return marker?.status === "accepted" ? marker : null; } function retainedFreshWorkspaceRecovery( resumeState: Record | null | undefined, ): FreshWorkspaceRecoveryMarker | null { const marker = freshWorkspaceRecoveryMarker(resumeState); return marker?.status === "accepted" || marker?.abandonedRevision ? marker : null; } function currentWorkspaceArchiveWasAbandoned(row: LeaseRow): boolean { const revision = freshWorkspaceRecoveryMarker(row.resume_state)?.abandonedRevision; return ( typeof revision === "string" && revision === recoveryStateFromLeaseRow(row).archive.current?.revision ); } /** Durable evidence that the exact provider object of this lease lineage was * definitively lost. Only the two loss transitions write it (the reaper's * missing-before-capture cold commit and an exact warm-instance NOT_FOUND); * replacement failures carry it forward but never create it, and a verified * warm publication ends the lineage. */ const PROVIDER_LOSS_KEY = "opengeniProviderLoss"; const PROVIDER_NOT_FOUND_BEFORE_CAPTURE = "provider_not_found_before_workspace_capture"; /** A failed or reset replacement box: not evidence about the lost workspace. */ const REPLACEMENT_FAILED_DIAGNOSTIC = "replacement_failed"; type ProviderLossRecord = { version: 1; source: "drain_probe" | "warm_resume" | "continuity_restore"; leaseId: string; lostEpoch: number; instanceId: string | null; workspaceGeneration: number; observedAt: string; /** The lost object's recorded hard provider deadline, when known. */ providerDeadlineAt: string | null; /** Backend-specific proof that the lost object, and with it every copy of * the workspace that only it held, no longer exists anywhere. A NotFound on * its own is an observation, not proof: without this (or Modal's hard * lifetime, or the compute control plane's own answer) the loss may at most * restore a checkpoint, never continue on an empty workspace. */ deathProof?: ProviderDeathProof; /** The drain stopped the box itself after its saves kept failing (it did * not vanish). The people in the chat were told when it stopped, so the * later restore of the save made at `unsavedSince` does not announce the * loss a second time. */ captureAbandoned?: true; /** With `captureAbandoned`: the time of the last good save the stop notice * named, or null when there was none. Absent on records that predate it. */ unsavedSince?: string | null; }; type ProviderDeathProof = { /** `workspace_absent`: the same Docker daemon reports the exact container * gone and its owned host workspace directory no longer exists. * `provider_lifetime`: the provider ends every box within a known bound, * so none can still be running after `provenAt`. */ kind: "workspace_absent" | "provider_lifetime"; provenAt: string; }; function parsedProviderDeathProof(value: unknown): ProviderDeathProof | null | undefined { if (value === undefined) return undefined; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const proof = value as Record; return (proof.kind === "workspace_absent" || proof.kind === "provider_lifetime") && typeof proof.provenAt === "string" && Number.isFinite(Date.parse(proof.provenAt)) ? { kind: proof.kind, provenAt: proof.provenAt } : null; } function providerLossRecord( resumeState: Record | null | undefined, ): ProviderLossRecord | null { const value = resumeState?.[PROVIDER_LOSS_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const record = value as Record; return record.version === 1 && (record.source === "drain_probe" || record.source === "warm_resume" || record.source === "continuity_restore") && typeof record.leaseId === "string" && typeof record.lostEpoch === "number" && Number.isSafeInteger(record.lostEpoch) && (typeof record.instanceId === "string" || record.instanceId === null) && typeof record.workspaceGeneration === "number" && Number.isSafeInteger(record.workspaceGeneration) && typeof record.observedAt === "string" && Number.isFinite(Date.parse(record.observedAt)) && (record.providerDeadlineAt === null || (typeof record.providerDeadlineAt === "string" && Number.isFinite(Date.parse(record.providerDeadlineAt)))) && parsedProviderDeathProof(record.deathProof) !== null ? (record as ProviderLossRecord) : null; } function timestampIso(value: Date | string | null | undefined): string | null { if (value === null || value === undefined) return null; const parsed = value instanceof Date ? value.getTime() : Date.parse(value); return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null; } /** The loss record a definitive loss transition commits for `row`. */ function providerLossRecordForLostRow( row: LeaseRow, source: ProviderLossRecord["source"], observedAt: string, /** The provider's bound on how long any box can still run after this * observation (its hard lifetime, or the renewable TTL nobody renews any * more), when it has one. */ providerMaxRemainingLifetimeMs?: number | null, ): ProviderLossRecord { const lifetimeEndsAt = typeof providerMaxRemainingLifetimeMs === "number" && Number.isSafeInteger(providerMaxRemainingLifetimeMs) && providerMaxRemainingLifetimeMs >= 0 ? Date.parse(observedAt) + providerMaxRemainingLifetimeMs + PROVIDER_CREATE_DEADLINE_GRACE_MS : null; return { version: 1, source, leaseId: row.id, lostEpoch: Number(row.lease_epoch), instanceId: row.instance_id, workspaceGeneration: Number(row.workspace_generation), observedAt, providerDeadlineAt: timestampIso(row.provider_deadline_at), ...(lifetimeEndsAt !== null && Number.isFinite(lifetimeEndsAt) ? { deathProof: { kind: "provider_lifetime" as const, provenAt: new Date(lifetimeEndsAt).toISOString(), }, } : {}), }; } /** The carried loss record with `workspace_absent` proof added, minting the * record when an older loss transition never wrote one. Never moves a record * to another lease or workspace generation. */ function providerLossRecordWithWorkspaceAbsent( row: LeaseRow, provenAt: string, ): ProviderLossRecord { const carried = providerLossRecord(row.resume_state); const base = carried && carried.leaseId === row.id && carried.workspaceGeneration === Number(row.workspace_generation) ? carried : providerLossRecordForLostRow(row, "continuity_restore", provenAt); return { ...base, deathProof: { kind: "workspace_absent", provenAt } }; } function resumeStateWithPreservedArchives( resumeState: Record | null, archiveSource: Record | null, ): Record | null { const preserved = resumeStateWithPreservedArchiveFields(resumeState, archiveSource); // A pending empty-workspace decision and the loss evidence behind it are not // archive truth, so they survive even when the lost lease had no archive. const fresh = retainedFreshWorkspaceRecovery(archiveSource); const loss = providerLossRecord(archiveSource); const retry = archiveSource?.opengeniWorkspaceRecoveryRequest; if (!fresh && !loss && !retry) return preserved; return { ...(preserved ?? {}), ...(fresh ? { [FRESH_WORKSPACE_RECOVERY_KEY]: fresh } : {}), ...(loss ? { [PROVIDER_LOSS_KEY]: loss } : {}), // Preserve the accepted operation across provider envelopes so a client // whose POST response was lost can reconcile the verified result by ID. ...(retry ? { opengeniWorkspaceRecoveryRequest: retry } : {}), }; } function resumeStateWithPreservedArchiveFields( resumeState: Record | null, archiveSource: Record | null, ): Record | null { const sourceSession = archiveSource?.sessionState && typeof archiveSource.sessionState === "object" ? (archiveSource.sessionState as Record) : undefined; if (!sourceSession) return resumeState; const archiveFields: Record = {}; for (const key of WORKSPACE_ARCHIVE_SESSION_KEYS) { if (sourceSession[key] !== undefined && sourceSession[key] !== null) { archiveFields[key] = sourceSession[key]; } } if (Object.keys(archiveFields).length === 0) return resumeState; const targetSession = resumeState?.sessionState && typeof resumeState.sessionState === "object" ? (resumeState.sessionState as Record) : {}; return { ...(resumeState ?? {}), ...(typeof archiveSource?.opengeniHistoricalArchiveRecoveryId === "string" ? { opengeniHistoricalArchiveRecoveryId: archiveSource.opengeniHistoricalArchiveRecoveryId, } : {}), ...(archiveSource?.opengeniAutomaticCheckpointRecovery && typeof archiveSource.opengeniAutomaticCheckpointRecovery === "object" ? { opengeniAutomaticCheckpointRecovery: archiveSource.opengeniAutomaticCheckpointRecovery, } : {}), ...(resumeState?.backendId === undefined && archiveSource?.backendId !== undefined ? { backendId: archiveSource.backendId } : {}), sessionState: omitInlineWorkspaceArchiveWhenObjectRefPresent({ ...targetSession, ...archiveFields, }), }; } function archiveOnlyResumeState( row: LeaseRow, recovery: SandboxRecoveryState, providerLoss?: ProviderLossRecord, ): Record { const carriedLoss = providerLoss ?? providerLossRecord(row.resume_state); const current = row.resume_state && typeof row.resume_state === "object" ? row.resume_state : undefined; const currentSession = current?.sessionState && typeof current.sessionState === "object" ? (current.sessionState as Record) : undefined; const sessionState: Record = {}; for (const key of WORKSPACE_ARCHIVE_SESSION_KEYS) { if (currentSession?.[key] !== undefined && currentSession[key] !== null) { sessionState[key] = currentSession[key]; } } const durableSession = Object.keys(sessionState).length > 0 ? omitInlineWorkspaceArchiveWhenObjectRefPresent(sessionState) : sessionState; return { backendId: typeof current?.backendId === "string" ? current.backendId : (row.resume_backend_id ?? row.backend), ...(Object.keys(durableSession).length > 0 ? { sessionState: durableSession } : {}), ...(typeof current?.opengeniHistoricalArchiveRecoveryId === "string" ? { opengeniHistoricalArchiveRecoveryId: current.opengeniHistoricalArchiveRecoveryId, } : {}), ...(current?.opengeniAutomaticCheckpointRecovery && typeof current.opengeniAutomaticCheckpointRecovery === "object" ? { opengeniAutomaticCheckpointRecovery: current.opengeniAutomaticCheckpointRecovery, } : {}), ...(retainedFreshWorkspaceRecovery(current) ? { [FRESH_WORKSPACE_RECOVERY_KEY]: retainedFreshWorkspaceRecovery(current) } : {}), ...(current?.opengeniWorkspaceRecoveryRequest ? { opengeniWorkspaceRecoveryRequest: current.opengeniWorkspaceRecoveryRequest } : {}), ...(carriedLoss ? { [PROVIDER_LOSS_KEY]: carriedLoss } : {}), opengeniRecovery: recovery, }; } /** The cold envelope of a WARMING lease whose creator died before any provider * instance was recorded. The global reaper's SQL routine * opengeni_private.warming_reset_resume_state_v2 implements the same rules; * keep the two identical. The selected archive (inline or object reference) * and every recovery marker survive. A lease that recorded a published archive * generation but lost its archive pointer fails closed as unrecoverable, so the * next turn is blocked visibly instead of starting on an empty workspace. Only * a lease that never had an archive or recovery state resets to null. */ function warmingResetResumeState(row: LeaseRow, resetAt: string): Record | null { const current = recoveryStateFromLeaseRow(row); const hasArchive = current.archive.status !== "none"; if ( !hasArchive && // An authorized empty-workspace continuation keeps its decision (and its // blocked lost-workspace truth) when no archive exists. pendingFreshWorkspaceRecovery(row.resume_state) === null && providerLossRecord(row.resume_state) === null && row.archive_generation === null ) { return null; } const restoreStatus: SandboxRestoreStatus = hasCompleteWorkspaceArchive(row) ? "pending" : hasArchive ? "degraded" : "unrecoverable"; return archiveOnlyResumeState(row, { provider: { status: "not_created", instanceId: null, observedAt: resetAt }, archive: current.archive, restore: { status: restoreStatus, rematerializationId: null, selectedRevision: current.archive.current?.revision ?? null, startedAt: null, completedAt: resetAt, ...(restoreStatus === "degraded" ? { failureCode: current.archive.status === "available" ? "archive_generation_mismatch" : "archive_unverified", retryable: false, } : restoreStatus === "unrecoverable" ? { failureCode: "archive_unavailable", retryable: false } : {}), }, workspace: { status: restoreStatus === "pending" ? "not_ready" : restoreStatus === "degraded" ? "degraded" : "unrecoverable", verifiedRevision: null, verifiedAt: null, }, }); } function providerStateFromLeaseResumeState(row: LeaseRow): Record | null { const resume = row.resume_state; if (!resume || typeof resume !== "object") return null; const sessionState = resume.sessionState && typeof resume.sessionState === "object" ? (resume.sessionState as Record) : resume; const providerState = sessionState.providerState; return providerState && typeof providerState === "object" && !Array.isArray(providerState) ? (providerState as Record) : null; } /** Docker's container is disposable; its owned host workspace is the durable * provider resource. The SDK is configured without local snapshots, so an * elected owner can restart a missing container on this exact path without * restoring older bytes over it. Every predicate is intentionally explicit. */ function dockerContinuityRecoveryFromLeaseRow( row: LeaseRow, sourceInstanceId: string | null, ): SandboxProviderContinuityRecovery | null { if ( (row.resume_backend_id ?? row.backend) !== "docker" || !sourceInstanceId || !row.resume_state ) { return null; } const providerState = providerStateFromLeaseResumeState(row); const declared = row.resume_state[OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD]; const containerId = providerState?.containerId; const workspaceRootPath = providerState?.workspaceRootPath; if ( (declared !== undefined && declared !== sourceInstanceId) || containerId !== sourceInstanceId || typeof workspaceRootPath !== "string" || !workspaceRootPath.startsWith("/") || workspaceRootPath.length > 4096 || workspaceRootPath.includes("\0") || providerState?.workspaceRootOwned !== true || (providerState.snapshot !== null && providerState.snapshot !== undefined) ) { return null; } return { version: 1, backend: "docker", kind: "docker_workspace", sourceInstanceId, continuityKey: workspaceRootPath, }; } function continuityRecoveryFromLeaseRow(row: LeaseRow): SandboxProviderContinuityRecovery | null { const current = recoveryStateFromLeaseRow(row).continuity; const derived = dockerContinuityRecoveryFromLeaseRow( row, row.instance_id ?? current?.sourceInstanceId ?? null, ); return derived && (!current || continuityRecoveryEquals(current, derived, false)) ? derived : null; } function continuityRecoveryEquals( left: SandboxProviderContinuityRecovery | null | undefined, right: SandboxProviderContinuityRecovery | null | undefined, compareSourceInstance = true, ): boolean { return Boolean( left && right && left.version === right.version && left.backend === right.backend && left.kind === right.kind && (!compareSourceInstance || left.sourceInstanceId === right.sourceInstanceId) && left.continuityKey === right.continuityKey, ); } function recoveryResumeState( row: LeaseRow, recovery: SandboxRecoveryState, providerLoss?: ProviderLossRecord, ): Record { return recovery.continuity ? { ...resumeStateWithRecovery(row.resume_state, recovery), ...(providerLoss ? { [PROVIDER_LOSS_KEY]: providerLoss } : {}), } : archiveOnlyResumeState(row, recovery, providerLoss); } function archiveProjectionFromResumeState( resumeState: Record | null, ): SandboxRecoveryState["archive"] { const sessionState = resumeState?.sessionState && typeof resumeState.sessionState === "object" ? (resumeState.sessionState as Record) : undefined; const currentPresent = workspaceArchivePayloadPresent(sessionState); const previousPresent = (typeof sessionState?.workspaceArchivePrev === "string" && sessionState.workspaceArchivePrev.length > 0) || parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchivePrevRef) !== null; const current = parseArchiveRevision(sessionState?.workspaceArchiveMeta); const previous = parseArchiveRevision(sessionState?.workspaceArchivePrevMeta); return { status: currentPresent ? current ? "available" : "unverified" : previousPresent ? "unverified" : "none", current, previous, }; } // Recompute refcount/split-counts from the holder rows (holders are the source // of truth), refresh expires_at, optionally set liveness. Returns the updated row. async function recomputeAndStampLease( tx: Database, leaseId: string, leaseTtlMs: number, setLiveness: SandboxLeaseLiveness | null, ): Promise { const counts = await tx.execute<{ total: number; turns: number; viewers: number; untracked_writers: number; }>(sql` select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers, count(*) filter (where kind in ('viewer', 'interaction'))::int as untracked_writers from sandbox_lease_holders where lease_id = ${leaseId} `); const c = counts[0]!; const updated = await tx.execute(sql` update sandbox_leases set refcount = ${c.total}, turn_holders = ${c.turns}, viewer_holders = ${c.viewers}, -- A viewer or interaction can write /workspace without a generation -- admission. Remember the earliest such attach until a capture taken -- with none attached covers it, so a writer that detached before the -- next capture still leaves the box dirty. ${ c.untracked_writers > 0 ? sql`untracked_writer_since = coalesce(untracked_writer_since, now()),` : sql`` } expires_at = now() + (${String(leaseTtlMs)} || ' milliseconds')::interval, ${setLiveness ? sql`liveness = ${setLiveness},` : sql``} updated_at = now() where id = ${leaseId} returning * `); return updated[0]!; } // Idempotent acquire: the unique (lease, kind, holder) index makes a retried or // duplicate acquire a no-op heartbeat refresh, never a double-count. async function upsertLeaseHolder( tx: Database, leaseId: string, accountId: string, workspaceId: string, kind: LeaseHolderKind, holderId: string, subjectId: string | null, viewerAuthority: { subjectId: string | null; authorityEpoch: number | null; /** Viewer holders only: the attaching page's reported interaction age. */ interactionAgeMs?: number | null; } = { subjectId: null, authorityEpoch: null, }, ): Promise { const interactionAgeMs = kind === "viewer" ? normalizeViewerInteractionAgeMs(viewerAuthority.interactionAgeMs) : null; const lastInteractionAt = interactionAgeMs === null ? sql`null::timestamptz` : sql`now() - (${String(interactionAgeMs)} || ' milliseconds')::interval`; await tx.execute(sql` insert into sandbox_lease_holders (account_id, workspace_id, lease_id, kind, holder_id, subject_id, viewer_subject_id, viewer_authority_epoch, last_heartbeat_at, last_interaction_at) values (${accountId}, ${workspaceId}, ${leaseId}, ${kind}, ${holderId}, ${subjectId}, ${viewerAuthority.subjectId}, ${viewerAuthority.authorityEpoch}, now(), ${lastInteractionAt}) on conflict (lease_id, kind, holder_id) do update set last_heartbeat_at = now(), last_interaction_at = greatest( sandbox_lease_holders.last_interaction_at, excluded.last_interaction_at), viewer_subject_id = coalesce(excluded.viewer_subject_id, sandbox_lease_holders.viewer_subject_id), -- The recorded (subject, epoch) pair stays coherent. Same subject (or -- a claimless rolling-window attach): the epoch is monotone - a -- re-acquire may raise it but never lower it. A DIFFERENT subject -- reusing the holder id starts a fresh pair; carrying the previous -- subject's higher epoch would misattribute authority evidence. viewer_authority_epoch = case when excluded.viewer_subject_id is not null and sandbox_lease_holders.viewer_subject_id is not null and excluded.viewer_subject_id is distinct from sandbox_lease_holders.viewer_subject_id then excluded.viewer_authority_epoch else greatest( coalesce(excluded.viewer_authority_epoch, sandbox_lease_holders.viewer_authority_epoch), coalesce(sandbox_lease_holders.viewer_authority_epoch, excluded.viewer_authority_epoch)) end `); } /** * Fence first lease materialization against control-plane mutations that must * prove the sandbox group has no holders. The lease-row lock remains the * canonical holder lock once the row exists; this advisory lock covers only * the otherwise-unlockable absent-row window. */ async function lockSandboxLeaseAdmission( tx: Database, workspaceId: string, sandboxGroupId: string, ): Promise { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended( ${`sandbox-lease-admission:${workspaceId}:${sandboxGroupId}`}, 0 ))`, ); } // §4.1 — the get-or-create critical section. ONE transaction: // insert-or-nothing -> SELECT … FOR UPDATE (block, not skip) -> branch -> bump. // The single most load-bearing function: the sole double-spawn guard. async function acquireLeaseOnce( db: Database, input: AcquireLeaseAdmissionInput, standing: SandboxComputeStanding | null = null, fleet: SandboxFleetAdmission | null = null, ): Promise { if (input.kind === "process") { throw new Error("Process lease holders are created only by atomic retained-process promotion"); } if ( input.retainedInstanceId !== undefined && (input.kind !== "direct" || input.retainedInstanceId.length === 0) ) { throw new Error( "Retained instance admission requires a direct holder and exact provider identity", ); } const { accountId, workspaceId, sandboxGroupId, kind, holderId, backend } = input; const os = input.os ?? "linux"; const subjectId = input.subjectId ?? null; const warmingLeaseTtlMs = input.warmingLeaseTtlMs ?? input.leaseTtlMs; const warmPolicy = input.warmBilling ?? { mode: "usage_only" as const, rateMicrosPerSecond: 0 }; if (!Number.isFinite(warmPolicy.rateMicrosPerSecond) || warmPolicy.rateMicrosPerSecond < 0) { throw new Error("sandbox warm rate must be finite and non-negative"); } return await withRlsContext( db, { accountId, workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const image = input.image ?? null; const rigVersionId = input.rigVersionId ?? null; await lockSandboxLeaseAdmission(tx, workspaceId, sandboxGroupId); // (1) Materialize the singleton row if absent. ON CONFLICT DO NOTHING + the // unique index = idempotent under a race; concurrent inserts collapse to // one row. expires_at seeded so a never-warmed cold row has a valid TTL. The // image (B3) + rig version (M3) are stamped on the cold-create so a fresh box // records what it will be built on; a conflict on an EXISTING live box is // handled below. await tx.execute(sql` insert into sandbox_leases (account_id, workspace_id, sandbox_group_id, liveness, backend, os, image, rig_version_id, expires_at) values (${accountId}, ${workspaceId}, ${sandboxGroupId}, 'cold', ${backend}, ${os}, ${image}, ${rigVersionId}, now() + (${String(input.leaseTtlMs)} || ' milliseconds')::interval) on conflict (workspace_id, sandbox_group_id) do nothing `); // (2) Serialize ALL concurrent arrivals on this group's row. Plain FOR // UPDATE (block, do NOT skip) — unlike concurrent enrollment scans, // because we WANT the loser to block then attach, not skip and lose. const rows = await tx.execute(sql` select lease.*, case when lease.archive_capture_deadline_at is null then null else greatest( 0, ceil(extract(epoch from ( lease.archive_capture_deadline_at - clock_timestamp() )) * 1000) )::bigint end as archive_capture_remaining_ms from sandbox_leases as lease where lease.workspace_id = ${workspaceId} and lease.sandbox_group_id = ${sandboxGroupId} for update `); const row = rows[0]; if (!row) throw new Error(`Lease row vanished post-insert: ${sandboxGroupId}`); const liveness = row.liveness; // Existing browser control and suspension must remain possible after a // deployment changes the image for new boxes. Check under the lease lock // before any holder, re-arm, billing admission or cold-spawner election. if ( input.retainedInstanceId !== undefined && (row.instance_id !== input.retainedInstanceId || row.backend !== backend || (liveness !== "warm" && liveness !== "draining")) ) { return { role: "fenced" as const, reason: "superseded" as const, lease: mapLeaseRow(row), }; } const existingSnapshot = warmBillingSnapshot(row); // The accepted session route selects a replacement backend, not the // backend label of a box that was drained before a deployment move. // Never retarget an existing instance or an outcome-unknown create. if ( row.backend !== backend && (liveness !== "cold" || row.instance_id !== null || row.provider_create_attempt?.instanceId === null || recoveryStateFromLeaseRow(row).continuity) ) { throw new SandboxBackendConflictError(sandboxGroupId, row.backend, backend); } if (row.resume_state?.opengeniWarmBilling && !existingSnapshot) { throw new Error("sandbox warm billing snapshot is invalid"); } const admittedAttribution = await sandboxWarmAdmissionAttribution(tx, input); // Every new paid holder, including direct operations and interaction // controllers, passes the same account funding boundary before it can // elect a spawner, re-arm a drain or prolong a warm lease. Replaying an // existing exact holder does not create new compute authority. const activeMode = input.warmBilling?.mode ?? existingSnapshot?.mode ?? "usage_only"; // Reconfiguration may not substitute a new (possibly zero) rate for // an already-running paid provider's immutable admitted tariff. const activeRate = liveness !== "cold" && existingSnapshot?.mode === "credits" ? existingSnapshot.rateMicrosPerSecond : (input.warmBilling?.rateMicrosPerSecond ?? existingSnapshot?.rateMicrosPerSecond ?? 0); if ( activeMode === "credits" && activeRate > 0 && (liveness === "cold" || (existingSnapshot?.mode === "credits" && existingSnapshot.rateMicrosPerSecond > 0)) ) { const alreadyHeld = await tx.execute<{ held: boolean }>(sql` select exists (select 1 from sandbox_lease_holders where lease_id = ${row.id} and kind = ${kind} and holder_id = ${holderId}) as held `); if (!alreadyHeld[0]?.held) { const attribution = liveness === "cold" ? admittedAttribution : (existingSnapshot?.attribution ?? { kind: "unknown" as const }); if (attribution.kind === "unknown") { throw new SandboxDebitAttributionUnavailableError(workspaceId, sandboxGroupId); } const refusal = await checkWorkspaceAllowance(tx, { accountId, workspaceId, subjectId: attribution.kind === "turn" || attribution.kind === "human" ? attribution.initiatingHumanSubjectId : null, }); if (refusal) { throw Object.assign( new SandboxPaidComputeAdmissionError(workspaceId, sandboxGroupId), refusal, ); } // The box is funded like the work it runs: an API chat's box spends credits. const leaseOrigin = await attributionBillingOrigin(tx, { accountId, workspaceId, attribution, }); const balance = await getSpendableCreditBalance( tx, accountId, undefined, undefined, undefined, leaseOrigin, ); if (balance.balanceMicros <= 0) { throw new SandboxPaidComputeAdmissionError( workspaceId, sandboxGroupId, chargeBillingOrigin(leaseOrigin) === "api" ? `${API_CREDITS_REQUIRED_MESSAGE} Add credits to start this computer.` : undefined, ); } } } // A workspace-wide billing/cap drain survives this lease becoming cold. // Viewer-only admission must consult it while holding the exact lease // row lock, otherwise a dashboard heartbeat can re-arm the draining box // between holder deletion and provider teardown. A live turn remains // viewable: the reaper intentionally drains only boxes with no turn // holder, and this same lock makes the distinction race-free. if ((kind === "viewer" || kind === "interaction") && Number(row.turn_holders) === 0) { const workspaceRows = await tx.execute<{ sandbox_viewer_force_drain_reason: SandboxViewerForceDrainReason | null; }>(sql` select sandbox_viewer_force_drain_reason from workspaces where id = ${workspaceId} `); const reason = workspaceRows[0]?.sandbox_viewer_force_drain_reason ?? null; if (reason === "warm_cap") { throw new SandboxViewerAdmissionBlockedError(workspaceId, sandboxGroupId, reason); } } // A viewer alone can start a box and keep it warm for as long as it // heartbeats, with no task and no model spend. Bound how many such // boxes one workspace, one organization and one member keep warm. // Joining a box that a turn, another viewer, a live process or a // Browser/ComputerSession already keeps warm adds no compute and is // always admitted, as is replaying this exact holder. A // host-provisioned (`embedded`) or `enterprise` organization is // outside the per-workspace limit as well as the plan limits its tier // does not set. // The standing read before this transaction carries the tier (and any // linked restriction); without one (no plan limits, or its read // failed) the tier is read here. const planTier = standing !== null ? standing.tier : input.sandboxPlanLimits || (input.viewerOnlyBoxLimit ?? 0) > 0 ? await resolveSandboxPlanTier(tx, accountId, input.sandboxPlanLimits) : null; const viewerOnlyBoxLimit = planTier !== null && sandboxPlanTierExemptFromViewerOnlyBounds(planTier) ? 0 : (input.viewerOnlyBoxLimit ?? 0); // An unpaid-tier organization that bought credit or paid for a plan // is a paying customer: none of the unpaid-only bounds apply. const tierLimit = input.sandboxPlanLimits && planTier !== null ? sandboxPlanLimitFor(input.sandboxPlanLimits, planTier) : {}; const planLimit = standing?.paidHistory ? paidSandboxPlanLimit(tierLimit) : tierLimit; // Free-compute bounds shared by every holder kind (docs/deployment.md, // "Free compute bounds"). A closed tier (running limit 0) or a spent // daily box-time budget refuses every holder, including a join, a // re-arm or a replayed holder, of a box no turn keeps warm. A warm box // a turn holds admits everything that turn and its people use (the // agent's own requests, its Browser/ComputerSessions, someone // watching), so an in-flight turn finishes; the reaper drains only // boxes no turn holds. Any other turn fails with a clear message // instead of waiting for a slot that will not come. A Connected // Machine never counts. // The card trial: until the tier's cardTrialBoxSeconds are used, an // agent turn of an organization that still needs a card may start a // box, one at a time (checked with the running-box limits below). Every // other holder kind still needs the card, and every bound after the // card still applies. const cardTrialTurn = backend !== "selfhosted" && kind === "turn" && standing?.cardRequired === true && standing.cardTrial === true; if (backend !== "selfhosted") { const refusal: SandboxOrganizationBoxLimitReason | null = planLimit.runningBoxesPerOrganization === 0 ? "closed" : standing?.cardRequired === true && !cardTrialTurn && // Once the card trial is used, joining its box needs the // card too, unless a turn still holds it (below). (standing.cardTrialSpent === true || (row.liveness !== "warm" && row.liveness !== "warming")) ? "card_required" : standing !== null && standing.bounded && sandboxDailyBoxTimeSpent(planLimit, standing) ? "daily_budget" : sandboxYoungBoxTimeSpent(fleet) ? "young_box_time" : kind !== "turn" && row.liveness !== "warm" && row.liveness !== "warming" && sandboxYoungTurnlessTimeSpent(fleet) ? "young_turnless" : null; const turnHeldWarm = row.liveness === "warm" && Number(row.turn_holders) > 0; if (refusal !== null && !turnHeldWarm) { const inFlightTurn = kind === "turn" && Boolean( ( await tx.execute<{ held: boolean }>(sql` select exists (select 1 from sandbox_lease_holders where lease_id = ${row.id} and kind = 'turn' and holder_id = ${holderId}) as held `) )[0]?.held, ); if (!inFlightTurn) { throw new SandboxOrganizationBoxLimitError( workspaceId, sandboxGroupId, refusal === "closed" || refusal === "card_required" ? 0 : refusal === "young_box_time" ? (fleet?.limits.youngOrganizationBoxSeconds ?? 0) : refusal === "young_turnless" ? (fleet?.limits.youngTurnlessBoxSeconds ?? 0) : sandboxDailyBoxTimeLimitSeconds(planLimit, standing), refusal, ); } } } const organizationViewerLimit = planLimit.viewerOnlyBoxesPerOrganization; const memberViewerLimit = input.viewerSubjectId ? planLimit.viewerOnlyBoxesPerMember : undefined; if ( kind === "viewer" && Number(row.turn_holders) === 0 && (viewerOnlyBoxLimit > 0 || organizationViewerLimit !== undefined || memberViewerLimit !== undefined) ) { const current = await tx.execute<{ held: boolean; joins_live_box: boolean }>(sql` select exists (select 1 from sandbox_lease_holders where lease_id = ${row.id} and kind = 'viewer' and holder_id = ${holderId}) as held, (${liveness}::text in ('warming', 'warm') and exists (select 1 from sandbox_lease_holders where lease_id = ${row.id} and kind in ('viewer', 'process', 'interaction'))) as joins_live_box `); if (!current[0]?.held && !current[0]?.joins_live_box) { // Two viewers on different groups each hold only their own group // lock. The organization key serializes their counts so every // limit is exact. await lockOrganizationSandboxLimit(tx, accountId); if (organizationViewerLimit === 0 || memberViewerLimit === 0) { throw new SandboxViewerBoxLimitError( workspaceId, sandboxGroupId, 0, organizationViewerLimit === 0 ? "organization" : "member", ); } if (viewerOnlyBoxLimit > 0) { const others = await tx.execute<{ n: number }>(sql` select count(*)::int as n from sandbox_leases other where other.workspace_id = ${workspaceId} and other.id <> ${row.id} and other.liveness in ('warming', 'warm') and other.turn_holders = 0 and exists (select 1 from sandbox_lease_holders h where h.lease_id = other.id and h.kind = 'viewer') `); if (Number(others[0]?.n ?? 0) >= viewerOnlyBoxLimit) { throw new SandboxViewerBoxLimitError( workspaceId, sandboxGroupId, viewerOnlyBoxLimit, ); } } if (organizationViewerLimit !== undefined || memberViewerLimit !== undefined) { const counts = await organizationWarmSandboxCounts(tx, { accountId, subjectId: input.viewerSubjectId ?? null, excludeLeaseId: row.id, }); if ( organizationViewerLimit !== undefined && counts.viewerOnlyBoxes >= organizationViewerLimit ) { throw new SandboxViewerBoxLimitError( workspaceId, sandboxGroupId, organizationViewerLimit, "organization", ); } if ( memberViewerLimit !== undefined && counts.subjectViewerOnlyBoxes >= memberViewerLimit ) { throw new SandboxViewerBoxLimitError( workspaceId, sandboxGroupId, memberViewerLimit, "member", ); } } } } const viewerInteractionAgeMs = kind === "viewer" ? normalizeViewerInteractionAgeMs(input.viewerInteractionAgeMs) : null; // Viewer-only idle drain: the reaper released this box's viewers // because nobody used the page. For one more idle window, an attach // that reports no interaction since then (an unattended page or an // older client re-attaching on its own) must not warm it again and // reset the idle clock. A person who interacts, a turn in the session, // a box someone else already holds, or any attach after that window // (a person returning on an older client) admits it as usual. const viewerIdleDrainedAt = (row as { viewer_idle_drained_at?: Date | string | null }) .viewer_idle_drained_at; if ( kind === "viewer" && (input.viewerIdleReattachRefusalMs ?? 0) > 0 && viewerIdleDrainedAt !== null && viewerIdleDrainedAt !== undefined && Number(row.turn_holders) === 0 ) { const idleRows = await tx.execute<{ refuse: boolean }>(sql` select ( ${viewerIdleDrainedAt}::timestamptz > now() - (${String( Math.floor(input.viewerIdleReattachRefusalMs ?? 0), )} || ' milliseconds')::interval and not exists ( select 1 from sandbox_lease_holders holder where holder.lease_id = ${row.id} ) and ${ viewerInteractionAgeMs === null ? sql`true` : sql`now() - (${String(viewerInteractionAgeMs)} || ' milliseconds')::interval <= ${viewerIdleDrainedAt}::timestamptz` } and not exists ( select 1 from sessions chat where chat.workspace_id = ${workspaceId} and chat.sandbox_group_id = ${sandboxGroupId} and ( chat.status in (${sql.raw( VIEWER_ONLY_OPEN_SESSION_STATUSES.map((status) => `'${status}'`).join(", "), )}) or exists ( select 1 from session_turns turn where turn.workspace_id = chat.workspace_id and turn.session_id = chat.id and ( turn.created_at > ${viewerIdleDrainedAt}::timestamptz or turn.finished_at > ${viewerIdleDrainedAt}::timestamptz ) ) ) ) ) as refuse `); if (idleRows[0]?.refuse === true) { throw new SandboxViewerAdmissionBlockedError( workspaceId, sandboxGroupId, "viewer_idle", ); } // Admitted: the session is in use again; the marker has done its job. await tx.execute(sql` update sandbox_leases set viewer_idle_drained_at = null where id = ${row.id} `); } // Provider-native capture may temporarily pause the box. Do not attach // another holder while that operation owns the exact lease: the caller // retries after the claim clears, before it can reach the provider. if (row.archive_capture_id !== null) { const captureRemainingMs = archiveCaptureRemainingMs(row); return { role: "fenced" as const, reason: "capture_in_progress" as const, lease: mapLeaseRow(row), ...(captureRemainingMs === null ? {} : { captureRemainingMs }), }; } // A finite-lifetime provider instance is already being replaced. Do not // admit another holder onto the old box: the current holders own its // quiescence, snapshot, and drain; every new arrival retries after the // cold->warming successor election. if (liveness !== "cold" && row.rotation_requested_at !== null) { return { role: "fenced" as const, reason: "rotation_in_progress" as const, lease: mapLeaseRow(row), }; } // A creator died before publishing its resumable envelope or verifying // the workspace. The attributed provider may still be live, // but an arrival has no verified state with which to attach. Keep this // exceptional row transiently fenced until the reaper captures/settles // it; unlike an ordinary expired drain, re-arming it cannot restore // service and would strand an unmanageable provider. if ( liveness === "draining" && (!hasRearmableWorkspace(row) || (leaseBackendRequiresResumableInstance(row) && !hasResumableLeaseInstance(row))) ) { return { role: "fenced" as const, reason: "provider_recovery_in_progress" as const, lease: mapLeaseRow(row), }; } // -- SHARED STATE CONFLICT (B3 image + M3 rig): a LIVE box (warm/draining/warming) // was created under a specific image AND rig version. If this run resolves a // DIFFERENT required image OR a DIFFERENT rig version (each checked only when both sides are // known), the one shared filesystem cannot serve both. Under the held row lock we // count the OTHER holders (not this exact (kind, holderId) — an idempotent retry of // our own holder is not a rival): // - SOLO (no other holders): ROTATE. Preserve the attributed provider instance and // durable checkpoint, request an immediate operator rotation, and fence this // arrival. Its idempotent release drops the final holder; the sole reaper then // captures /workspace, terminates the old provider, and confirms cold. A retry // stamps the new image/rig only when it wins the cold successor election. // - OTHER holders present: REFUSE. Throw — recreating would yank the running // filesystem out from under the other sessions. Image conflict is reported first // so its (pre-rig) error is unchanged for the image-only case. // Deployment pins (new_creates_only) retain the live image instead. Each required // axis is enforced only when BOTH sides are known; a cold row / a legacy null / // an unset input never conflicts (the selfhosted path passes neither; a rig-less run // passes no rigVersionId, so it never stamps or conflicts on rig). const imageConflict = input.retainedInstanceId === undefined && input.imagePolicy !== "new_creates_only" && image !== null && row.image !== null && row.image !== image; const rigConflict = rigVersionId !== null && row.rig_version_id !== null && row.rig_version_id !== rigVersionId; if (liveness !== "cold" && (imageConflict || rigConflict)) { const others = await tx.execute<{ n: number }>(sql` select count(*)::int as n from sandbox_lease_holders where lease_id = ${row.id} and not (kind = ${kind} and holder_id = ${holderId}) `); const otherHolders = Number(others[0]?.n ?? 0); if (otherHolders > 0) { if (imageConflict) { throw new SandboxImageConflictError( sandboxGroupId, row.image as string, image as string, ); } throw new SandboxRigConflictError( sandboxGroupId, row.rig_version_id as string, rigVersionId as string, ); } // A live provider may be deleted only by the reaper after a verified // capture. Never manufacture a cold row or erase its provider/checkpoint // attribution here. Expiring the lease makes warming/draining conflicts // immediately eligible; a warm conflict reaches draining when the fenced // caller releases its exact final holder. const rotating = await tx.execute(sql` update sandbox_leases set rotation_requested_at = coalesce(rotation_requested_at, now()), rotation_reason = coalesce(rotation_reason, 'operator'), expires_at = least(expires_at, now()), updated_at = now() where id = ${row.id} returning * `); return { role: "fenced" as const, reason: "rotation_in_progress" as const, lease: mapLeaseRow(rotating[0] ?? row), }; } // -- draining: a late arrival re-arms until the reaper has acquired the // exact durable archive-capture claim checked above. `expires_at` makes a // row eligible for cleanup; it is never teardown ownership by itself. // The row lock serializes this holder insertion against the reaper claim: // whichever wins first owns the next state without an availability gap. if (liveness === "draining") { // Capture may have failed after an earlier stop attempt recorded a // cutoff. The box is wanted again: a provider that was never stopped // keeps running, and a Docker container stopped for a capture is // restored on its workspace by the arriving owner. Either way the // re-armed box needs a fresh charge horizon for its next drain. if (warmBillingSnapshot(row)?.stopChargeAt) { await tx.execute(sql` update sandbox_leases set resume_state = resume_state #- '{opengeniWarmBilling,stopChargeAt}', updated_at = now() where id = ${row.id} `); } if (row.group_end_requested_at) { // Re-armed: whatever group end was requested did not happen. await tx.execute(sql` update sandbox_leases set group_end_requested_at = null, updated_at = now() where id = ${row.id} `); } if (Number(row.drain_capture_failures ?? 0) > 0) { // Re-armed: the drain ended without a save, so its failures no // longer describe the next one. A later drain starts with a full // snapshot and no backoff, and only failures of that drain can // lead to a reduced save or a stop (sandboxDrainCaptureFallback). await tx.execute(sql` update sandbox_leases set drain_capture_failures = 0, drain_capture_failure_epoch = null, drain_capture_first_failed_at = null, drain_capture_last_failed_at = null, updated_at = now() where id = ${row.id} `); } await upsertLeaseHolder(tx, row.id, accountId, workspaceId, kind, holderId, subjectId, { subjectId: input.viewerSubjectId ?? null, authorityEpoch: input.viewerAuthorityEpoch ?? null, interactionAgeMs: viewerInteractionAgeMs, }); const updated = await recomputeAndStampLease(tx, row.id, input.leaseTtlMs, "warm"); return { role: "rearmed" as const, lease: mapLeaseRow(updated) }; } // -- cold: WIN the cold->warming CAS (C1). Exactly one winner under the // held row lock; concurrent arrivals serialize behind us and see warming. // The image (B3) is (re-)stamped on the CAS so the box the spawner cold-creates // records the image it runs — for a fresh cold row or a successor after // rotation/reaping. Deployment pins do not relabel a reused live box. if (liveness === "cold") { const recovery = recoveryStateFromLeaseRow(row); // An audited system decision to continue on an EMPTY workspace makes // the lost workspace's blocked restore truth non-blocking for exactly // one kind of publication: a new box with no archive hydrated. const freshWorkspaceRecoveryId = await authorizedFreshWorkspaceRecoveryId(tx, row); if ( freshWorkspaceRecoveryId === null && // A failure verdict describes an earlier restore, not immutable // archive truth. Revalidate the exact CURRENT generation with the // current loader/provider configuration. Election, selected-revision // verification and warm publication still fence every replacement. // Missing/unverified archives and generation gaps need an explicit // recovery decision; never silently substitute an older archive. !canRevalidateCurrentWorkspaceArchive(row) && ((recovery.restore.status === "degraded" && recovery.restore.retryable !== true) || recovery.restore.status === "unrecoverable") && (await authorizedHistoricalArchiveGeneration(tx, row)) === null ) { return { role: "blocked" as const, code: recovery.restore.status === "degraded" ? ("restore_degraded" as const) : ("restore_unrecoverable" as const), lease: mapLeaseRow(row), }; } // A new box counts against the organization's running-box limit for // its plan. Attaching to, or re-arming, a box that already runs // adds none and never reaches this election. // The acting person's limited organizations share a second budget // (runningBoxesPerPerson); their other organizations' boxes were // counted before this transaction. // A young unpaid organization runs fewer boxes (fleet limits). // It counts boxes a turn or a person's own work keeps warm, not // boxes only viewers keep warm (the viewer-only limits bound those), // so an open desktop does not park the organization's next chat. const youngLimit = backend !== "selfhosted" && kind !== "viewer" && fleet !== null && fleet.young && fleet.limits.youngOrganizationRunningBoxes !== undefined ? fleet.limits.youngOrganizationRunningBoxes : undefined; const runningBoxLimit = backend === "selfhosted" ? undefined : planLimit.runningBoxesPerOrganization; const personBoxLimit = backend === "selfhosted" || standing === null || !standing.bounded ? undefined : planLimit.runningBoxesPerPerson; if ( runningBoxLimit !== undefined || personBoxLimit !== undefined || youngLimit !== undefined || cardTrialTurn ) { await lockOrganizationSandboxLimit(tx, accountId); const counts = !cardTrialTurn && (runningBoxLimit === 0 || personBoxLimit === 0 || youngLimit === 0) ? null : await organizationWarmSandboxCounts(tx, { accountId, subjectId: null, excludeLeaseId: row.id, }); // A trial box runs alone: while another box runs, the card is // asked for instead of waiting for it. if (cardTrialTurn && (counts === null || counts.runningBoxes > 0)) { throw new SandboxOrganizationBoxLimitError( workspaceId, sandboxGroupId, 0, "card_required", ); } const organizationFull = runningBoxLimit !== undefined && (runningBoxLimit === 0 || (counts !== null && counts.runningBoxes >= runningBoxLimit)); const youngFull = !organizationFull && youngLimit !== undefined && (youngLimit === 0 || (counts !== null && counts.runningBoxes - counts.viewerOnlyBoxes >= youngLimit)); const personFull = !organizationFull && !youngFull && personBoxLimit !== undefined && (personBoxLimit === 0 || (counts !== null && (standing?.personOwnsOrganization ? counts.runningBoxes : 0) + (standing?.personOtherRunningBoxes ?? 0) >= personBoxLimit)); if (organizationFull || youngFull || personFull) { const limit = organizationFull ? (runningBoxLimit ?? 0) : youngFull ? (youngLimit ?? 0) : (personBoxLimit ?? 0); if (kind !== "turn") { throw new SandboxOrganizationBoxLimitError( workspaceId, sandboxGroupId, limit, organizationFull ? "running" : youngFull ? "young_running" : "person_running", ); } return { role: "fenced" as const, reason: "organization_sandbox_capacity" as const, lease: mapLeaseRow(row), organizationBoxLimit: limit, }; } } // Every unpaid organization together (fleet limits): a new box past // the fleet's box time, its running cap, or while the fleet is // under pressure is refused for every holder kind; a turn fails with // the reason rather than waiting. Joining a running box never gets // here. Reads that fail refuse (fail closed) for unpaid boxes only. const unpaidBox = backend !== "selfhosted" && sandboxFleetBounded(standing); if (unpaidBox && fleet !== null) { await enforceSandboxFleetLimits(tx, { fleet, leaseId: row.id, workspaceId, sandboxGroupId, onFallback: input.onComputeStandingFallback, }); } const casRows = await tx.execute<{ id: string }>(sql` update sandbox_leases set liveness = 'warming', backend = ${backend}, compute_unpaid = ${unpaidBox}, ${ input.warmBilling ? sql`resume_state = coalesce(resume_state, '{}'::jsonb) || jsonb_build_object('opengeniWarmBilling', ${JSON.stringify({ mode: warmPolicy.mode, rateMicrosPerSecond: warmPolicy.rateMicrosPerSecond, accountId, workspaceId, attribution: admittedAttribution, })}::jsonb),` : sql`` } ${image !== null ? sql`image = ${image},` : sql``} ${rigVersionId !== null ? sql`rig_version_id = ${rigVersionId},` : sql``} updated_at = now() where id = ${row.id} and liveness = 'cold' returning id `); await upsertLeaseHolder(tx, row.id, accountId, workspaceId, kind, holderId, subjectId, { subjectId: input.viewerSubjectId ?? null, authorityEpoch: input.viewerAuthorityEpoch ?? null, interactionAgeMs: viewerInteractionAgeMs, }); const updated = await recomputeAndStampLease(tx, row.id, warmingLeaseTtlMs, null); // casRows.length === 0 cannot happen under the held row lock (defensive): // a lost CAS means a sibling flipped it first, so we attach. const role = casRows.length === 0 ? ("attached" as const) : ("spawner" as const); return { role, ...(planTier !== null ? { sandboxPlanTier: planTier } : {}), ...(standing?.paidHistory ? { sandboxPaidHistory: true } : {}), lease: { ...mapLeaseRow(updated), historicalRecoveryAuthorized: freshWorkspaceRecoveryId === null && (await authorizedHistoricalArchiveGeneration(tx, updated)) !== null, ...(freshWorkspaceRecoveryId ? { freshWorkspaceRecoveryId } : {}), }, }; } // -- warm: epoch fence for re-establishing turn holders (split-brain). A // turn arriving with expectedEpoch must match the live row epoch; a stale // re-dispatched turn is fenced out -> back off, NEVER create(). Number()- // coerced so an int8 drift cannot make the compare always-true. if ( liveness === "warm" && kind === "turn" && input.expectedEpoch !== undefined && Number(row.lease_epoch) !== input.expectedEpoch ) { return { role: "fenced" as const, reason: "superseded" as const, lease: mapLeaseRow(row), }; } // -- warm / warming: attach (A2 / A1). refcount++ ONLY; never touch // liveness. The spawner exclusively owns warming->warm. // TTL: a WARMING attach must keep the warming budget — re-stamping the // plain (90s) TTL while a spawner's create() is still in flight would // collapse expires_at and let the warming-death reaper reset/drain the // lease before instance_id is recorded (F1). A WARM attach uses the plain // TTL as before. await upsertLeaseHolder(tx, row.id, accountId, workspaceId, kind, holderId, subjectId, { subjectId: input.viewerSubjectId ?? null, authorityEpoch: input.viewerAuthorityEpoch ?? null, interactionAgeMs: viewerInteractionAgeMs, }); const attachTtlMs = liveness === "warming" ? warmingLeaseTtlMs : input.leaseTtlMs; const updated = await recomputeAndStampLease(tx, row.id, attachTtlMs, null); return { role: "attached" as const, lease: mapLeaseRow(updated) }; }), ); } function waitForSandboxTransition( ms: number, signal: AbortSignal | undefined, cancellationMessage: string, ): Promise { return new Promise((resolve, reject) => { let settled = false; const timer = setTimeout(finish, ms); function finish(): void { if (settled) return; settled = true; signal?.removeEventListener("abort", cancel); resolve(); } const cancel = (): void => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", cancel); reject(signal?.reason ?? new Error(cancellationMessage)); }; signal?.addEventListener("abort", cancel, { once: true }); // Close the precheck/listener-registration race: an abort dispatched after // the caller entered this function but before the listener was attached is // still observed synchronously here. if (signal?.aborted) cancel(); }); } /** * A request or Browser/ComputerSession admitted to a box is use of it: move * the box's process and Browser/ComputerSession holders' activity forward, so * the compute-bounds idle drain (listNoTurnWarmLeases) sees a terminal being * typed into or a browser being driven as activity, not only when its process * started. Holder rows only, never the lease row, so it takes no lock an * admission waits on. Best-effort. */ async function stampSandboxCommandHolderActivity( db: Database, input: Pick, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb.execute(sql` update sandbox_lease_holders holder set last_interaction_at = now() from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and holder.lease_id = lease.id and holder.kind in ('process', 'interaction') and (holder.last_interaction_at is null or holder.last_interaction_at < now() - interval '30 seconds') `); }, ); } /** What the fleet limits need for one admission of an unpaid organization, * read before the admission transaction. */ type SandboxFleetAdmission = { limits: SandboxFleetLimits; pressure: SandboxFleetPressure; /** Today's unpaid box time; null when not readable yet (definer withheld). */ boxSecondsToday: number | null; /** The box-time read failed: fail closed for this unpaid organization. */ boxSecondsFailed: boolean; /** The organization is younger than `youngOrganizationAgeMs`. */ young: boolean; /** A young organization's metered box seconds since it was created; null * when unbounded or unreadable (fails open, like its other own bounds). */ youngBoxSeconds: number | null; /** A young organization that never started a turn (read only for a holder * other than a turn; false when unread or unreadable, failing open). */ turnless: boolean; }; function sandboxYoungBoxTimeSpent(fleet: SandboxFleetAdmission | null): boolean { return ( fleet !== null && fleet.young && fleet.limits.youngOrganizationBoxSeconds !== undefined && fleet.youngBoxSeconds !== null && fleet.youngBoxSeconds >= fleet.limits.youngOrganizationBoxSeconds ); } /** Whether a young organization is past the box time it gets before its * first turn (`youngTurnlessBoxSeconds`). */ function sandboxYoungTurnlessTimeSpent(fleet: SandboxFleetAdmission | null): boolean { return ( fleet !== null && fleet.young && fleet.turnless && fleet.limits.youngTurnlessBoxSeconds !== undefined && fleet.youngBoxSeconds !== null && fleet.youngBoxSeconds >= fleet.limits.youngTurnlessBoxSeconds ); } /** * Whether any turn was ever created in the organization (any workspace, * shared or personal; the first 50 workspaces). Meant for young * organizations, which have a few workspaces and turns. */ export async function organizationHasAnyTurn(db: Database, accountId: string): Promise { // A turn once created stays created: remember the organizations that have // one, so frequent holders (terminal input, viewer heartbeats) read once. if (ORGANIZATIONS_WITH_A_TURN.has(accountId)) return true; const workspaces = await withRlsContext( db, { accountId, workspaceId: null }, async (scopedDb) => await rawRows<{ id: string }>( scopedDb, sql`select id from workspaces where account_id = ${accountId}::uuid order by created_at limit 50`, ), ); for (const { id: workspaceId } of workspaces) { const [row] = await withRlsContext( db, { accountId, workspaceId }, async (scopedDb) => await rawRows<{ any_turn: boolean }>( scopedDb, sql`select exists (select 1 from session_turns where workspace_id = ${workspaceId}::uuid limit 1) as any_turn`, ), ); if (row?.any_turn) { if (ORGANIZATIONS_WITH_A_TURN.size >= 10_000) ORGANIZATIONS_WITH_A_TURN.clear(); ORGANIZATIONS_WITH_A_TURN.add(accountId); return true; } } return false; } const ORGANIZATIONS_WITH_A_TURN = new Set(); /** Metered box seconds of one organization since `since`. */ export async function organizationBoxSecondsSince( db: Database, accountId: string, since: Date, ): Promise { return await withAccountRls(db, accountId, async (tx) => { const [row] = await rawRows<{ seconds: string | number | null }>( tx, sql`select coalesce(sum(quantity), 0)::bigint as seconds from usage_events where account_id = ${accountId}::uuid and event_type = 'sandbox.warm_seconds' and occurred_at >= ${since.toISOString()}::timestamptz`, ); return Number(row?.seconds ?? 0); }); } /** An unpaid organization (unpaid tier, no paid history) the fleet limits * apply to; paid, Enterprise and host-provisioned organizations never are. */ function sandboxFleetBounded(standing: SandboxComputeStanding | null): boolean { return standing !== null && standing.bounded; } async function readSandboxFleetAdmission( db: Database, input: AcquireLeaseAdmissionInput, standing: SandboxComputeStanding | null, ): Promise { const limits = input.sandboxFleetLimits; if (!limits || input.backend === "selfhosted" || !sandboxFleetBounded(standing)) return null; const report = (error: unknown) => reportSandboxComputeStandingFallback(input.onComputeStandingFallback, error, "fleet"); const pressure = await readSandboxFleetPressure(db, limits, { onReadFailure: report }); let boxSecondsToday: number | null = null; let boxSecondsFailed = false; if (limits.unpaidBoxSecondsPerDay !== undefined) { try { boxSecondsToday = await readSandboxUnpaidFleetBoxSecondsToday(db); } catch (error) { report(error); boxSecondsFailed = true; } } const createdAt = standing?.organizationCreatedAt ?? null; const young = limits.youngOrganizationAgeMs !== undefined && createdAt !== null && Date.now() - createdAt.getTime() < limits.youngOrganizationAgeMs; let youngBoxSeconds: number | null = null; const turnlessBounded = limits.youngTurnlessBoxSeconds !== undefined && input.kind !== "turn"; if ( young && createdAt !== null && (limits.youngOrganizationBoxSeconds !== undefined || turnlessBounded) ) { try { youngBoxSeconds = await organizationBoxSecondsSince(db, input.accountId, createdAt); } catch (error) { reportSandboxComputeStandingFallback(input.onComputeStandingFallback, error, "organization"); } } // Only once its turnless box time is used: a turn ever started in the // organization lifts the bound for good. A failed read fails open. let turnless = false; if ( young && turnlessBounded && youngBoxSeconds !== null && youngBoxSeconds >= limits.youngTurnlessBoxSeconds! ) { try { turnless = !(await organizationHasAnyTurn(db, input.accountId)); } catch (error) { reportSandboxComputeStandingFallback(input.onComputeStandingFallback, error, "organization"); } } return { limits, pressure, boxSecondsToday, boxSecondsFailed, young, youngBoxSeconds, turnless }; } export async function acquireLease( db: Database, request: AcquireLeaseInput, ): Promise { const { sandboxPlanLimits: requestedPlanLimits, ...rest } = request; const input: AcquireLeaseAdmissionInput = requestedPlanLimits === "unbounded_test_fixture" ? rest : { ...rest, sandboxPlanLimits: requestedPlanLimits }; const captureWaitMs = input.captureWaitMs ?? 0; if (!Number.isSafeInteger(captureWaitMs) || captureWaitMs < 0 || captureWaitMs > 60 * 60_000) { throw new Error("Sandbox lease archive capture wait is invalid"); } // A bounded in-process wait must use a monotonic clock. Wall-clock steps from // NTP/VM resume may change timestamp interpretation, but must never stretch // or prematurely consume the caller's resource budget. PostgreSQL projects // an active claim's remaining time on its own authoritative clock; that may // extend a positive caller budget once after a rolling config change. Later // capture retries must not keep renewing a waiter's observational budget. const startedAt = performance.now(); const waitBudget = new SandboxTransitionWaitBudget(captureWaitMs, startedAt); let delayMs = 25; // The organization's tier and the facts outside its lease rows (its box // time today and the acting person's other organizations), read once before // admission. A failed read fails open to the tier read under the lease lock. let standing: SandboxComputeStanding | null = null; if (input.sandboxPlanLimits) { try { standing = await resolveSandboxComputeStanding(db, { accountId: input.accountId, limits: input.sandboxPlanLimits, actingSubjectId: input.actingSubjectId ?? input.viewerSubjectId ?? null, onFallback: input.onComputeStandingFallback, subscriptionPlansEnabled: input.subscriptionPlansEnabled, }); } catch (error) { reportSandboxComputeStandingFallback(input.onComputeStandingFallback, error, "organization"); } } const fleet = await readSandboxFleetAdmission(db, input, standing); for (;;) { const result = await acquireLeaseOnce(db, input, standing, fleet); if ( standing !== null && standing.bounded && (input.kind === "direct" || input.kind === "interaction") && (result.role === "attached" || result.role === "rearmed") ) { await stampSandboxCommandHolderActivity(db, input).catch(() => undefined); } const now = performance.now(); if (captureWaitMs > 0 && result.role === "fenced" && result.reason === "capture_in_progress") { waitBudget.observeCapture(result.captureRemainingMs, now); } if ( result.role !== "fenced" || result.reason === "superseded" || result.reason === "rotation_in_progress" || // A slot frees on the scale of minutes; never busy-wait for one here. result.reason === "organization_sandbox_capacity" || now >= waitBudget.deadline ) { return result; } await waitForSandboxTransition( Math.min(delayMs, Math.max(1, waitBudget.deadline - now)), input.waitSignal, "Sandbox lease transition wait cancelled", ); delayMs = Math.min(500, delayMs * 2); } } export type SandboxCheckpointRestoreArtifact = { id: string; providerBackend: string; providerBindingKey: string; providerBinding: Record; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; objectId: string; descriptorRevision: string; }; export type BeginSandboxRematerializationResult = | { status: "started"; lease: LeaseSnapshot; /** Null is the explicit compatibility path for a verified legacy archive * that predates the checkpoint ledger. Newly published native snapshots * always carry this exact provider-ownership receipt. */ checkpointArtifact: SandboxCheckpointRestoreArtifact | null; } | { status: "blocked"; code: | "archive_unavailable" | "archive_unverified" | "archive_generation_mismatch" | "checkpoint_artifact_invalid" | "fresh_workspace_pending" | "attempt_conflict" | "stale_epoch"; lease: LeaseSnapshot | null; }; function validatedLegacyNativeSnapshotAdoption( value: | { archiveBase64: string; descriptor: SandboxNativeSnapshotRevision; } | null | undefined, ): { archiveBase64: string; descriptor: SandboxNativeSnapshotRevision } | null { if (!value) return null; const bytes = decodeCanonicalBase64(value.archiveBase64); if (!bytes) return null; const descriptor = parseArchiveRevision(value.descriptor); const native = decodeNativeSnapshotRef(bytes); if ( descriptor?.version !== 2 || !native || descriptor.archiveBytes !== bytes.length || descriptor.archiveSha256 !== createHash("sha256").update(bytes).digest("hex") || descriptor.provider !== native.provider || descriptor.snapshotId !== native.snapshotId || descriptor.workspacePersistence !== native.workspacePersistence ) { return null; } return { archiveBase64: value.archiveBase64, descriptor }; } /** Reuse the session control quiescence receipt instead of treating every * historical closed attempt without a receipt as an active writer. Caller * holds the workspace inference fence, which also serializes new claims. */ async function hasSandboxGroupAttemptActivityTx( tx: Database, input: { workspaceId: string; sandboxGroupId: string; idleGraceMs: number; writerMode?: "physical" | "containment"; }, ): Promise { const sessions = await tx.execute<{ id: string; active: boolean }>(sql` select session.id, exists(select 1 from session_turn_attempts attempt where attempt.workspace_id = session.workspace_id and attempt.session_id = session.id and (attempt.state in ('claimed','running') or coalesce(attempt.quiesced_at, attempt.closed_at, attempt.updated_at) > now() - (${input.idleGraceMs}::bigint * interval '1 millisecond'))) as active from sessions session where session.workspace_id = ${input.workspaceId} and session.sandbox_group_id = ${input.sandboxGroupId} `); for (const session of sessions) { if ( session.active || (await hasPendingSessionAttemptQuiescenceTx(tx, { workspaceId: input.workspaceId, sessionId: session.id, writerMode: input.writerMode ?? "physical", })) ) return true; } return false; } export class SandboxRecoveryConflictError extends Error { readonly code = "SANDBOX_RECOVERY_CONFLICT"; } /** Retry already owns workspace/session/turn locks. Fence the EFFECTIVE route, * not a degraded managed home behind an explicitly selected Connected Machine. */ export async function sessionEffectiveSandboxRecoveryBlocked( tx: Database, session: typeof schema.sessions.$inferSelect, ): Promise { if (session.activeSandboxId !== null) { const [target] = await tx .select({ kind: schema.sandboxes.kind }) .from(schema.sandboxes) .where( and( eq(schema.sandboxes.workspaceId, session.workspaceId), eq(schema.sandboxes.id, session.activeSandboxId), ), ) .for("share"); if (target?.kind === "selfhosted") return false; } const groupId = session.activeSandboxId ?? session.sandboxGroupId; const [row] = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${session.workspaceId} and sandbox_group_id = ${groupId} for update`); if (!row) return false; if ((row.public_recovery as Record | null)?.status === "accepted") return true; if (row.liveness !== "cold") return false; // A failed turn may be explicitly retried into a system recovery lane: the // latest verified checkpoint, or a new empty workspace when none survived a // definitive loss. Retry itself restores and replays nothing; the next // claimed attempt rechecks the lane and group-wide quiescence first. const lane = await automaticRecoveryLaneTx(tx, row, session); if (lane.kind !== "unavailable") { if (lane.state === "authorized") return false; const blockers = await sandboxGroupRecoveryBlockersTx(tx, { row, sessionId: session.id, attemptId: null, }); if (!blockers.lease && !blockers.current && !blockers.others) return false; } const recovery = recoveryStateFromLeaseRow(row); // Retrying a current archive is non-destructive revalidation, not consent to // lose newer files. An old loader/configuration failure must not strand the // conversation before the next cold election can run today's verifier. if (canRevalidateCurrentWorkspaceArchive(row)) return false; return ( recovery.restore.status === "unrecoverable" || (recovery.restore.status === "degraded" && recovery.restore.retryable !== true) || (recovery.archive.status === "available" && !hasCompleteWorkspaceArchive(row)) ); } type PublicRecoveryScope = { accountId: string; workspaceId: string; sessionId: string; subjectId: string; /** Core reauthorizes every member under the held tenancy/control fence. * Absent callback never grants group-wide data-loss consent. */ canControlMember?: (tx: Database, sessionId: string) => Promise; }; function recoveryTargetForSession( row: LeaseRow, session: Pick, ): SandboxRecoveryTarget { const recovery = recoveryStateFromLeaseRow(row); return { sessionId: session.id, sandboxGroupId: row.sandbox_group_id, leaseId: row.id, routeEpoch: session.activeEpoch, authorityEpoch: session.authorityEpoch, leaseEpoch: Number(row.lease_epoch), workspaceGeneration: Number(row.workspace_generation), archiveGeneration: row.archive_generation === null ? null : Number(row.archive_generation), revision: recovery.archive.current?.revision ?? null, restoreStatus: recovery.restore.status, restoreCompletedAt: recovery.restore.completedAt, }; } async function currentWorkspaceRecoveryProjection( tx: Database, input: PublicRecoveryScope, row: LeaseRow, session: typeof schema.sessions.$inferSelect, operator = false, ): Promise { const recovery = recoveryStateFromLeaseRow(row); const failed = recovery.restore.status === "unrecoverable" || recovery.restore.status === "degraded"; const fresh = freshWorkspaceRecoveryMarker(row.resume_state); const retryMarker = row.resume_state?.opengeniWorkspaceRecoveryRequest as | { operationId?: string } | undefined; if (!failed && fresh?.source !== "explicit" && !retryMarker?.operationId) return null; if (fresh?.source === "explicit" && (fresh.status === "accepted" || !failed)) { return { version: 1, status: fresh.status === "verified" && recovery.workspace.status === "ready" ? "restored" : row.liveness === "warming" ? "restoring" : "consent_accepted", reason: "fresh_workspace_selected", checkpoint: null, operationId: fresh.operationId, }; } if (!failed && retryMarker?.operationId) return { version: 1, status: recovery.workspace.status === "ready" ? "restored" : row.liveness === "warming" ? "restoring" : "consent_accepted", reason: "archive_retry_selected", checkpoint: null, operationId: retryMarker.operationId, }; const target = recoveryTargetForSession(row, session); const blocked = (reason: string): SandboxRecoveryProjection => ({ version: 1, status: "blocked", reason, checkpoint: null, operationId: retryMarker?.operationId ?? null, target, retryAvailable: false, freshWorkspaceAvailable: false, }); if (row.liveness !== "cold" || row.instance_id !== null || Number(row.refcount) !== 0) return blocked("lease_not_quiescent"); if (row.archive_capture_id !== null || row.provider_create_attempt?.instanceId === null) return blocked("execution_unresolved"); if ( (row.public_recovery as Record | null)?.status === "accepted" || automaticCheckpointMarker(row.resume_state)?.status === "accepted" ) return blocked("automatic_recovery_pending"); const members = await sandboxGroupMembersTx(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: row.sandbox_group_id, }); const blockers = await sandboxGroupRecoveryBlockersTx(tx, { row, sessionId: session.id, attemptId: null, }); const [queued] = await withCompleteSandboxGroupScope(tx, () => rawRows<{ present: boolean }>( tx, sql`select exists(select 1 from session_turns turn join sessions member on member.id = turn.session_id where member.workspace_id = ${input.workspaceId} and member.sandbox_group_id = ${row.sandbox_group_id} and turn.status in ('queued','running','recovering','requires_action','waiting_capacity')) as present`, ), ); if (blockers.lease || blockers.current || blockers.others || queued?.present) return blocked("execution_unresolved"); let controlsGroup = operator; if (!controlsGroup && input.canControlMember && members.length > 0) { controlsGroup = true; for (const member of members) { if (!(await input.canControlMember(tx, member.id))) { controlsGroup = false; break; } } } return { version: 1, status: "eligible", reason: controlsGroup ? null : "group_control_required", checkpoint: null, operationId: retryMarker?.operationId ?? null, target, retryAvailable: canRevalidateCurrentWorkspaceArchive(row), freshWorkspaceAvailable: controlsGroup, ...(controlsGroup ? { groupSessionCount: members.length } : {}), }; } /** Count the complete tenant group, not the actor-visible subset. The caller * has already authorized the selected session; this returns no member data. */ async function completeRecoveryGroupCount( tx: Database, input: PublicRecoveryScope, groupId: string, ): Promise { await tx.execute(sql`select set_config('opengeni.subject_id', '', true)`); try { const [row] = await rawRows<{ count: number }>( tx, sql`select count(*)::int as count from (select id from sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${groupId} limit 2) members`, ); return Number(row?.count ?? 0); } finally { if (input.subjectId.trim()) await setSubjectRlsContext(tx, input.subjectId); else await tx.execute(sql`select set_config('opengeni.subject_id', '', true)`); } } /** System attribution for group-member receipts that no member's own attempt * created. Never a human, delegated principal or agent authority. */ const AUTOMATIC_SANDBOX_RECOVERY_SUBJECT = "opengeni:automatic-sandbox-recovery"; const FRESH_WORKSPACE_RECOVERY_ACTION = "sandbox.fresh_workspace_recovery.authorized"; /** Automatic restores of one checkpoint before an operator must decide. Only * a definitive integrity failure of that exact checkpoint abandons it. */ const MAX_AUTOMATIC_CHECKPOINT_ATTEMPTS = 6; /** Wait after the k-th failed automatic restore before the next decision. */ const AUTOMATIC_CHECKPOINT_RETRY_BACKOFF_MS = [ 60_000, 5 * 60_000, 15 * 60_000, 60 * 60_000, 4 * 60 * 60_000, ] as const; /** Failure codes that prove the exact selected checkpoint's own content can * never be restored (its bytes, descriptor or registered artifact are wrong), * and only when the failure was recorded as not retryable. Provider, binding, * capacity, commit, worker, storage-configuration (`archive_storage_unavailable`) * and missing-object (`archive_object_missing`) failures are deliberately * absent: a bad deploy or storage outage must never abandon a checkpoint. */ const DEFINITIVE_CHECKPOINT_FAILURES: ReadonlySet = new Set([ "archive_metadata_missing", "archive_metadata_invalid", "archive_base64_invalid", "archive_hash_mismatch", "checkpoint_artifact_invalid", ]); /** Opengeni validates OPENGENI_MODAL_TIMEOUT_SECONDS to at most 24h, Modal's * own hard cap, and Modal lifetimes are never renewed. */ const MODAL_SANDBOX_MAX_LIFETIME_MS = 24 * 60 * 60_000; /** A recorded deadline is stamped from the create call's start; the provider * object may come up to the warming budget later. */ const PROVIDER_CREATE_DEADLINE_GRACE_MS = 60 * 60_000; /** persistDrainSnapshot refuses a cold late publication after this window. */ const LATE_CAPTURE_PUBLICATION_WINDOW_MS = SANDBOX_LIFECYCLE_TRANSITION_MAX_WAIT_MS; /** Decisions wait slightly longer than publication so host clock skew can * never let a late archive land after a decision. */ const LATE_CAPTURE_DECISION_DELAY_MS = LATE_CAPTURE_PUBLICATION_WINDOW_MS + 5 * 60_000; type AutomaticCheckpointMarker = { operationId: string; sessionId: string; status: string; attempt: number; }; function automaticCheckpointMarker( resumeState: Record | null | undefined, ): AutomaticCheckpointMarker | null { const value = resumeState?.opengeniAutomaticCheckpointRecovery; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const marker = value as Record; return { operationId: typeof marker.operationId === "string" ? marker.operationId : "", sessionId: typeof marker.sessionId === "string" ? marker.sessionId : "", status: typeof marker.status === "string" ? marker.status : "", attempt: typeof marker.attempt === "number" && Number.isSafeInteger(marker.attempt) && marker.attempt > 0 ? marker.attempt : 1, }; } /** Clear the RLS actor so a census and its warning receipts cover the complete * tenant group, including sessions private to another human. Callers never * return member identities to an actor who cannot already see them. */ async function withCompleteSandboxGroupScope(tx: Database, fn: () => Promise): Promise { const [context] = await rawRows<{ subject_id: string }>( tx, sql`select coalesce(current_setting('opengeni.subject_id', true), '') as subject_id`, ); const restore = async () => { const subjectId = context?.subject_id ?? ""; if (subjectId.trim()) await setSubjectRlsContext(tx, subjectId); else await tx.execute(sql`select set_config('opengeni.subject_id', '', true)`); }; await tx.execute(sql`select set_config('opengeni.subject_id', '', true)`); let result: T; try { result = await fn(); } catch (error) { await restore().catch(() => undefined); throw error; } await restore(); return result; } type SandboxGroupMember = { id: string; activeEpoch: number; authorityEpoch: number }; async function sandboxGroupMembersTx( tx: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string }, ): Promise { return await withCompleteSandboxGroupScope(tx, async () => { const rows = await rawRows<{ id: string; active_epoch: number | string; authority_epoch: number | string; }>( tx, sql`select id, active_epoch, authority_epoch from sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} order by id`, ); return rows.map((row) => ({ id: row.id, activeEpoch: Number(row.active_epoch), authorityEpoch: Number(row.authority_epoch), })); }); } /** Group-wide quiescence for an automatic system recovery decision. Every * member of the sandbox group counts, including private and finished children: * no lease holder, open workspace admission, active retained process, live * pending tool call, or unclosed/unquiesced attempt may exist anywhere in the * group. A pending call is live while its owning attempt is open or awaits * quiescence, or while its turn can still resume it. A row left behind by a * terminal turn whose attempt settled cannot run again and is not a writer. * `attemptId` is the exact deciding attempt, which is itself still running. */ async function sandboxGroupRecoveryBlockersTx( tx: Database, input: { row: LeaseRow; sessionId: string; attemptId: string | null }, ): Promise<{ lease: boolean; current: boolean; others: boolean }> { const workspaceId = input.row.workspace_id; return await withCompleteSandboxGroupScope(tx, async () => { const [blockers] = await rawRows<{ lease: boolean; current: boolean; others: boolean }>( tx, sql`with members as ( select id from sessions where workspace_id = ${workspaceId} and sandbox_group_id = ${input.row.sandbox_group_id} ), unsettled as ( select attempt.session_id from session_turn_attempts attempt join members on members.id = attempt.session_id where attempt.workspace_id = ${workspaceId} and attempt.id is distinct from ${input.attemptId}::uuid and (attempt.state <> 'closed' or (attempt.quiesced_at is null and exists( select 1 from session_attempt_interruptions interruption where interruption.attempt_id = attempt.id))) union all select pending.session_id from session_pending_tool_calls pending join members on members.id = pending.session_id where pending.workspace_id = ${workspaceId} and (exists(select 1 from session_turn_attempts owner where owner.workspace_id = pending.workspace_id and owner.id = pending.attempt_id and (owner.state <> 'closed' or (owner.quiesced_at is null and exists( select 1 from session_attempt_interruptions interruption where interruption.attempt_id = owner.id)))) or exists(select 1 from session_turns turn where turn.workspace_id = pending.workspace_id and turn.id = pending.turn_id and turn.status not in ('completed', 'failed', 'cancelled', 'superseded', 'withdrawn_for_edit'))) ) select exists(select 1 from sandbox_lease_holders where lease_id = ${input.row.id}) or exists(select 1 from sandbox_workspace_mutation_admissions where lease_id = ${input.row.id} and settled_at is null) or exists(select 1 from sandbox_retained_processes where lease_id = ${input.row.id} and state = 'active') as lease, exists(select 1 from unsettled where session_id = ${input.sessionId}) or (${input.attemptId}::uuid is not null and exists( select 1 from session_attempt_interruptions where workspace_id = ${workspaceId} and attempt_id = ${input.attemptId}::uuid)) as current, exists(select 1 from unsettled where session_id <> ${input.sessionId}) as others`, ); return { lease: Boolean(blockers?.lease), current: Boolean(blockers?.current), others: Boolean(blockers?.others), }; }); } /** The CURRENT checkpoint older than the lost workspace: on Modal a registered * native checkpoint, elsewhere the lease's own verified portable archive (which * has no native artifact). The restore path independently verifies the bytes * against the descriptor, and a native checkpoint's provider binding. */ async function verifiedAutomaticCheckpointSelectionTx( tx: Database, row: LeaseRow, session: typeof schema.sessions.$inferSelect, recovery: SandboxRecoveryState, ): Promise { const descriptor = recovery.archive.current; if ( recovery.archive.status !== "available" || currentWorkspaceArchiveWasAbandoned(row) || !descriptor || row.archive_generation === null || Number(row.archive_generation) >= Number(row.workspace_generation) ) return null; if ((row.resume_backend_id ?? row.backend) !== "modal") { return descriptor.version === 1 && row.current_checkpoint_artifact_id === null ? checkpointSelectionForSession(row, session, descriptor) : null; } if (descriptor.version !== 2 || row.current_checkpoint_artifact_id === null) return null; const [artifact] = await rawRows<{ valid: boolean }>( tx, sql`select exists(select 1 from sandbox_checkpoint_artifacts where id = ${row.current_checkpoint_artifact_id} and account_id = ${session.accountId} and workspace_id = ${session.workspaceId} and sandbox_group_id = ${row.sandbox_group_id} and source_lease_id = ${row.id} and state = 'current' and provider_backend = 'modal' and provenance = 'native_capture' and source_workspace_generation = ${Number(row.archive_generation)} and descriptor_revision = ${descriptor.revision} and (descriptor->>'capturedAt') = ${descriptor.capturedAt}) as valid`, ); if (!artifact?.valid) return null; return checkpointSelectionForSession(row, session, descriptor); } function checkpointSelectionForSession( row: LeaseRow, session: Pick, descriptor: { revision: string; capturedAt: string }, ): SandboxCheckpointSelection | null { const parsed = SandboxCheckpointSelection.safeParse({ version: 1, sessionId: session.id, sandboxGroupId: row.sandbox_group_id, leaseId: row.id, routeEpoch: session.activeEpoch, authorityEpoch: session.authorityEpoch, leaseEpoch: Number(row.lease_epoch), workspaceGeneration: Number(row.workspace_generation), archiveGeneration: row.archive_generation === null ? null : Number(row.archive_generation), artifactId: row.current_checkpoint_artifact_id, revision: descriptor.revision, capturedAt: descriptor.capturedAt, }); return parsed.success ? parsed.data : null; } async function freshWorkspaceAuthorizationTx( tx: Database, row: LeaseRow, ): Promise<{ operationId: string; initiatingSessionId: string; reason: SandboxFreshWorkspaceReason; lostAt: string; } | null> { const marker = pendingFreshWorkspaceRecovery(row.resume_state); // Human consent and the empty-workspace decision are mutually exclusive. if (!marker || row.public_recovery !== null) return null; const [audit] = await tx .select({ metadata: schema.auditEvents.metadata }) .from(schema.auditEvents) .where( and( eq(schema.auditEvents.id, marker.operationId), eq(schema.auditEvents.accountId, row.account_id), eq(schema.auditEvents.workspaceId, row.workspace_id), eq(schema.auditEvents.targetId, row.sandbox_group_id), eq(schema.auditEvents.action, FRESH_WORKSPACE_RECOVERY_ACTION), ), ); const metadata = audit?.metadata as Record | undefined; const reason = SandboxFreshWorkspaceReason.safeParse(metadata?.reason); return metadata?.version === 1 && metadata.freshWorkspace === true && metadata.leaseId === row.id && metadata.sessionId === marker.sessionId && typeof metadata.lostAt === "string" && reason.success ? { operationId: marker.operationId, initiatingSessionId: marker.sessionId, reason: reason.data, lostAt: metadata.lostAt, } : null; } /** The exact pending empty-workspace authorization, for the cold->warming * election. Never inferred from archive absence; always an audited decision. */ async function authorizedFreshWorkspaceRecoveryId( tx: Database, row: LeaseRow, ): Promise { return (await freshWorkspaceAuthorizationTx(tx, row))?.operationId ?? null; } type AutomaticRecoveryLane = | { kind: "checkpoint"; state: "available" | "authorized"; selection: SandboxCheckpointSelection; operationId: string | null; initiatingSessionId: string | null; attempt: number; /** Present for a new decision; the lease records it with the decision. */ loss?: ProviderLossRecord; } | { kind: "fresh_workspace"; state: "available" | "authorized"; operationId: string | null; initiatingSessionId: string | null; reason: SandboxFreshWorkspaceReason; lostAt: string; /** Present for a new decision; the lease records it with the decision. */ loss?: ProviderLossRecord; } | { kind: "unavailable"; reason: | "not_applicable" | "not_required" | "loss_unconfirmed" | "capture_unresolved" | "restore_retry_backoff" | "restore_retry_exhausted" | "provider_lifetime_unexpired" | "provider_death_unproven" | "authorization_pending" | "authorization_invalid"; /** For a timed wait: the earliest time a new decision (Retry or a new * message) can proceed. Nothing re-decides by itself before then. */ availableAt?: string; }; function isoTimestamp(...candidates: Array): string { for (const candidate of candidates) { const parsed = typeof candidate === "string" ? Date.parse(candidate) : Number.NaN; if (Number.isFinite(parsed)) return new Date(parsed).toISOString(); } return new Date().toISOString(); } /** Backends whose lost boxes the system may recover by itself. Connected * Machines and backend-less sessions are never system recovered. */ function automaticRecoveryBackend( session: Pick, row: Pick, ): boolean { const backend = row.resume_backend_id ?? row.backend; return ( session.sandboxBackend === backend && row.backend === backend && backend !== "none" && backend !== "selfhosted" ); } /** When the lost object is proven gone, as a database-clock epoch, or null * when nothing proves it. Modal: past its hard lifetime, which no Modal * sandbox outlives in any workspace. Compute: the control plane, which is * authoritative for its own sandboxes, is the only source of a compute * NotFound. Others: the backend-specific proof the loss recorded. */ function providerDeathProvenAtMs(row: LeaseRow, loss: ProviderLossRecord): number | null { const backend = row.resume_backend_id ?? row.backend; if (backend === "modal") { return loss.providerDeadlineAt ? Date.parse(loss.providerDeadlineAt) + PROVIDER_CREATE_DEADLINE_GRACE_MS : Date.parse(loss.observedAt) + MODAL_SANDBOX_MAX_LIFETIME_MS; } if (backend === "compute") return Date.parse(loss.observedAt); return loss.deathProof ? Date.parse(loss.deathProof.provenAt) : null; } /** Structural system continuity for a definitively lost managed box. Prefer * the latest verified checkpoint; otherwise, only with proof the lost object is * gone (providerDeathProvenAtMs), continue on a new EMPTY workspace. Never for * an ambiguous provider state, an unresolved create, a live explicit * authorization, or an unsettled late capture. Group * quiescence is checked separately, at the exact deciding attempt. Rows * written by older confirmDrainCold/lost-instance code qualify as-is: the * decision reads current lease truth, not a new loss-time receipt. */ async function automaticRecoveryLaneTx( tx: Database, row: LeaseRow, session: typeof schema.sessions.$inferSelect, ): Promise { if ( session.sandboxGroupId !== row.sandbox_group_id || (session.activeSandboxId !== null && session.activeSandboxId !== row.sandbox_group_id) || row.public_recovery !== null || (row.liveness !== "cold" && row.liveness !== "warming") ) return { kind: "unavailable", reason: "not_applicable" }; const recovery = recoveryStateFromLeaseRow(row); if (recovery.continuity) return { kind: "unavailable", reason: "not_applicable" }; // An already durable decision is reused, never re-evaluated or duplicated, // including while an elected spawner rematerializes it. const fresh = await freshWorkspaceAuthorizationTx(tx, row); if (fresh) return { kind: "fresh_workspace", state: "authorized", operationId: fresh.operationId, initiatingSessionId: fresh.initiatingSessionId, reason: fresh.reason, lostAt: fresh.lostAt, }; if (pendingFreshWorkspaceRecovery(row.resume_state)) return { kind: "unavailable", reason: "authorization_invalid" }; if (!automaticRecoveryBackend(session, row)) return { kind: "unavailable", reason: "not_applicable" }; const automatic = automaticCheckpointMarker(row.resume_state); if (automatic?.status === "accepted") { const generation = await authorizedHistoricalArchiveGeneration(tx, row); const selection = recovery.archive.current && generation !== null ? checkpointSelectionForSession(row, session, recovery.archive.current) : null; return selection && generation === selection.archiveGeneration ? { kind: "checkpoint", state: "authorized", selection, operationId: automatic.operationId, initiatingSessionId: automatic.sessionId || null, attempt: automatic.attempt, } : { kind: "unavailable", reason: "authorization_invalid" }; } // A new decision needs a settled, box-less lease. if ( row.liveness !== "cold" || row.instance_id !== null || Number(row.refcount) !== 0 || row.archive_capture_id !== null || // An unresolved provider create may still own a live box. (row.provider_create_attempt != null && row.provider_create_attempt.instanceId === null) ) return { kind: "unavailable", reason: "not_applicable" }; // A complete archive (or one at the workspace generation) belongs to the // ordinary restore path, whose failures stop for an operator. Never select // a historical checkpoint over it, and never discard it for an empty box. const archiveGeneration = row.archive_generation === null ? null : Number(row.archive_generation); if ( hasCompleteWorkspaceArchive(row) || (archiveGeneration !== null && archiveGeneration >= Number(row.workspace_generation)) ) return { kind: "unavailable", reason: "not_required" }; const automaticFailed = automatic?.status === "failed"; const blocked = (recovery.restore.status === "degraded" && recovery.restore.retryable !== true) || recovery.restore.status === "unrecoverable"; // The spawner restores only a complete archive or an explicitly authorized // one. An incomplete archive is a dead end whatever its restore label says // (a reset `pending`, a retryable failure, or a failed system restore). const deadEnd = blocked || (recovery.archive.status !== "none" && (recovery.restore.status === "degraded" || recovery.restore.status === "pending")); if (!deadEnd) return { kind: "unavailable", reason: "not_required" }; const loss = await providerLossEvidenceTx(tx, row, recovery); if (!loss) return { kind: "unavailable", reason: "loss_unconfirmed" }; if ((await authorizedHistoricalArchiveGeneration(tx, row)) !== null) return { kind: "unavailable", reason: "authorization_pending" }; // A drain capture that was in flight when the provider vanished may still // publish the exact lost generation until its durable publication deadline // (enforced by persistDrainSnapshot). Neither lane may pre-empt it. // Every deadline is compared with the database clock, the same clock // persistDrainSnapshot uses for its publication window, never a host clock. const late = recovery.lateArchiveCapture; const now = (await transactionNow(tx)).getTime(); const lateDecisionAt = late ? Date.parse(late.recordedAt) + LATE_CAPTURE_DECISION_DELAY_MS : 0; if (late && now < lateDecisionAt) return { kind: "unavailable", reason: "capture_unresolved", availableAt: new Date(lateDecisionAt).toISOString(), }; // Only a definitive integrity failure of the exact checkpoint abandons it. // Retryable or ambiguous failures (provider capacity, worker death, a // rejected commit, a changed provider binding) keep the checkpoint lane. const definitiveCheckpointFailure = (recovery.restore.status === "degraded" || recovery.restore.status === "unrecoverable") && recovery.restore.retryable !== true && DEFINITIVE_CHECKPOINT_FAILURES.has(recovery.restore.failureCode ?? ""); const selection = definitiveCheckpointFailure ? null : await verifiedAutomaticCheckpointSelectionTx(tx, row, session, recovery); if (selection) { const attempt = automaticFailed ? automatic.attempt + 1 : 1; if (automaticFailed) { // Bounded retries with backoff, then an operator decides. A verified // checkpoint is never discarded because restoring it kept failing. if (attempt > MAX_AUTOMATIC_CHECKPOINT_ATTEMPTS) return { kind: "unavailable", reason: "restore_retry_exhausted" }; // A failure with no recorded time starts no backoff, rather than one // that restarts from the current clock on every evaluation. const failedAt = [recovery.restore.completedAt, recovery.provider.observedAt] .map((value) => (typeof value === "string" ? Date.parse(value) : Number.NaN)) .find(Number.isFinite) ?? 0; const backoffMs = AUTOMATIC_CHECKPOINT_RETRY_BACKOFF_MS[ Math.min(automatic.attempt, AUTOMATIC_CHECKPOINT_RETRY_BACKOFF_MS.length) - 1 ]!; if (now < failedAt + backoffMs) return { kind: "unavailable", reason: "restore_retry_backoff", availableAt: new Date(failedAt + backoffMs).toISOString(), }; } return { kind: "checkpoint", state: "available", selection, operationId: null, initiatingSessionId: null, attempt, loss, }; } // No checkpoint Opengeni can restore automatically. An empty workspace is // irreversible for the running sandbox, so it needs proof that the lost // object, and any workspace only it held, is really gone. A NotFound alone // can come from a misconfigured credential or namespace, or a daemon under // memory pressure, and must never turn a live workspace into an empty one. const lifetimeEndsAt = providerDeathProvenAtMs(row, loss); if (lifetimeEndsAt === null) return { kind: "unavailable", reason: "provider_death_unproven" }; if (now < lifetimeEndsAt) return { kind: "unavailable", reason: "provider_lifetime_unexpired", availableAt: new Date(lifetimeEndsAt).toISOString(), }; const reason: SandboxFreshWorkspaceReason = definitiveCheckpointFailure ? "checkpoint_restore_failed" : recovery.archive.status === "none" ? "archive_unavailable" : recovery.archive.status === "available" ? "checkpoint_unrestorable" : "archive_unverified"; return { kind: "fresh_workspace", state: "available", operationId: null, initiatingSessionId: null, reason, lostAt: isoTimestamp(loss.observedAt), loss, }; } /** The durable proof that this lease lineage's provider object was lost. * Replacement failures and ambiguous provider states are never proof. Rows * committed before this release qualify from their own loss transition's * exact shape or from the committed reaper loss audit. */ async function providerLossEvidenceTx( tx: Database, row: LeaseRow, recovery: SandboxRecoveryState, ): Promise { if (recovery.provider.status !== "missing" && recovery.provider.status !== "not_created") return null; const recorded = providerLossRecord(row.resume_state); if (recorded) return recorded.leaseId === row.id && recorded.workspaceGeneration === Number(row.workspace_generation) ? recorded : null; const legacy = ( source: ProviderLossRecord["source"], observedAt: string, ): ProviderLossRecord => ({ version: 1, source, leaseId: row.id, lostEpoch: Math.max(0, Number(row.lease_epoch) - 1), instanceId: recovery.provider.instanceId, workspaceGeneration: Number(row.workspace_generation), observedAt, providerDeadlineAt: null, }); if (recovery.provider.status === "missing" && recovery.provider.observedAt) { // confirmDrainCold: the reaper's exact missing-before-capture commit. if (recovery.provider.diagnostic === PROVIDER_NOT_FOUND_BEFORE_CAPTURE) return legacy("drain_probe", recovery.provider.observedAt); // markWarmLeaseInstanceLost is the only writer of `missing` that leaves // the restore unsettled; replacement failures always stamp completion. if ( recovery.restore.completedAt === null && recovery.restore.rematerializationId === null && recovery.provider.diagnostic !== REPLACEMENT_FAILED_DIAGNOSTIC ) return legacy("warm_resume", recovery.provider.observedAt); } // A replacement attempt overwrote the provider record: older code wrote // `missing`, current code `replacement_failed`. Only those shapes may fall // back to the committed reaper audit for this exact lease and unchanged // workspace generation; a plain `not_created` (an ordinary drain, operator // restore or capture failure) never resurrects an older loss, nor does a // lineage a verified automatic restore already ended. if ( recovery.provider.status !== "missing" && recovery.provider.diagnostic !== REPLACEMENT_FAILED_DIAGNOSTIC ) return null; if (automaticCheckpointMarker(row.resume_state)?.status === "verified") return null; const [audit] = await tx .select({ occurredAt: schema.auditEvents.occurredAt }) .from(schema.auditEvents) .where( and( eq(schema.auditEvents.accountId, row.account_id), eq(schema.auditEvents.workspaceId, row.workspace_id), eq(schema.auditEvents.targetId, row.sandbox_group_id), eq(schema.auditEvents.action, "sandbox.provider_missing_before_capture"), sql`${schema.auditEvents.metadata}->>'leaseId' = ${row.id}`, sql`(${schema.auditEvents.metadata}->>'workspaceGeneration')::bigint = ${Number(row.workspace_generation)}`, ), ) .orderBy(desc(schema.auditEvents.occurredAt)) .limit(1); return audit ? legacy("drain_probe", audit.occurredAt.toISOString()) : null; } /** Public projection reasons for an automatic lane that is structurally * available but not yet safe to decide. */ async function automaticLaneQuiescenceReason( tx: Database, row: LeaseRow, session: typeof schema.sessions.$inferSelect, ): Promise { if (session.activeTurnId !== null || session.status === "cancelled") return "session_not_quiescent"; const blockers = await sandboxGroupRecoveryBlockersTx(tx, { row, sessionId: session.id, attemptId: null, }); if (blockers.current) return "execution_unresolved"; if (blockers.others) return "shared_sandbox_member_active"; // A holder, open admission or retained process on the lost lease is still // unsettled execution, whichever member owns it. if (blockers.lease) return "execution_unresolved"; return null; } async function projectPublicSandboxRecovery( tx: Database, input: PublicRecoveryScope, purpose: "preview" | "consent" = "preview", ): Promise { let currentWorkspace: SandboxRecoveryProjection | null = null; const workspaceOptions = () => currentWorkspace?.target ? { target: currentWorkspace.target, retryAvailable: currentWorkspace.retryAvailable, freshWorkspaceAvailable: currentWorkspace.freshWorkspaceAvailable, ...(currentWorkspace.groupSessionCount ? { groupSessionCount: currentWorkspace.groupSessionCount } : {}), } : {}; const unavailable = ( reason: string, checkpoint: SandboxRecoverySelection | null = null, availableAt?: string, ): SandboxRecoveryProjection => ({ version: 1, status: "blocked", reason, checkpoint, operationId: null, ...(availableAt ? { availableAt } : {}), ...workspaceOptions(), }); const [session] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.accountId, input.accountId), ), ); if (!session) return unavailable("session_unavailable"); if (session.activeSandboxId !== null && session.activeSandboxId !== session.sandboxGroupId) { const [target] = await tx .select({ kind: schema.sandboxes.kind }) .from(schema.sandboxes) .where( and( eq(schema.sandboxes.workspaceId, input.workspaceId), eq(schema.sandboxes.id, session.activeSandboxId), ), ); return { ...unavailable( target?.kind === "selfhosted" ? "connected_machine_selected" : "managed_modal_home_required", ), status: "unsupported", }; } if (session.sandboxBackend === "none" || session.sandboxBackend === "selfhosted") return { ...unavailable("managed_modal_home_required"), status: "unsupported" }; const [row] = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${session.sandboxGroupId}`); if (!row) return { ...unavailable("historical_checkpoint_not_required"), status: "unsupported" }; currentWorkspace = await currentWorkspaceRecoveryProjection(tx, input, row, session); if ( currentWorkspace && (currentWorkspace.reason === "fresh_workspace_selected" || currentWorkspace.reason === "archive_retry_selected" || canRevalidateCurrentWorkspaceArchive(row)) ) return currentWorkspace; // Explicit historical-checkpoint consent stays Modal-only; system continuity // after a loss serves every automatically recoverable backend. const modalHome = session.sandboxBackend === "modal" && row.backend === "modal"; const homeUnsupported = (): SandboxRecoveryProjection => currentWorkspace ?? { ...unavailable("managed_modal_home_required"), status: "unsupported" }; if (!modalHome && !automaticRecoveryBackend(session, row)) return homeUnsupported(); const publicRecovery = row.public_recovery as Record | null; const acceptedSelection = SandboxRecoverySelection.safeParse(publicRecovery?.selection); if (publicRecovery && acceptedSelection.success && publicRecovery.sessionId === input.sessionId) { const recovery = recoveryStateFromLeaseRow(row); const verified = publicRecovery.status === "verified"; const stale = !verified && (session.authorityEpoch !== acceptedSelection.data.authorityEpoch || session.activeEpoch !== acceptedSelection.data.routeEpoch || Number(row.lease_epoch) !== acceptedSelection.data.leaseEpoch); return { version: 1, status: verified && recovery.workspace.status === "ready" ? "restored" : verified || stale || publicRecovery.status === "failed" ? "blocked" : row.liveness === "warming" ? "restoring" : "consent_accepted", reason: publicRecovery.status === "failed" ? "restore_failed" : stale ? "consent_stale" : verified && recovery.workspace.status !== "ready" ? "restored_checkpoint_no_longer_ready" : null, checkpoint: acceptedSelection.data, operationId: String(publicRecovery.operationId), ...workspaceOptions(), }; } // System continuity first: a definitively lost box is never a dead end when // the complete group is quiescent. Human consent below is the remaining // explicit lane for singleton checkpoints the system may not select itself. if (purpose === "preview") { const lane = await automaticRecoveryLaneTx(tx, row, session); if (lane.kind === "checkpoint" || lane.kind === "fresh_workspace") { const automaticCheckpoint = lane.kind === "checkpoint" ? lane.selection : null; // `checkpoint` keeps its public shape: a native checkpoint only. A // portable one is named by `automaticCheckpoint` alone. const nativeCheckpoint = SandboxRecoverySelection.safeParse(automaticCheckpoint); const checkpoint = nativeCheckpoint.success ? nativeCheckpoint.data : null; const blocked = (blockedReason: string): SandboxRecoveryProjection => ({ ...unavailable(blockedReason, checkpoint), ...(automaticCheckpoint ? { automaticCheckpoint } : {}), }); const reason = lane.state === "authorized" ? null : await automaticLaneQuiescenceReason(tx, row, session); if (reason) return blocked(reason); // Retry reopens the latest failed turn, and never with a tool call whose // outcome it cannot prove. A new message still recovers the sandbox. const [retryTarget] = await rawRows<{ unresolved: boolean }>( tx, sql`select exists(select 1 from session_pending_tool_calls pending where pending.workspace_id = ${input.workspaceId} and pending.session_id = ${session.id} and pending.turn_id = (select turn.id from session_turns turn where turn.workspace_id = ${input.workspaceId} and turn.session_id = ${session.id} order by turn.position desc, turn.created_at desc limit 1)) as unresolved`, ); if (retryTarget?.unresolved) return blocked("retry_tool_outcome_unresolved"); return { version: 1, status: "eligible", reason: null, checkpoint, ...(automaticCheckpoint ? { automaticCheckpoint } : {}), operationId: null, automaticAvailable: true, automaticLane: lane.kind, }; } // A timed wait (Retry or a new message can re-decide at `availableAt`; // nothing proceeds by itself) or an operator hand-off; explain which. if ( lane.reason === "capture_unresolved" || lane.reason === "restore_retry_backoff" || lane.reason === "restore_retry_exhausted" || lane.reason === "provider_lifetime_unexpired" ) return unavailable(lane.reason, null, lane.availableAt); } if (!modalHome) return homeUnsupported(); // A system decision already owns this lease; consent may not compete with it. if ( pendingFreshWorkspaceRecovery(row.resume_state) || automaticCheckpointMarker(row.resume_state)?.status === "accepted" ) return unavailable("automatic_recovery_pending"); if (currentWorkspace && !row.current_checkpoint_artifact_id) return currentWorkspace; if ((await completeRecoveryGroupCount(tx, input, session.sandboxGroupId)) !== 1) return currentWorkspace?.freshWorkspaceAvailable ? currentWorkspace : { ...unavailable("singleton_required"), status: "unsupported" }; const recovery = recoveryStateFromLeaseRow(row); // No authoritative recovery failure: a model/transport failure must keep its // ordinary remedies even before the first checkpoint or lease exists. if ( recovery.restore.status !== "unrecoverable" && recovery.restore.status !== "degraded" && (recovery.archive.status !== "available" || hasCompleteWorkspaceArchive(row)) ) return { ...unavailable("historical_checkpoint_not_required"), status: "unsupported" }; const descriptor = recovery.archive.current; if ( !descriptor || descriptor.version !== 2 || recovery.archive.status !== "available" || !row.current_checkpoint_artifact_id ) return unavailable("registered_current_checkpoint_required"); // Human consent is offered only for a registered native checkpoint, so the // public selection always names its artifact. const parsedSelection = SandboxRecoverySelection.safeParse( checkpointSelectionForSession(row, session, descriptor), ); if (!parsedSelection.success) return unavailable("checkpoint_metadata_invalid"); const selection = parsedSelection.data; if (selection.archiveGeneration >= selection.workspaceGeneration) return unavailable("historical_checkpoint_not_required", selection); if (row.liveness !== "cold" || row.instance_id !== null || Number(row.refcount) !== 0) return unavailable("lease_not_quiescent", selection); if (session.activeTurnId !== null || session.status === "cancelled") return unavailable("session_not_quiescent", selection); const [pending] = await rawRows<{ present: boolean }>( tx, sql`select exists(select 1 from session_turns where workspace_id = ${input.workspaceId} and session_id = ${input.sessionId} and status in ('queued','running','recovering','requires_action','waiting_capacity')) or exists(select 1 from sandbox_lease_holders where lease_id = ${row.id}) or exists(select 1 from sandbox_workspace_mutation_admissions where lease_id = ${row.id} and settled_at is null) or exists(select 1 from sandbox_retained_processes where lease_id = ${row.id} and state = 'active') as present`, ); if ( pending?.present || (await hasSandboxGroupAttemptActivityTx(tx, { workspaceId: input.workspaceId, sandboxGroupId: session.sandboxGroupId, idleGraceMs: 0, })) ) return unavailable("execution_unresolved", selection); if (row.archive_capture_id !== null && row.archive_capture_published_at === null) return unavailable("capture_unresolved", selection); const [artifact] = await rawRows<{ valid: boolean }>( tx, sql`select exists(select 1 from sandbox_checkpoint_artifacts where id = ${selection.artifactId} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${selection.sandboxGroupId} and source_lease_id = ${selection.leaseId} and state = 'current' and provider_backend = 'modal' and descriptor_revision = ${selection.revision} and (descriptor->>'capturedAt') = ${selection.capturedAt} and provenance = 'native_capture' and source_workspace_generation = ${selection.archiveGeneration}) as valid`, ); if (!artifact?.valid) return unavailable("checkpoint_artifact_invalid", selection); const [activation] = await rawRows<{ consent_enabled: boolean }>( tx, sql`select consent_enabled from opengeni_private.sandbox_recovery_rollout where singleton`, ); if (!activation?.consent_enabled) return unavailable("recovery_not_enabled", selection); return { version: 1, status: "eligible", reason: null, checkpoint: selection, operationId: null, ...workspaceOptions(), }; } /** Authorized caller only; provider-free and mutation-free (transaction scope only). */ export async function readPublicSandboxRecovery( db: Database, input: PublicRecoveryScope, ): Promise { return withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, (tx) => projectPublicSandboxRecovery(tx, input), ); } /** Core authenticates the canonical managed human before calling this seam. * Exclusive tenancy precedes the complete membership proof and is shared by * every attach/child writer. No provider operation or inference is dispatched. */ export async function consentPublicSandboxRecovery( db: Database, input: PublicRecoveryScope & { request: SandboxRecoveryRequest }, ): Promise { const budget = workspaceControlLockBudget(workspaceControlRequestLockTimeoutMs()); return withRlsContext( db, input, async (tx) => { const lock = (step: () => Promise) => boundedLockStep(tx, input.workspaceId, budget, step); await lock(() => tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ), ); await lock(() => tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`session-tenancy:${input.workspaceId}`}, 0))`, ), ); await setSubjectRlsContext(tx, input.subjectId); if (!(await subjectHasLiveWorkspaceAuthorityInScope(tx, input))) throw new SandboxRecoveryConflictError("Current human authority is unavailable"); const activity = tx; await lockWorkspaceInferenceControl(activity, input.workspaceId, "update", { budget }); const locks = await lock(() => lockSessionEventWriteRows(activity, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], }), ); const session = locks.sessions[0]; if (!session || session.accountId !== input.accountId) throw new SandboxRecoveryConflictError("Session is unavailable"); if ("action" in input.request) { return applySandboxWorkspaceRecoveryTx(activity, input, session, input.request, false); } const reserved = await reserveSessionCommandReceipt(activity, { accountId: input.accountId, workspaceId: input.workspaceId, targetSessionId: input.sessionId, targetTurnId: null, actor: { type: "human", subjectId: input.subjectId }, action: "sandbox.recovery.consent", operationKey: input.request.operationId, canonicalRequestHash: canonicalSessionCommandHash(input.request), }); if (reserved.replay) return { ...SandboxRecoveryResponse.parse(reserved.receipt.result), outcome: "replayed" as const, }; if (input.request.selection.sessionId !== input.sessionId) throw new SandboxRecoveryConflictError("Consent names a different session"); await lock(() => lockSandboxLeaseAdmission(activity, input.workspaceId, session.sandboxGroupId), ); await lock(() => activity.execute( sql`select id from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${session.sandboxGroupId} for update`, ), ); // Consent stays singleton-only and uses its own eligibility: the // automatic system lanes never widen what a human may accept. const projection = await projectPublicSandboxRecovery(activity, input, "consent"); if ( projection.status !== "eligible" || canonicalSessionCommandHash(projection.checkpoint) !== canonicalSessionCommandHash(input.request.selection) ) throw new SandboxRecoveryConflictError( "The checkpoint or recovery eligibility changed; review a fresh preview", ); const selection = input.request.selection; const authorized = await authorizeHistoricalSandboxCheckpointRecovery(activity, { ...input, sandboxGroupId: selection.sandboxGroupId, expectedEpoch: selection.leaseEpoch, expectedWorkspaceGeneration: selection.workspaceGeneration, expectedArchiveGeneration: selection.archiveGeneration, selectedRevision: selection.revision, operationId: input.request.operationId, acceptHistoricalCheckpoint: true, reason: `Explicit same-session checkpoint consent at ${selection.capturedAt}`, }); if (!authorized.authorized) throw new SandboxRecoveryConflictError("Recovery quiescence changed"); await activity.execute( sql`update sandbox_leases set public_recovery = ${JSON.stringify({ version: 1, status: "accepted", sessionId: input.sessionId, subjectId: input.subjectId, operationId: input.request.operationId, selection, })}::jsonb where id = ${selection.leaseId}`, ); const result: SandboxRecoveryResponse = { outcome: "accepted", operationId: input.request.operationId, recovery: { ...projection, status: "consent_accepted", operationId: input.request.operationId, }, }; await updateSessionCommandReceiptResult(activity, reserved.receipt.id, { result }); return result; }, undefined, "none", ); } type WorkspaceRecoveryRequest = Extract; /** Shared human/operator decision seam. The caller holds organization tenancy, * workspace control and session locks; no provider work happens in this transaction. */ async function applySandboxWorkspaceRecoveryTx( tx: Database, input: PublicRecoveryScope, session: typeof schema.sessions.$inferSelect, request: WorkspaceRecoveryRequest, operator: boolean, ): Promise { const members = await sandboxGroupMembersTx(tx, { ...input, sandboxGroupId: session.sandboxGroupId, }); if (request.action === "continue_fresh" && !operator) { if (!input.canControlMember || members.length === 0) throw new SandboxRecoveryConflictError("Control of the complete sandbox group is required"); for (const member of members) { if (!(await input.canControlMember(tx, member.id))) throw new SandboxRecoveryConflictError("Control of the complete sandbox group is required"); } } await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "none", sessionIds: members.map((member) => member.id), }); const reserved = await reserveSessionCommandReceipt(tx, { accountId: input.accountId, workspaceId: input.workspaceId, targetSessionId: input.sessionId, targetTurnId: null, actor: { type: operator ? "service" : "human", subjectId: input.subjectId }, action: "sandbox.recovery.request", operationKey: request.operationId, canonicalRequestHash: canonicalSessionCommandHash(request), }); if (reserved.replay) return { ...SandboxRecoveryResponse.parse(reserved.receipt.result), outcome: "replayed" }; await lockSandboxLeaseAdmission(tx, input.workspaceId, session.sandboxGroupId); const [row] = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${session.sandboxGroupId} for update`); if ( !row || (session.activeSandboxId !== null && session.activeSandboxId !== session.sandboxGroupId) || canonicalSessionCommandHash(recoveryTargetForSession(row, session)) !== canonicalSessionCommandHash(request.target) ) throw new SandboxRecoveryConflictError("Recovery selection changed; review its current status"); const projection = await currentWorkspaceRecoveryProjection(tx, input, row, session, operator); if ( !projection || (request.action === "retry" ? !projection.retryAvailable : !projection.freshWorkspaceAvailable) ) throw new SandboxRecoveryConflictError( "Recovery is not available until the sandbox group is quiescent and authorized", ); const recovery = recoveryStateFromLeaseRow(row); const now = (await transactionNow(tx)).toISOString(); const fresh = request.action === "continue_fresh"; await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { id: request.operationId, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: fresh ? FRESH_WORKSPACE_RECOVERY_ACTION : "sandbox.archive_recovery.retried", targetType: "sandbox_group", targetId: row.sandbox_group_id, metadata: { version: 1, leaseId: row.id, leaseEpoch: Number(row.lease_epoch), sessionId: session.id, workspaceGeneration: Number(row.workspace_generation), archiveGeneration: row.archive_generation === null ? null : Number(row.archive_generation), archiveRevision: recovery.archive.current?.revision ?? null, previousRecovery: recovery, previousPublicRecovery: row.public_recovery, groupSessionCount: members.length, operator, ...(fresh ? { freshWorkspace: true, reason: "restore_abandoned", lostAt: now } : {}), }, }, "metadata", "metadataCodecVersion", ), ); if (fresh) { await writeAutomaticRecoveryReceiptsTx(tx, { ...input, row, operationId: request.operationId, initiatingSessionId: session.id, currentSessionId: session.id, actor: { type: operator ? "service" : "human", subjectId: input.subjectId }, members, lane: { kind: "fresh_workspace", state: "authorized", operationId: request.operationId, initiatingSessionId: session.id, reason: "restore_abandoned", lostAt: now, }, }); const marker: FreshWorkspaceRecoveryMarker = { version: 1, operationId: request.operationId, sessionId: session.id, status: "accepted", authorizedAt: now, source: "explicit", ...(recovery.archive.current?.revision ? { abandonedRevision: recovery.archive.current.revision } : {}), }; await tx.execute(sql`update sandbox_leases set public_recovery = null, resume_state = (coalesce(resume_state, '{}'::jsonb) #- '{opengeniRecovery,lateArchiveCapture}') || ${JSON.stringify({ [FRESH_WORKSPACE_RECOVERY_KEY]: marker })}::jsonb, updated_at = now() where id = ${row.id}`); await withCompleteSandboxGroupScope(tx, () => appendSessionEventToSandboxGroup(tx, input.workspaceId, row.sandbox_group_id, { type: "sandbox.recovery.selected", payload: { operationId: request.operationId, mode: "fresh_workspace", text: "An empty workspace was selected for this chat and any chats sharing it. Previous files were not restored. The old archive is retained; conversations and changes outside the workspace are unchanged. No commands were replayed.", }, }), ); } else { const pending: SandboxRecoveryState = { ...recovery, restore: { status: "pending", rematerializationId: null, selectedRevision: null, startedAt: null, completedAt: null, }, workspace: { status: "not_ready", verifiedRevision: null, verifiedAt: null }, }; await tx.execute(sql`update sandbox_leases set resume_state = ${JSON.stringify({ ...resumeStateWithRecovery(row.resume_state, pending), opengeniWorkspaceRecoveryRequest: { operationId: request.operationId, sessionId: session.id, }, })}::jsonb, updated_at = now() where id = ${row.id}`); } const result: SandboxRecoveryResponse = { outcome: "accepted", operationId: request.operationId, recovery: { version: 1, status: "consent_accepted", reason: fresh ? "fresh_workspace_selected" : "archive_retry_selected", checkpoint: null, operationId: request.operationId, }, }; await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result }); return result; } /** Operator-controlled database access is the authority boundary. Shares the * exact human recovery transaction and never edits archive bytes/generations. */ export async function readSandboxWorkspaceRecoveryAsOperator( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string }, ): Promise { return withRlsContext(db, input, async (tx) => { const [session] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); if (!session) return null; const [row] = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${session.sandboxGroupId}`); return row ? currentWorkspaceRecoveryProjection(tx, input, row, session, true) : null; }); } export async function recoverSandboxWorkspaceAsOperator( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; request: WorkspaceRecoveryRequest; }, ): Promise { if (!input.subjectId.trim()) throw new SandboxRecoveryConflictError("An identified operator is required"); return withRlsContext( db, input, async (tx) => { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-membership:${input.accountId}`}, 0))`, ); await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`session-tenancy:${input.workspaceId}`}, 0))`, ); await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session || session.accountId !== input.accountId) throw new SandboxRecoveryConflictError("Session is unavailable"); return applySandboxWorkspaceRecoveryTx(tx, input, session, input.request, true); }, undefined, "none", ); } export type AutomaticSandboxRecoveryAuthorization = | { status: "not_eligible" } | { status: "authorized" | "already_authorized"; lane: "checkpoint"; selection: SandboxCheckpointSelection; groupSessionCount: number; } | { status: "authorized" | "already_authorized"; lane: "fresh_workspace"; operationId: string; reason: SandboxFreshWorkspaceReason; lostAt: string; groupSessionCount: number; }; type SessionCommandActorInput = Parameters[1]["actor"]; /** One immutable warning receipt per group member for the exact decision. * The deciding attempt is the actor for its own session; every other member * is attributed to the system recovery subject. Members created after the * decision receive the same receipt on their next turn start. */ async function writeAutomaticRecoveryReceiptsTx( tx: Database, input: { accountId: string; workspaceId: string; row: LeaseRow; lane: Exclude; operationId: string; initiatingSessionId: string; currentSessionId: string; actor: SessionCommandActorInput; members: SandboxGroupMember[]; }, ): Promise { const action = input.lane.kind === "checkpoint" ? "sandbox.recovery.automatic" : "sandbox.recovery.fresh_workspace"; await withCompleteSandboxGroupScope(tx, async () => { const existing = await rawRows<{ target_session_id: string }>( tx, sql`select target_session_id from session_command_receipts where workspace_id = ${input.workspaceId} and action = ${action} and result->>'operationId' = ${input.operationId}`, ); const covered = new Set(existing.map((receipt) => receipt.target_session_id)); const shared = input.members.length > 1; for (const member of input.members) { if (covered.has(member.id)) continue; const actor: SessionCommandActorInput = member.id === input.currentSessionId ? input.actor : { type: "service", subjectId: AUTOMATIC_SANDBOX_RECOVERY_SUBJECT }; if (input.lane.kind === "checkpoint") { const checkpoint = SandboxCheckpointSelection.parse({ ...input.lane.selection, sessionId: member.id, routeEpoch: member.activeEpoch, authorityEpoch: member.authorityEpoch, }); await reserveSessionCommandReceipt(tx, { accountId: input.accountId, workspaceId: input.workspaceId, targetSessionId: member.id, targetTurnId: null, actor, action, operationKey: input.operationId, canonicalRequestHash: canonicalSessionCommandHash(checkpoint), initialResult: { operationId: input.operationId, checkpoint, ...(shared ? { scope: "shared", initiatingSessionId: input.initiatingSessionId } : {}), }, }); continue; } const freshWorkspace = SandboxFreshWorkspaceRecovery.parse({ version: 1, sessionId: member.id, sandboxGroupId: input.row.sandbox_group_id, leaseId: input.row.id, leaseEpoch: Number(input.row.lease_epoch), workspaceGeneration: Number(input.row.workspace_generation), archiveGeneration: input.row.archive_generation === null ? null : Number(input.row.archive_generation), lostAt: input.lane.lostAt, reason: input.lane.reason, }); await reserveSessionCommandReceipt(tx, { accountId: input.accountId, workspaceId: input.workspaceId, targetSessionId: member.id, targetTurnId: null, actor, action, operationKey: input.operationId, canonicalRequestHash: canonicalSessionCommandHash(freshWorkspace), initialResult: { operationId: input.operationId, freshWorkspace, initiatingSessionId: input.initiatingSessionId, }, }); } }); } /** Turn-start-only continuity after definitive managed-provider loss. This is * system policy, never a fabricated human consent or permission to replay an * operation. It selects the latest verified checkpoint when the restore path * can use it, otherwise a new EMPTY workspace, for the complete sandbox group * at once. No box is created here; rematerialization rechecks the exact * decision before publishing a usable sandbox. */ export async function authorizeAutomaticSandboxCheckpointRecovery( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; }, ): Promise { return withRlsContext(db, input, async (tx) => { // Healthy turns, including the ordinary idle-drained resume of a complete // archive (`not_created`/`pending`), must not acquire a workspace-wide // inference or session write lock just to discover that no system recovery // is needed. Only an incomplete archive with a loss-shaped provider record // can ever be decided (see automaticRecoveryLaneTx/providerLossEvidenceTx). const [candidate] = await rawRows<{ present: boolean }>( tx, sql`select exists(select 1 from sessions session join sandbox_leases lease on lease.workspace_id = session.workspace_id and lease.sandbox_group_id = session.sandbox_group_id where session.account_id = ${input.accountId} and session.workspace_id = ${input.workspaceId} and session.id = ${input.sessionId} and ((lease.liveness = 'cold' and (lease.archive_generation is null or lease.archive_generation < lease.workspace_generation) and (lease.resume_state #>> '{opengeniRecovery,provider,status}' = 'missing' or lease.resume_state ? ${PROVIDER_LOSS_KEY} or lease.resume_state #>> '{opengeniRecovery,provider,diagnostic}' = ${REPLACEMENT_FAILED_DIAGNOSTIC}) and lease.resume_state #>> '{opengeniRecovery,provider,status}' in ('missing', 'not_created') and lease.resume_state #>> '{opengeniRecovery,restore,status}' in ('degraded', 'unrecoverable', 'pending')) -- A pending decision still delivers receipts to members that -- joined after it, including while its box is being created. or (lease.liveness in ('cold', 'warming') and ( lease.resume_state #>> '{opengeniAutomaticCheckpointRecovery,status}' = 'accepted' or lease.resume_state #>> '{opengeniFreshWorkspaceRecovery,status}' = 'accepted')))) as present`, ); if (!candidate?.present) return { status: "not_eligible" }; await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const [session] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("update"); if (!session) return { status: "not_eligible" }; const [attempt] = await tx .select() .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.accountId, input.accountId), eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ); if ( !attempt || !["claimed", "running"].includes(attempt.state) || attempt.quiescedAt !== null || session.activeTurnId !== attempt.turnId || session.authorityEpoch !== attempt.authorityEpoch || session.visibility !== attempt.authorityVisibility || session.ownerOrganizationMembershipId !== attempt.authorityOwnerOrganizationMembershipId ) return { status: "not_eligible" }; await lockSandboxLeaseAdmission(tx, input.workspaceId, session.sandboxGroupId); const [row] = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${session.sandboxGroupId} for update`); if (!row) return { status: "not_eligible" }; const lane = await automaticRecoveryLaneTx(tx, row, session); if (lane.kind === "unavailable") return { status: "not_eligible" }; const members = await sandboxGroupMembersTx(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: row.sandbox_group_id, }); if (!members.some((member) => member.id === session.id)) return { status: "not_eligible" }; const actor: SessionCommandActorInput = { type: "agent_attempt", attemptId: input.attemptId, sessionId: input.sessionId, turnId: attempt.turnId, executionGeneration: attempt.executionGeneration, }; const result = ( status: "authorized" | "already_authorized", operationId: string, ): AutomaticSandboxRecoveryAuthorization => lane.kind === "checkpoint" ? { status, lane: "checkpoint", selection: lane.selection, groupSessionCount: members.length, } : { status, lane: "fresh_workspace", operationId, reason: lane.reason, lostAt: lane.lostAt, groupSessionCount: members.length, }; if (lane.state === "authorized") { // The durable decision is reused, not re-evaluated against quiescence. await writeAutomaticRecoveryReceiptsTx(tx, { accountId: input.accountId, workspaceId: input.workspaceId, row, lane, operationId: lane.operationId!, initiatingSessionId: lane.initiatingSessionId ?? input.sessionId, currentSessionId: input.sessionId, actor, members, }); return result("already_authorized", lane.operationId!); } const blockers = await sandboxGroupRecoveryBlockersTx(tx, { row, sessionId: input.sessionId, attemptId: input.attemptId, }); if (blockers.lease || blockers.current || blockers.others) return { status: "not_eligible" }; const operationId = crypto.randomUUID(); const recovery = recoveryStateFromLeaseRow(row); const priorAutomatic = automaticCheckpointMarker(row.resume_state); if (lane.kind === "checkpoint") { const selection = lane.selection; await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { id: operationId, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: "opengeni:automatic-checkpoint-recovery", action: "sandbox.automatic_checkpoint_recovery.authorized", targetType: "sandbox_group", targetId: row.sandbox_group_id, metadata: { version: 1, leaseId: row.id, leaseEpoch: selection.leaseEpoch, workspaceGeneration: selection.workspaceGeneration, archiveGeneration: selection.archiveGeneration, selectedRevision: selection.revision, artifactId: selection.artifactId, sessionId: input.sessionId, attemptId: input.attemptId, automaticHistoricalCheckpoint: true, providerMissingBeforeCapture: true, groupSessionCount: members.length, attempt: lane.attempt, ...(lane.loss ? { providerLoss: lane.loss } : {}), ...(priorAutomatic ? { supersededAutomaticRecovery: priorAutomatic } : {}), }, }, "metadata", "metadataCodecVersion", ), ); await tx.execute(sql`select opengeni_private.record_sandbox_recovery_operator_event( ${operationId}::uuid, 'checkpoint_fallback_selected')`); await writeAutomaticRecoveryReceiptsTx(tx, { accountId: input.accountId, workspaceId: input.workspaceId, row, lane, operationId, initiatingSessionId: input.sessionId, currentSessionId: input.sessionId, actor, members, }); // The decision also pins its loss evidence, so a failed restore of the // selected checkpoint cannot erase why this lineage is recoverable. await tx.execute(sql`update sandbox_leases set resume_state = coalesce(resume_state, '{}'::jsonb) || ${JSON.stringify({ opengeniHistoricalArchiveRecoveryId: operationId, opengeniAutomaticCheckpointRecovery: { operationId, sessionId: input.sessionId, status: "accepted", attempt: lane.attempt, // The verified warm commit tells the people in the group which // save their files came back from (see commitWarmingToWarm). capturedAt: selection.capturedAt, }, ...(lane.loss ? { [PROVIDER_LOSS_KEY]: lane.loss } : {}), })}::jsonb, updated_at = now() where id = ${row.id} and liveness = 'cold' and lease_epoch = ${selection.leaseEpoch}`); return result("authorized", operationId); } await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { id: operationId, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: AUTOMATIC_SANDBOX_RECOVERY_SUBJECT, action: FRESH_WORKSPACE_RECOVERY_ACTION, targetType: "sandbox_group", targetId: row.sandbox_group_id, // The lost workspace's full recovery evidence stays on the lease and // its checkpoint artifacts; this receipt names what was abandoned. metadata: { version: 1, freshWorkspace: true, providerMissing: true, leaseId: row.id, leaseEpoch: Number(row.lease_epoch), workspaceGeneration: Number(row.workspace_generation), archiveGeneration: row.archive_generation === null ? null : Number(row.archive_generation), reason: lane.reason, lostAt: lane.lostAt, sessionId: input.sessionId, attemptId: input.attemptId, groupSessionCount: members.length, providerDiagnostic: recovery.provider.diagnostic ?? null, restoreStatus: recovery.restore.status, restoreFailureCode: recovery.restore.failureCode ?? null, archiveStatus: recovery.archive.status, archiveRevision: recovery.archive.current?.revision ?? null, currentCheckpointArtifactId: row.current_checkpoint_artifact_id, previousCheckpointArtifactId: row.previous_checkpoint_artifact_id, ...(lane.loss ? { providerLoss: lane.loss } : {}), ...(recovery.lateArchiveCapture ? { retiredLateArchiveCapture: recovery.lateArchiveCapture } : {}), ...(priorAutomatic ? { supersededAutomaticRecovery: priorAutomatic } : {}), }, }, "metadata", "metadataCodecVersion", ), ); await tx.execute(sql`select opengeni_private.record_sandbox_recovery_operator_event( ${operationId}::uuid, 'fresh_workspace_selected')`); await writeAutomaticRecoveryReceiptsTx(tx, { accountId: input.accountId, workspaceId: input.workspaceId, row, lane, operationId, initiatingSessionId: input.sessionId, currentSessionId: input.sessionId, actor, members, }); const marker: FreshWorkspaceRecoveryMarker = { version: 1, operationId, sessionId: input.sessionId, status: "accepted", authorizedAt: new Date().toISOString(), ...(freshWorkspaceRecoveryMarker(row.resume_state)?.abandonedRevision ? { abandonedRevision: freshWorkspaceRecoveryMarker(row.resume_state)!.abandonedRevision } : {}), }; // The decision retires any late-capture receipt in the same commit, so a // capture of the lost generation can no longer land behind the empty box. await tx.execute(sql`update sandbox_leases set resume_state = (coalesce(resume_state, '{}'::jsonb) #- '{opengeniRecovery,lateArchiveCapture}') || ${JSON.stringify({ [FRESH_WORKSPACE_RECOVERY_KEY]: marker, ...(lane.loss ? { [PROVIDER_LOSS_KEY]: lane.loss } : {}), })}::jsonb, resume_backend_id = coalesce(resume_backend_id, backend), updated_at = now() where id = ${row.id} and liveness = 'cold' and lease_epoch = ${Number(row.lease_epoch)}`); return result("authorized", operationId); }); } /** True once any empty-workspace decision was delivered to this session. A * spawner must then never restore a per-session legacy archive: that session * was told its pre-loss files are gone, whatever the lease marker says now. */ export async function sessionHoldsFreshWorkspaceRecovery( db: Database, workspaceId: string, sessionId: string, ): Promise { return withWorkspaceRls(db, workspaceId, async (tx) => { const [row] = await rawRows<{ present: boolean }>( tx, sql`select exists(select 1 from session_command_receipts where workspace_id = ${workspaceId} and target_session_id = ${sessionId} and action = 'sandbox.recovery.fresh_workspace') as present`, ); return row?.present === true; }); } /** These warnings are outside compactable history and survive ordinary context * reconstruction. Receipts describe decisions, never unverified restore success. */ export async function getSandboxRecoveryDiscontinuity( db: Database, workspaceId: string, sessionId: string, projection: "all" | "legacy_instructions" | "explicit_notice" = "all", ): Promise { return withWorkspaceRls(db, workspaceId, async (tx) => { const rows = await tx .select({ action: schema.sessionCommandReceipts.action, result: schema.sessionCommandReceipts.result, }) .from(schema.sessionCommandReceipts) .where( and( eq(schema.sessionCommandReceipts.workspaceId, workspaceId), eq(schema.sessionCommandReceipts.targetSessionId, sessionId), inArray(schema.sessionCommandReceipts.action, [ "sandbox.recovery.consent", "sandbox.recovery.automatic", "sandbox.recovery.fresh_workspace", ]), projection === "explicit_notice" ? sql`${schema.sessionCommandReceipts.action} = 'sandbox.recovery.fresh_workspace' and ${schema.sessionCommandReceipts.result} #>> '{freshWorkspace,reason}' = 'restore_abandoned'` : projection === "legacy_instructions" ? sql`not (${schema.sessionCommandReceipts.action} = 'sandbox.recovery.fresh_workspace' and coalesce(${schema.sessionCommandReceipts.result} #>> '{freshWorkspace,reason}', '') = 'restore_abandoned')` : undefined, ), ) .orderBy(desc(schema.sessionCommandReceipts.createdAt)) .limit(1); if (!rows[0]) return null; if (rows[0].action === "sandbox.recovery.fresh_workspace") { return freshWorkspaceSandboxRecoveryDiscontinuity( SandboxFreshWorkspaceRecovery.parse(rows[0].result.freshWorkspace), ); } if (rows[0].action === "sandbox.recovery.automatic") { const selection = SandboxCheckpointSelection.parse(rows[0].result.checkpoint); return automaticSandboxRecoveryDiscontinuity( selection, rows[0].result.scope === "shared" ? "shared" : "session", ); } const receipt = SandboxRecoveryResponse.parse(rows[0].result); return receipt.recovery.checkpoint ? sandboxRecoveryDiscontinuity(receipt.recovery.checkpoint) : null; }); } /** Operator-only authorization for an exact historical checkpoint. Direct * database access is the authority boundary; subjectId records attribution. * This never resumes a turn or changes the archive/workspace generations. */ export async function authorizeHistoricalSandboxCheckpointRecovery( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedWorkspaceGeneration: number; expectedArchiveGeneration: number; selectedRevision: string; operationId: string; subjectId: string; reason: string; acceptHistoricalCheckpoint: true; }, ): Promise<{ authorized: boolean }> { if ( input.acceptHistoricalCheckpoint !== true || !input.subjectId.trim() || !input.reason.trim() ) { throw new Error( "Historical checkpoint recovery requires an identified operator and explicit reason", ); } return await withRlsContext(db, input, async (tx) => { await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const rows = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update`); const row = rows[0]; if ( !row || row.backend !== "modal" || row.liveness !== "cold" || row.instance_id !== null || Number(row.lease_epoch) !== input.expectedEpoch || Number(row.refcount) !== 0 || Number(row.workspace_generation) !== input.expectedWorkspaceGeneration || row.archive_generation === null || Number(row.archive_generation) !== input.expectedArchiveGeneration || input.expectedArchiveGeneration >= input.expectedWorkspaceGeneration || recoveryStateFromLeaseRow(row).archive.current?.revision !== input.selectedRevision ) return { authorized: false }; if (await hasSandboxGroupAttemptActivityTx(tx, { ...input, idleGraceMs: 0 })) return { authorized: false }; const blockers = await tx.execute<{ present: boolean }>(sql`select exists(select 1 from sandbox_lease_holders where lease_id = ${row.id}) or exists(select 1 from sandbox_workspace_mutation_admissions where lease_id = ${row.id} and settled_at is null) or exists(select 1 from sandbox_retained_processes where lease_id = ${row.id} and state = 'active') as present`); if (blockers[0]?.present) return { authorized: false }; if ( row.resume_state?.opengeniHistoricalArchiveRecoveryId === input.operationId && (await authorizedHistoricalArchiveGeneration(tx, row)) === input.expectedArchiveGeneration ) return { authorized: true }; const publicRecovery = row.public_recovery as Record | null; // Only a completed public restore may be superseded by this new, exact // operator authorization. Never steal an accepted selection or silently // retry a failed public operation. Keep its full projection in the new // audit receipt; permanent public command receipts remain untouched. if (publicRecovery && publicRecovery.status !== "verified") return { authorized: false }; const metadata = { version: 1, leaseId: row.id, leaseEpoch: input.expectedEpoch, workspaceGeneration: input.expectedWorkspaceGeneration, archiveGeneration: input.expectedArchiveGeneration, selectedRevision: input.selectedRevision, reason: input.reason, acceptedHistoricalCheckpoint: true, ...(publicRecovery ? { supersededPublicRecovery: publicRecovery } : {}), }; await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { id: input.operationId, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "sandbox.historical_checkpoint_recovery.authorized", targetType: "sandbox_group", targetId: input.sandboxGroupId, metadata, }, "metadata", "metadataCodecVersion", ), ); await tx.execute(sql`update sandbox_leases set public_recovery = null, resume_state = jsonb_set(coalesce(resume_state, '{}'::jsonb), '{opengeniHistoricalArchiveRecoveryId}', ${JSON.stringify(input.operationId)}::jsonb), updated_at = now() where id = ${row.id}`); return { authorized: true }; }); } async function authorizedHistoricalArchiveGeneration( db: Database, row: LeaseRow, ): Promise { const publicRecovery = row.public_recovery as Record | null; if (publicRecovery) { const selected = SandboxRecoverySelection.safeParse(publicRecovery.selection); if (publicRecovery.status !== "accepted" || !selected.success) return null; const selection = selected.data; const [session] = await db .select() .from(schema.sessions) .where( and( eq(schema.sessions.accountId, row.account_id), eq(schema.sessions.workspaceId, row.workspace_id), eq(schema.sessions.id, selection.sessionId), ), ); if ( !session || session.sandboxGroupId !== selection.sandboxGroupId || session.sandboxBackend !== "modal" || session.authorityEpoch !== selection.authorityEpoch || session.activeEpoch !== selection.routeEpoch || (session.activeSandboxId !== null && session.activeSandboxId !== selection.sandboxGroupId) || row.current_checkpoint_artifact_id !== selection.artifactId || recoveryStateFromLeaseRow(row).archive.current?.capturedAt !== selection.capturedAt || publicRecovery.operationId !== row.resume_state?.opengeniHistoricalArchiveRecoveryId ) return null; // This is a live-authority oracle for the already authenticated, durable // consent actor, NOT an authentication of a request-supplied subject. if ( typeof publicRecovery.subjectId !== "string" || !(await namedSubjectHasLiveWorkspaceAuthority(db, { accountId: row.account_id, workspaceId: row.workspace_id, subjectId: publicRecovery.subjectId, })) ) return null; } const operationId = row.resume_state?.opengeniHistoricalArchiveRecoveryId; if ( typeof operationId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(operationId) ) return null; const [receipt] = await db .select({ action: schema.auditEvents.action, metadata: schema.auditEvents.metadata, subjectId: schema.auditEvents.subjectId, }) .from(schema.auditEvents) .where( and( eq(schema.auditEvents.id, operationId), eq(schema.auditEvents.accountId, row.account_id), eq(schema.auditEvents.workspaceId, row.workspace_id), eq(schema.auditEvents.targetId, row.sandbox_group_id), inArray(schema.auditEvents.action, [ "sandbox.historical_checkpoint_recovery.authorized", "sandbox.automatic_checkpoint_recovery.authorized", ]), ), ); const metadata = receipt?.metadata; const archiveGeneration = row.archive_generation === null ? null : Number(row.archive_generation); if (receipt?.action === "sandbox.automatic_checkpoint_recovery.authorized") { if (publicRecovery || typeof metadata?.sessionId !== "string") return null; const automatic = row.resume_state?.opengeniAutomaticCheckpointRecovery; if ( !automatic || typeof automatic !== "object" || (automatic as Record).status !== "accepted" || (automatic as Record).operationId !== operationId || (automatic as Record).sessionId !== metadata.sessionId ) return null; const [session] = await db .select({ id: schema.sessions.id, sandboxGroupId: schema.sessions.sandboxGroupId, sandboxBackend: schema.sessions.sandboxBackend, activeSandboxId: schema.sessions.activeSandboxId, }) .from(schema.sessions) .where( and( eq(schema.sessions.accountId, row.account_id), eq(schema.sessions.workspaceId, row.workspace_id), eq(schema.sessions.id, metadata.sessionId), ), ); // Shared groups qualify: every member received its warning receipt when // the decision was made, and the 0526 guard pins membership and routes // until verified warm publication. if (!session) return null; return session.sandboxGroupId === row.sandbox_group_id && automaticRecoveryBackend(session, row) && (session.activeSandboxId === null || session.activeSandboxId === row.sandbox_group_id) && metadata?.version === 1 && metadata.automaticHistoricalCheckpoint === true && metadata.providerMissingBeforeCapture === true && metadata.leaseId === row.id && metadata.leaseEpoch === Number(row.lease_epoch) && metadata.workspaceGeneration === Number(row.workspace_generation) && metadata.archiveGeneration === archiveGeneration && (metadata.artifactId ?? null) === row.current_checkpoint_artifact_id && archiveGeneration !== null && archiveGeneration < Number(row.workspace_generation) && metadata.selectedRevision === recoveryStateFromLeaseRow(row).archive.current?.revision ? archiveGeneration : null; } return (!publicRecovery || receipt?.subjectId === publicRecovery.subjectId) && metadata?.version === 1 && metadata.acceptedHistoricalCheckpoint === true && metadata.leaseId === row.id && metadata.leaseEpoch === Number(row.lease_epoch) && metadata.workspaceGeneration === Number(row.workspace_generation) && metadata.archiveGeneration === archiveGeneration && archiveGeneration !== null && archiveGeneration < Number(row.workspace_generation) && metadata.selectedRevision === recoveryStateFromLeaseRow(row).archive.current?.revision ? archiveGeneration : null; } /** Records the single cold->warming winner's exact restore attempt. The lease * election remains the sole spawner guard; this adds durable selected-revision * and progress truth under the same epoch. */ export async function beginSandboxRematerialization( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; rematerializationId: string; /** Optional durable per-session fallback envelope. When the lease has no * archive yet, its archive fields are imported under this same row lock so * restoration can never consume bytes that were not durably selected by * the lease attempt. Provider/session state is never imported here. */ archiveSource?: Record | null; /** One-time adoption of a native provider receipt written before the v2 * descriptor split. The runtime derives v2 identity from the exact opaque * bytes. A metadata-less receipt is accepted only at generation zero; a v1 * descriptor is accepted only when its byte hash and archive generation are * already current. Tar payloads and generation gaps remain ineligible. */ legacyNativeArchive?: { archiveBase64: string; descriptor: SandboxNativeSnapshotRevision; } | null; }, ): Promise { const legacyNativeArchive = validatedLegacyNativeSnapshotAdoption(input.legacyNativeArchive); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch) { return { status: "blocked" as const, code: "stale_epoch" as const, lease: row ? mapLeaseRow(row) : null, }; } // Every member was already told the workspace is empty. No archive, // including a per-session legacy fallback, may be restored under it. if (pendingFreshWorkspaceRecovery(row.resume_state)) { return { status: "blocked" as const, code: "fresh_workspace_pending" as const, lease: mapLeaseRow(row), }; } let workingResumeState = row.resume_state; let workingRow = row; let current = recoveryStateFromLeaseRow(workingRow); let importedArchiveGeneration = false; if (current.archive.status === "none" && input.archiveSource) { const imported = resumeStateWithPreservedArchives( workingResumeState, input.archiveSource, ); if (imported !== workingResumeState) { workingResumeState = imported; workingRow = { ...workingRow, resume_state: imported }; current = recoveryStateFromLeaseRow(workingRow); // A session fallback is the last verified archive from before the // lease acquired generation-aware ownership. Importing it is the // one-time protocol-v2 handoff: bind it to the currently locked // workspace generation in the same transaction that selects it. // Runtime still verifies the selected receipt/archive according to // its kind before the warming lease may commit warm. if (current.archive.status === "available" && current.archive.current) { workingRow = { ...workingRow, archive_generation: workingRow.workspace_generation, }; importedArchiveGeneration = true; } } } if (legacyNativeArchive) { const sessionState = workingResumeState?.sessionState && typeof workingResumeState.sessionState === "object" ? (workingResumeState.sessionState as Record) : null; const descriptor = legacyNativeArchive.descriptor; const existingDescriptor = parseArchiveRevision(sessionState?.workspaceArchiveMeta); const metadataLessGenerationZero = current.archive.status === "unverified" && Number(workingRow.workspace_generation) === 0 && workingRow.archive_generation === null; const v1DescriptorAlreadyCurrent = existingDescriptor?.version === 1 && existingDescriptor.archiveBytes === descriptor.archiveBytes && existingDescriptor.archiveSha256 === descriptor.archiveSha256 && workingRow.archive_generation !== null && Number(workingRow.archive_generation) === Number(workingRow.workspace_generation); if ( (metadataLessGenerationZero || v1DescriptorAlreadyCurrent) && backendForNativeSnapshotProvider(descriptor.provider) === (workingRow.resume_backend_id ?? workingRow.backend) && sessionState?.workspaceArchive === legacyNativeArchive.archiveBase64 ) { const adoptedSessionState = { ...sessionState, workspaceArchiveMeta: descriptor, }; workingResumeState = { ...(workingResumeState ?? {}), sessionState: adoptedSessionState, }; workingRow = { ...workingRow, resume_state: workingResumeState, archive_generation: workingRow.workspace_generation, }; current = recoveryStateFromLeaseRow(workingRow); importedArchiveGeneration = true; } } const historicalGeneration = await authorizedHistoricalArchiveGeneration(tx, workingRow); const archiveComplete = hasCompleteWorkspaceArchive(workingRow) || historicalGeneration !== null; if ( current.archive.status !== "available" || !current.archive.current || !archiveComplete ) { if (current.archive.status !== "none") { const failedAt = new Date().toISOString(); const failureCode = current.archive.status === "available" && !archiveComplete ? "archive_generation_mismatch" : "archive_unverified"; const degraded: SandboxRecoveryState = { provider: { status: "not_created", instanceId: null, observedAt: failedAt, }, archive: current.archive, restore: { status: "degraded", rematerializationId: null, selectedRevision: null, startedAt: null, completedAt: failedAt, failureCode, retryable: false, }, workspace: { status: "degraded", verifiedRevision: null, verifiedAt: null, }, ...(current.continuity ? { continuity: current.continuity } : {}), }; const degradedResumeState = resumeStateWithRecovery(workingResumeState, degraded); const degradedRows = await tx.execute(sql` update sandbox_leases set resume_state = ${JSON.stringify(degradedResumeState)}::jsonb, resume_backend_id = coalesce(resume_backend_id, backend), updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); workingRow = degradedRows[0] ?? workingRow; } return { status: "blocked" as const, code: current.archive.status === "none" ? ("archive_unavailable" as const) : current.archive.status === "available" && !archiveComplete ? ("archive_generation_mismatch" as const) : ("archive_unverified" as const), lease: mapLeaseRow(workingRow), }; } let checkpointArtifact: SandboxCheckpointRestoreArtifact | null = null; if (workingRow.current_checkpoint_artifact_id !== null) { const artifactRows = await tx.execute<{ id: string; account_id: string; workspace_id: string; sandbox_group_id: string; source_lease_id: string; source_workspace_generation: number | string | null; provenance: "native_capture" | "legacy_provider_adopted"; provider_backend: string; provider_binding_key: string; provider_binding: Record; object_kind: string; object_id: string; archive_base64: string; descriptor: unknown; descriptor_revision: string; state: string; }>(sql` select id, account_id, workspace_id, sandbox_group_id, source_lease_id, source_workspace_generation, provenance, provider_backend, provider_binding_key, provider_binding, object_kind, object_id, archive_base64, descriptor, descriptor_revision, state from sandbox_checkpoint_artifacts where id = ${workingRow.current_checkpoint_artifact_id} for share `); const artifact = artifactRows[0]; const descriptor = parseArchiveRevision(artifact?.descriptor); const providerIdentity = canonicalModalCheckpointProviderBinding( artifact?.provider_binding, ); const sessionState = workingResumeState?.sessionState && typeof workingResumeState.sessionState === "object" ? (workingResumeState.sessionState as Record) : null; const selected = current.archive.current; const expectedObjectKind = selected.version === 2 && selected.provider === "modal_snapshot_filesystem" ? "modal_filesystem_snapshot" : selected.version === 2 && selected.provider === "modal_snapshot_directory" ? "modal_directory_snapshot" : null; const valid = artifact !== undefined && selected.version === 2 && descriptor?.version === 2 && expectedObjectKind !== null && artifact.state === "current" && artifact.account_id === input.accountId && artifact.workspace_id === input.workspaceId && artifact.sandbox_group_id === input.sandboxGroupId && artifact.source_lease_id === workingRow.id && ((artifact.provenance === "native_capture" && artifact.source_workspace_generation !== null && Number(artifact.source_workspace_generation) === (historicalGeneration ?? Number(workingRow.workspace_generation))) || (artifact.provenance === "legacy_provider_adopted" && artifact.source_workspace_generation === null)) && artifact.provider_backend === workingRow.backend && artifact.provider_backend === backendForNativeSnapshotProvider(selected.provider) && providerIdentity !== null && providerIdentity.key === artifact.provider_binding_key && artifact.object_kind === expectedObjectKind && artifact.object_id === selected.snapshotId && artifact.archive_base64 === sessionState?.workspaceArchive && artifact.descriptor_revision === selected.revision && descriptor.revision === selected.revision && descriptor.archiveSha256 === selected.archiveSha256 && descriptor.archiveBytes === selected.archiveBytes && descriptor.provider === selected.provider && descriptor.snapshotId === selected.snapshotId && descriptor.workspacePersistence === selected.workspacePersistence; if (!valid) { const failedAt = new Date().toISOString(); const degraded: SandboxRecoveryState = { provider: { status: "not_created", instanceId: null, observedAt: failedAt, }, archive: current.archive, restore: { status: "degraded", rematerializationId: null, selectedRevision: null, startedAt: null, completedAt: failedAt, failureCode: "checkpoint_artifact_invalid", retryable: false, }, workspace: { status: "degraded", verifiedRevision: null, verifiedAt: null, }, ...(current.continuity ? { continuity: current.continuity } : {}), }; const degradedRows = await tx.execute(sql` update sandbox_leases set resume_state = ${JSON.stringify( resumeStateWithRecovery(workingResumeState, degraded), )}::jsonb, resume_backend_id = coalesce(resume_backend_id, backend), updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); return { status: "blocked" as const, code: "checkpoint_artifact_invalid" as const, lease: mapLeaseRow(degradedRows[0] ?? workingRow), }; } checkpointArtifact = { id: artifact.id, providerBackend: artifact.provider_backend, providerBindingKey: artifact.provider_binding_key, providerBinding: providerIdentity.binding, objectKind: artifact.object_kind as SandboxCheckpointRestoreArtifact["objectKind"], objectId: artifact.object_id, descriptorRevision: artifact.descriptor_revision, }; } if ( (current.restore.status === "restoring" || current.restore.status === "verifying") && current.restore.rematerializationId !== input.rematerializationId ) { return { status: "blocked" as const, code: "attempt_conflict" as const, lease: mapLeaseRow(row), }; } if ( (current.restore.status === "restoring" || current.restore.status === "verifying") && current.restore.rematerializationId === input.rematerializationId ) { return { status: "started" as const, lease: mapLeaseRow(row), checkpointArtifact, }; } const startedAt = new Date().toISOString(); const recovery: SandboxRecoveryState = { provider: { status: "creating", instanceId: null, observedAt: startedAt, }, archive: current.archive, restore: { status: "restoring", rematerializationId: input.rematerializationId, selectedRevision: current.archive.current.revision, startedAt, completedAt: null, }, workspace: { status: "not_ready", verifiedRevision: null, verifiedAt: null, }, ...(current.continuity ? { continuity: current.continuity } : {}), }; const resumeStateJson = JSON.stringify( resumeStateWithRecovery(workingResumeState, recovery), ); const updated = await tx.execute(sql` update sandbox_leases set resume_state = ${resumeStateJson}::jsonb, ${importedArchiveGeneration ? sql`archive_generation = workspace_generation,` : sql``} updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); return updated[0] ? { status: "started" as const, lease: mapLeaseRow(updated[0]), checkpointArtifact, } : { status: "blocked" as const, code: "stale_epoch" as const, lease: null, }; }), ); } export async function markSandboxRestoreVerifying( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; rematerializationId: string; }, ): Promise<{ wrote: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set resume_state = jsonb_set(resume_state, '{opengeniRecovery,restore,status}', '"verifying"'::jsonb), updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} and resume_state #>> '{opengeniRecovery,restore,rematerializationId}' = ${input.rematerializationId} and resume_state #>> '{opengeniRecovery,restore,status}' = 'restoring' returning id `); return { wrote: rows.length > 0 }; }, ); } export async function failSandboxRematerialization( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; rematerializationId: string; failureCode: string; retryable: boolean; discardContinuity?: boolean; /** The continuity restore proved the lost workspace itself is gone (see * ProviderDeathProof `workspace_absent`). Implies discardContinuity. */ providerWorkspaceAbsent?: boolean; }, ): Promise<{ failed: boolean; lease: LeaseSnapshot | null }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || row.provider_create_attempt?.instanceId === null || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch || ( row.resume_state as { opengeniRecovery?: { restore?: { rematerializationId?: unknown }; }; } )?.opengeniRecovery?.restore?.rematerializationId !== input.rematerializationId ) { return { failed: false, lease: row ? mapLeaseRow(row) : null }; } const current = recoveryStateFromLeaseRow(row); const continuity = input.retryable && !input.discardContinuity && !input.providerWorkspaceAbsent ? continuityRecoveryFromLeaseRow(row) : null; const terminalStatus: SandboxRestoreStatus = continuity ? "pending" : input.retryable ? "degraded" : "unrecoverable"; const recovery: SandboxRecoveryState = { // The failed replacement is not evidence about the lost workspace: // loss is recorded only by the loss transitions themselves. provider: { status: "not_created", instanceId: row.instance_id, observedAt: new Date().toISOString(), diagnostic: REPLACEMENT_FAILED_DIAGNOSTIC, }, archive: current.archive, restore: { ...current.restore, status: terminalStatus, completedAt: new Date().toISOString(), ...(continuity ? { rematerializationId: null, selectedRevision: current.archive.current?.revision ?? null, startedAt: null, } : { failureCode: input.failureCode.slice(0, 96), retryable: input.retryable, }), }, workspace: { status: continuity ? "not_ready" : input.retryable ? "degraded" : "unrecoverable", verifiedRevision: null, verifiedAt: null, }, ...(continuity ? { continuity } : {}), }; const resumeStateJson = JSON.stringify( recoveryResumeState( row, recovery, input.providerWorkspaceAbsent ? providerLossRecordWithWorkspaceAbsent(row, new Date().toISOString()) : undefined, ), ); const updated = await tx.execute(sql` update sandbox_leases set liveness = 'cold', instance_id = null, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, resume_state = ${resumeStateJson}::jsonb, provider_created_at = null, provider_deadline_at = null, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); if (updated[0] && row.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, input); } return updated[0] ? { failed: true, lease: mapLeaseRow(updated[0]) } : { failed: false, lease: null }; }), ); } export async function markSandboxProviderReady( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; }, ): Promise<{ wrote: boolean; lease: LeaseSnapshot | null }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || row.liveness !== "warm" || Number(row.lease_epoch) !== input.expectedEpoch || row.instance_id !== input.expectedInstanceId ) { return { wrote: false, lease: row ? mapLeaseRow(row) : null }; } const current = recoveryStateFromLeaseRow(row); const observedAt = new Date().toISOString(); const recovery: SandboxRecoveryState = { ...current, provider: { status: "exists", instanceId: row.instance_id, observedAt, }, restore: current.restore.status === "ready" ? current.restore : { status: "not_required", rematerializationId: null, selectedRevision: null, startedAt: null, completedAt: observedAt, }, workspace: current.restore.status === "ready" ? current.workspace : { status: "ready", verifiedRevision: null, verifiedAt: observedAt, }, }; const resumeStateJson = JSON.stringify(resumeStateWithRecovery(row.resume_state, recovery)); const updated = await tx.execute(sql` update sandbox_leases set resume_state = ${resumeStateJson}::jsonb, updated_at = now() where id = ${row.id} and liveness = 'warm' and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} returning * `); return updated[0] ? { wrote: true, lease: mapLeaseRow(updated[0]) } : { wrote: false, lease: null }; }), ); } // §4.2 — the warming publication lease_epoch++ site. Loss, failed restore, and // drain transitions also advance the epoch under their own exact predicates. // CAS on (warming AND lease_epoch=expected) and fold the group box envelope // (resume_backend_id/resume_state) onto the lease. export async function commitWarmingToWarm( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; // the epoch the spawner observed at cold->warming instanceId: string; dataPlaneUrl?: string | null; // event-driven resolveExposedPort result, any worker resumeBackendId?: string | null; resumeState?: Record | null; /** Required when the warming lease carries a selected durable archive. * The warm transition is rejected unless this exact attempt is in the * verifying state for this exact revision. */ rematerialization?: { id: string; verifiedRevision: string; }; /** Exact durable same-workspace receipt returned by the elected provider * continuity recovery. Mutually exclusive with archive hydration. */ continuityRecovery?: SandboxProviderContinuityRecovery; /** The exact audited empty-workspace decision this archive-free box * fulfils. Required while such a decision is pending; exclusive with * archive hydration and provider continuity. */ freshWorkspace?: { operationId: string }; leaseTtlMs: number; }, ): Promise<{ committed: boolean; lease: LeaseSnapshot | null; reason?: | "stale_epoch" | "rematerialization_required" | "rematerialization_mismatch" | "recovery_mode_conflict" | "continuity_mismatch" | "archive_revision_mismatch" | "archive_generation_mismatch" | "fresh_workspace_required" | "fresh_workspace_mismatch"; }> { const result = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch) { return { committed: false, lease: row ? mapLeaseRow(row) : null, reason: "stale_epoch" as const, }; } const current = recoveryStateFromLeaseRow(row); const rematerialization = input.rematerialization; const continuityRecovery = input.continuityRecovery; const freshWorkspace = input.freshWorkspace; if ( (rematerialization && continuityRecovery) || (freshWorkspace && (rematerialization || continuityRecovery)) ) { return { committed: false, lease: mapLeaseRow(row), reason: "recovery_mode_conflict" as const, }; } const pendingFresh = pendingFreshWorkspaceRecovery(row.resume_state); if (pendingFresh && !freshWorkspace) { // Every group member was already told this workspace is empty. return { committed: false, lease: mapLeaseRow(row), reason: "fresh_workspace_required" as const, }; } if ( freshWorkspace && (!pendingFresh || pendingFresh.operationId !== freshWorkspace.operationId || (await authorizedFreshWorkspaceRecoveryId(tx, row)) !== freshWorkspace.operationId || current.restore.status === "restoring" || current.restore.status === "verifying") ) { return { committed: false, lease: mapLeaseRow(row), reason: "fresh_workspace_mismatch" as const, }; } if (continuityRecovery) { const adoptedState = dockerContinuityRecoveryFromLeaseRow(row, input.instanceId); if ( !continuityRecoveryEquals(current.continuity, continuityRecovery) || !continuityRecoveryEquals(adoptedState, continuityRecovery, false) ) { return { committed: false, lease: mapLeaseRow(row), reason: "continuity_mismatch" as const, }; } } if (current.continuity && !continuityRecovery && !rematerialization && !freshWorkspace) { return { committed: false, lease: mapLeaseRow(row), reason: "continuity_mismatch" as const, }; } if ( current.archive.status === "available" && !rematerialization && !continuityRecovery && !freshWorkspace ) { return { committed: false, lease: mapLeaseRow(row), reason: "rematerialization_required" as const, }; } if ( rematerialization && (current.restore.status !== "verifying" || current.restore.rematerializationId !== rematerialization.id || current.restore.selectedRevision !== rematerialization.verifiedRevision) ) { return { committed: false, lease: mapLeaseRow(row), reason: "rematerialization_mismatch" as const, }; } if ( rematerialization && current.archive.current?.revision !== rematerialization.verifiedRevision ) { return { committed: false, lease: mapLeaseRow(row), reason: "archive_revision_mismatch" as const, }; } if ( rematerialization && !hasCompleteWorkspaceArchive(row) && (await authorizedHistoricalArchiveGeneration(tx, row)) === null ) { return { committed: false, lease: mapLeaseRow(row), reason: "archive_generation_mismatch" as const, }; } // Warm-time billing and stop cutoffs share the database clock, even // when the worker host's wall clock differs from PostgreSQL's. const [warmClock] = await tx.execute<{ completed_at: Date | string }>(sql` select clock_timestamp() as completed_at `); if (!warmClock) throw new Error("sandbox warm-transition clock unavailable"); const completedAt = new Date(warmClock.completed_at).toISOString(); const recovery: SandboxRecoveryState = rematerialization ? { provider: { status: "exists", instanceId: input.instanceId, observedAt: completedAt, }, archive: current.archive, restore: { status: "ready", rematerializationId: rematerialization.id, selectedRevision: rematerialization.verifiedRevision, startedAt: current.restore.startedAt, completedAt, }, workspace: { status: "ready", verifiedRevision: rematerialization.verifiedRevision, verifiedAt: completedAt, }, } : { provider: { status: "exists", instanceId: input.instanceId, observedAt: completedAt, }, archive: archiveProjectionFromResumeState(input.resumeState ?? null), restore: { status: "not_required", rematerializationId: null, selectedRevision: null, startedAt: null, completedAt, }, workspace: { status: "ready", verifiedRevision: null, verifiedAt: completedAt, }, }; const withArchives = resumeStateWithPreservedArchives( input.resumeState ?? null, row.resume_state, ); const automatic = row.resume_state?.opengeniAutomaticCheckpointRecovery; const automaticVerified = rematerialization !== null && row.public_recovery === null && automatic !== null && typeof automatic === "object" && (automatic as Record).status === "accepted" && (automatic as Record).operationId === row.resume_state?.opengeniHistoricalArchiveRecoveryId; // The model learned of the older snapshot from its receipt when the // restore was authorized. The people in the group are told once, after // this commit, when that restore is verified, so a restore that fails, // retries or ends on an empty workspace never claims their files came // back. Only an archive restore qualifies, never an empty workspace or // same-box continuity. A box the drain stopped after failed saves // already told them, when it stopped, which files were not saved. const loss = row.resume_state?.[PROVIDER_LOSS_KEY] as ProviderLossRecord | undefined; const restoredFrom = automaticVerified && rematerialization !== undefined && !freshWorkspace && !continuityRecovery ? (automatic as Record).capturedAt : undefined; const restoredNotice = typeof restoredFrom === "string" && !stopNoticeNamedSave(loss, restoredFrom) ? { operationId: (automatic as Record).operationId, mode: "checkpoint" as const, capturedAt: restoredFrom, } : null; const completedResumeState = resumeStateWithRecovery( { ...(withArchives ?? {}), ...(row.resume_state?.opengeniWarmBilling ? { opengeniWarmBilling: row.resume_state.opengeniWarmBilling } : {}), ...(automaticVerified ? { opengeniAutomaticCheckpointRecovery: { ...(automatic as Record), status: "verified", // Durable until the notice is written: a failed write is // retried (`deliverPendingSandboxRestoreNotice`) and the // write clears it, so the notice lands exactly once. ...(restoredNotice ? { noticePending: true } : {}), }, } : {}), }, recovery, ); if (automaticVerified) delete completedResumeState.opengeniHistoricalArchiveRecoveryId; // A verified warm box ends the lost lineage; its loss evidence cannot // describe any later loss of this new provider object. delete completedResumeState[PROVIDER_LOSS_KEY]; if (freshWorkspace && pendingFresh) { // The lost workspace's archive fields and checkpoint references stay // for forensics until ordinary capture rotation supersedes them. Any // failed or stale earlier restore decision is retired so a later loss // of this new workspace can be recovered again. completedResumeState[FRESH_WORKSPACE_RECOVERY_KEY] = { ...pendingFresh, status: "verified", verifiedAt: completedAt, } satisfies FreshWorkspaceRecoveryMarker; delete completedResumeState.opengeniHistoricalArchiveRecoveryId; if (automaticCheckpointMarker(completedResumeState)?.status !== "accepted") delete completedResumeState.opengeniAutomaticCheckpointRecovery; } const resumeStateJson = JSON.stringify(completedResumeState); const updated = await tx.execute(sql` update sandbox_leases set liveness = 'warm', public_recovery = case when public_recovery->>'status' = 'accepted' then jsonb_set(jsonb_set(public_recovery, '{status}', '"verified"'::jsonb), '{verifiedAt}', ${JSON.stringify(completedAt)}::jsonb) else public_recovery end, instance_id = ${input.instanceId}, data_plane_url = ${input.dataPlaneUrl ?? null}, terminal_data_plane_url = null, controller_data_plane_url = null, resume_backend_id = ${input.resumeBackendId ?? null}, resume_state = ${resumeStateJson}::jsonb, -- Publishing an explicitly empty filesystem is a new generation, -- even before its first command. Its retained old archive must not -- become a current recovery source if this replacement is lost. workspace_generation = workspace_generation + ${freshWorkspace && pendingFresh?.source === "explicit" ? 1 : 0}, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, expires_at = now() + (${String(input.leaseTtlMs)} || ' milliseconds')::interval, updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); if (!updated[0]) { return { committed: false, lease: null, reason: "stale_epoch" as const, }; } return { committed: true, lease: mapLeaseRow(updated[0]), restoredNotice }; }), ); const { restoredNotice, ...outcome } = result as typeof result & { restoredNotice?: Record | null; }; if (outcome.committed && restoredNotice) { // Its own transaction, after the commit: appending locks every member's // session row, and this commit already holds the lease row, which // recovery authorization takes after its own session row. The verified // restore must never be undone for a notice: a failed write leaves the // durable pending flag, and the next turn delivers it. try { await deliverPendingSandboxRestoreNotice(db, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, }); } catch (error) { console.warn("sandbox restore: older-save notice write failed; retried on the next turn", { sandboxGroupId: input.sandboxGroupId, operationId: restoredNotice.operationId, error: error instanceof Error ? error.message : String(error), }); } } return outcome; } /** * Writes the "files were restored from an older save" notice of a verified * automatic restore to every chat sharing the box, exactly once. The warm * commit records it as pending on the lease's recovery marker; this appends * it and clears that flag in one transaction (sessions locked before the * lease, the canonical order), so concurrent or repeated calls write it once. * Called right after the commit and again at each turn start, so a write that * failed is retried rather than lost. Returns whether this call wrote it. */ export async function deliverPendingSandboxRestoreNotice( db: Database, input: { accountId: string; workspaceId: string } & ( | { sandboxGroupId: string; sessionId?: undefined } | { sessionId: string; sandboxGroupId?: undefined } ), ): Promise { const pendingIn = (resumeState: Record | null | undefined) => { const marker = resumeState?.opengeniAutomaticCheckpointRecovery as | Record | undefined; return marker && typeof marker === "object" && marker.status === "verified" && marker.noticePending === true && typeof marker.operationId === "string" && typeof marker.capturedAt === "string" ? { operationId: marker.operationId, capturedAt: marker.capturedAt } : null; }; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Best-effort at turn start and after a restore: never queue behind a // long lock; a pending notice stays pending for the next delivery. await tx.execute(sql`set local lock_timeout = '5s'`); return await withCompleteSandboxGroupScope(tx, async () => { const observed = await tx.execute<{ id: string; sandbox_group_id: string; resume_state: Record | null; }>( input.sandboxGroupId !== undefined ? sql`select id, sandbox_group_id, resume_state from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId}` : sql`select lease.id, lease.sandbox_group_id, lease.resume_state from sandbox_leases lease join sessions session on session.workspace_id = lease.workspace_id and session.sandbox_group_id = lease.sandbox_group_id where session.workspace_id = ${input.workspaceId} and session.id = ${input.sessionId} limit 1`, ); const lease = observed[0]; if (!lease || !pendingIn(lease.resume_state)) return false; const sessionIds = ( await tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.sandboxGroupId, lease.sandbox_group_id), ), ) .orderBy(asc(schema.sessions.id)) ).map((session) => session.id); await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "none", sessionIds, }); const locked = await tx.execute<{ resume_state: Record | null }>(sql` select resume_state from sandbox_leases where id = ${lease.id} for update `); const pending = pendingIn(locked[0]?.resume_state); if (!pending) return false; await appendSessionEventToSandboxGroup(tx, input.workspaceId, lease.sandbox_group_id, { type: "sandbox.recovery.selected", payload: { operationId: pending.operationId, mode: "checkpoint", capturedAt: pending.capturedAt, }, }); await tx.execute(sql` update sandbox_leases set resume_state = resume_state #- '{opengeniAutomaticCheckpointRecovery,noticePending}', updated_at = now() where id = ${lease.id} `); return true; }); }), ); } /** The drain's stop notice already told the people in the chat that changes * after exactly this save were not kept. A restore of any other save, or a * loss without that notice, is announced on its own. */ function stopNoticeNamedSave( loss: ProviderLossRecord | undefined, restoredCapturedAt: string, ): boolean { if (loss?.captureAbandoned !== true || typeof loss.unsavedSince !== "string") return false; const named = Date.parse(loss.unsavedSince); return Number.isFinite(named) && named === Date.parse(restoredCapturedAt); } /** Persist before provider dispatch. This is deliberately not replayable: a * timeout, absent running-name lookup, or expired lease cannot settle an * unknown create. A later exact provider receipt may attribute the operation. */ export async function beginModalProviderCreate( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; operationId: string; providerBindingKey: string; rematerializationId: string | null; selectedRevision: string | null; imageId: string | null; imageRef: string | null; appId: string; providerName: string; requestSha256: string; }, ): Promise { if ( !input.operationId || !input.providerBindingKey || !input.appId || input.providerName !== `opengeni-create-${input.operationId}` || !/^[a-f0-9]{64}$/u.test(input.requestSha256) ) { throw new Error("Modal create requires operation and provider namespace identities"); } await withRlsContext(db, input, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || row.backend !== "modal" || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch || row.instance_id !== null ) { throw new Error("Modal create lease no longer owns an unbound warming epoch"); } const current = recoveryStateFromLeaseRow(row); if ( current.restore.rematerializationId !== input.rematerializationId || current.restore.selectedRevision !== input.selectedRevision ) { throw new Error("Modal create selected recovery revision changed before dispatch"); } if ( row.provider_create_attempt?.instanceId === null || row.provider_create_attempt?.leaseEpoch === input.expectedEpoch ) { throw new Error("provider_create_outcome_unknown: provider attempt cannot be replayed"); } const attempt: SandboxProviderCreateAttempt = { version: 1, operationId: input.operationId, leaseEpoch: input.expectedEpoch, providerBindingKey: input.providerBindingKey, rematerializationId: input.rematerializationId, selectedRevision: input.selectedRevision, imageId: input.imageId, imageRef: input.imageRef, appId: input.appId, providerName: input.providerName, requestSha256: input.requestSha256, startedAt: new Date().toISOString(), instanceId: null, }; await tx.execute(sql` update sandbox_leases set provider_create_attempt = ${JSON.stringify(attempt)}::jsonb, provider_create_recovery_after = null, updated_at = now() where id = ${row.id} `); }), ); } export async function listPendingModalProviderCreates( db: Database, ): Promise> { const rows = await rawRows<{ workspace_id: string; sandbox_group_id: string }>( db, sql`select * from opengeni_private.list_pending_modal_provider_creates()`, ); return rows.map((row) => ({ workspaceId: row.workspace_id, sandboxGroupId: row.sandbox_group_id, })); } /** Throttle positive discovery without extending the warming lease or changing * its create authority. Old unresolved rows rotate behind the next batch. */ export async function claimModalProviderCreateRecovery( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb.execute<{ provider_create_attempt: SandboxProviderCreateAttempt; }>(sql` update sandbox_leases set provider_create_recovery_after = now() + interval '30 seconds' where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and backend = 'modal' and liveness = 'warming' and instance_id is null and provider_create_attempt->'instanceId' = 'null'::jsonb and expires_at < now() and coalesce(provider_create_recovery_after, '-infinity'::timestamptz) <= now() returning provider_create_attempt `); return rows[0]?.provider_create_attempt ?? null; }); } /** Modal ends every sandbox within 24 hours, its maximum lifetime (and the * most `modalTimeoutSeconds` allows). An unresolved create that started longer * ago than that plus an hour for dispatch and scheduling can own no running * box. The database guard enforces the same horizon (migration 1549). */ export const MODAL_PROVIDER_CREATE_SETTLE_AFTER_MS = 25 * 60 * 60 * 1000; export function modalProviderCreateOutlivedProvider( attempt: Pick, nowMs: number = Date.now(), ): boolean { const startedAtMs = Date.parse(attempt.startedAt); return ( Number.isFinite(startedAtMs) && nowMs - startedAtMs > MODAL_PROVIDER_CREATE_SETTLE_AFTER_MS ); } /** Clear an unresolved create that no receipt attributed within the provider's * maximum sandbox lifetime. Only the exact attempt on its own expired warming * epoch is cleared; the ordinary expired-warming reset then moves the lease to * cold with a new epoch, keeping its archive, so the next turn creates afresh. */ export async function settleExpiredModalProviderCreate( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; attempt: SandboxProviderCreateAttempt; }, ): Promise { if (input.attempt.instanceId !== null || !modalProviderCreateOutlivedProvider(input.attempt)) return false; return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set provider_create_attempt = null, provider_create_recovery_after = null, updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and backend = 'modal' and liveness = 'warming' and instance_id is null and lease_epoch = ${input.attempt.leaseEpoch} and provider_create_attempt = ${JSON.stringify(input.attempt)}::jsonb and expires_at < now() and (provider_create_attempt->>'startedAt')::timestamptz <= now() - (${String(MODAL_PROVIDER_CREATE_SETTLE_AFTER_MS)} || ' milliseconds')::interval returning id `); return rows.length > 0; }); } /** Attribute a positively identified late receipt, preserving expiry and every * checkpoint. Ordinary holder/epoch-fenced draining owns all physical cleanup. */ export async function recordRecoveredModalProviderCreate( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; attempt: SandboxProviderCreateAttempt; instanceId: string; }, ): Promise { if (!input.instanceId.startsWith("sb-") || input.attempt.instanceId !== null) throw new Error("Modal create recovery requires an unresolved operation and exact provider id"); return await withRlsContext(db, input, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql`select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and backend = 'modal' and liveness = 'warming' and instance_id is null and lease_epoch = ${input.attempt.leaseEpoch} and provider_create_attempt = ${JSON.stringify(input.attempt)}::jsonb for update`); const row = rows[0]; if (!row) return false; const current = recoveryStateFromLeaseRow(row); if ( current.restore.rematerializationId !== input.attempt.rematerializationId || current.restore.selectedRevision !== input.attempt.selectedRevision ) return false; const recovery: SandboxRecoveryState = { ...current, provider: { status: "creating", instanceId: input.instanceId, observedAt: new Date().toISOString(), }, workspace: { ...current.workspace, status: "not_ready", verifiedRevision: null, verifiedAt: null, }, }; await tx.execute(sql`update sandbox_leases set instance_id = ${input.instanceId}, provider_create_attempt = ${JSON.stringify({ ...input.attempt, instanceId: input.instanceId })}::jsonb, resume_state = ${JSON.stringify( resumeStateWithRecovery( { ...(resumeStateWithPreservedArchives(null, row.resume_state) ?? {}), ...(row.resume_state?.opengeniWarmBilling ? { opengeniWarmBilling: row.resume_state.opengeniWarmBilling } : {}), }, recovery, ), )}::jsonb, updated_at = now() where id = ${row.id}`); return true; }), ); } // §4.2a — leak-proof create attribution. The spawner calls this immediately // after the provider create returns, before display/readiness/setup work. It // intentionally does NOT bump lease_epoch or mark the lease warm; it only makes // the just-created provider id durable while the row is still warming so a // failure/reaper/provider-side sweep can identify and stop it. export async function recordWarmingSandboxCreated( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; providerCreateOperationId?: string; /** Exact restore attempt elected before provider create. Null for a fresh * archive-less create. Provider attribution is accepted only while the * warming row still carries this same attempt as well as this epoch. */ rematerializationId?: string | null; continuityRecovery?: SandboxProviderContinuityRecovery; instanceId: string; resumeBackendId?: string | null; resumeState?: Record | null; /** Conservative provider-call start, not callback completion. Required as * a pair for finite-lifetime providers such as Modal. */ providerCreatedAt?: Date | null; providerDeadlineAt?: Date | null; leaseTtlMs: number; /** The still-WARMING lease must keep the warming budget after create() returns: * provider manifest hydration and commitWarmingToWarm can exceed the 90s turn * TTL and trip the warming-death (c2) drain now that instance_id is set. * Desktop/display work is not part of warming; it is initialized lazily by * viewer attach or actual computer-use. Defaults to leaseTtlMs for callers. */ warmingLeaseTtlMs?: number; }, ): Promise<{ recorded: boolean; lease: LeaseSnapshot | null }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch) { return { recorded: false, lease: row ? mapLeaseRow(row) : null }; } const now = new Date().toISOString(); const current = recoveryStateFromLeaseRow(row); const createAttempt = row.provider_create_attempt?.leaseEpoch === input.expectedEpoch ? row.provider_create_attempt : null; if ( createAttempt && (createAttempt.leaseEpoch !== input.expectedEpoch || createAttempt.operationId !== input.providerCreateOperationId || (createAttempt.instanceId !== null && createAttempt.instanceId !== input.instanceId)) ) { return { recorded: false, lease: mapLeaseRow(row) }; } if (current.restore.rematerializationId !== (input.rematerializationId ?? null)) { return { recorded: false, lease: mapLeaseRow(row) }; } if (input.continuityRecovery) { const candidateRow: LeaseRow = { ...row, instance_id: input.instanceId, resume_backend_id: input.resumeBackendId ?? row.resume_backend_id, resume_state: input.resumeState ?? row.resume_state, }; const adoptedState = dockerContinuityRecoveryFromLeaseRow(candidateRow, input.instanceId); if ( !continuityRecoveryEquals(current.continuity, input.continuityRecovery) || !continuityRecoveryEquals(adoptedState, input.continuityRecovery, false) ) { return { recorded: false, lease: mapLeaseRow(row) }; } } else if (current.continuity) { // A normal fresh create/archive restore superseded the continuity // candidate. Never carry its authorization onto a different workspace. delete current.continuity; } const recovery: SandboxRecoveryState = { ...current, provider: { status: "creating", instanceId: input.instanceId, observedAt: now, }, workspace: { ...current.workspace, status: "not_ready", verifiedRevision: null, verifiedAt: null, }, }; const withArchives = resumeStateWithPreservedArchives( input.resumeState ?? null, row.resume_state, ); const resumeStateJson = JSON.stringify( resumeStateWithRecovery( { ...(withArchives ?? {}), ...(row.resume_state?.opengeniWarmBilling ? { opengeniWarmBilling: row.resume_state.opengeniWarmBilling } : {}), }, recovery, ), ); const warmingTtlMs = input.warmingLeaseTtlMs ?? input.leaseTtlMs; const providerCreatedAt = input.providerCreatedAt ?? null; const providerDeadlineAt = input.providerDeadlineAt ?? null; if ((providerCreatedAt === null) !== (providerDeadlineAt === null)) { throw new Error("Provider creation and deadline timestamps must be supplied together"); } if ( providerCreatedAt && providerDeadlineAt && providerDeadlineAt.getTime() <= providerCreatedAt.getTime() ) { throw new Error("Provider deadline must be later than provider creation"); } const updated = await tx.execute(sql` update sandbox_leases set instance_id = ${input.instanceId}, provider_create_attempt = ${ createAttempt ? JSON.stringify({ ...createAttempt, instanceId: input.instanceId }) : null }::jsonb, resume_backend_id = ${input.resumeBackendId ?? null}, resume_state = ${resumeStateJson}::jsonb, provider_created_at = ${providerCreatedAt?.toISOString() ?? null}::timestamptz, provider_deadline_at = ${providerDeadlineAt?.toISOString() ?? null}::timestamptz, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, expires_at = now() + (${String(warmingTtlMs)} || ' milliseconds')::interval, updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} returning * `); if (updated[0] && row.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, input); } return updated[0] ? { recorded: true, lease: mapLeaseRow(updated[0]) } : { recorded: false, lease: null }; }), ); } export type LostProviderWorkspaceSettlement = { processesLost: number; admissionsRejected: number; ptysClosed: number; processHoldersDeleted: number; }; export type ColdLostProviderObjectObservation = { providerBackend: string | null; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot" | null; objectId: string | null; status: "exists" | "missing" | "unknown"; observedAt: string | null; }; export type PreviewColdLostLeaseInstanceBlockersInput = { accountId: string; workspaceId: string; sessionId: string; sandboxGroupId: string; expectedLeaseId?: string; expectedBackend?: string; expectedCurrentEpoch?: number; expectedLostEpoch?: number; expectedLostInstanceId?: string; expectedRefcount?: number; expectedProviderBackend?: string; expectedRouteKind?: "home" | "active"; expectedRouteTargetId?: string | null; expectedRouteEpoch?: number; expectedWorkspaceGeneration?: number; expectedWorkspaceStatus?: SandboxWorkspaceReadiness; expectedRestoreStatus?: SandboxRestoreStatus; expectedRestoreFailureCode?: string | null; expectedArchiveGeneration?: number | null; expectedArchiveComplete?: boolean; expectedArchiveDescriptorVersion?: 1; expectedArchiveRevision?: string; expectedArchiveObjectKind?: "modal_filesystem_snapshot" | "modal_directory_snapshot"; expectedArchiveObjectId?: string; expectedDescriptorReferenceBytes?: number; expectedDescriptorReferenceSha256?: string; expectedReferenceBytes?: number; expectedReferenceSha256?: string; expectedTreeFingerprintAlgorithm?: "sha256"; expectedTreeFingerprintSha256?: string; expectedTreeEntryCount?: number; expectedTreeFileCount?: number; expectedTotalFileBytes?: number; expectedArchiveCapturedAt?: string; expectedArchiveVerificationState?: "verified" | "unverified"; expectedArchiveVerifiedRevision?: string | null; expectedArchiveVerifiedAt?: string | null; providerObject: ColdLostProviderObjectObservation; }; export type ColdLostReconciliationBlockerCode = | "database_transaction_not_read_only" | "database_row_security_disabled" | "database_role_is_superuser" | "database_role_bypasses_rls" | "database_force_rls_unverified" | "expected_lease_id_missing" | "expected_backend_missing" | "expected_current_epoch_missing" | "expected_lost_epoch_missing" | "expected_lost_instance_missing" | "expected_refcount_missing" | "expected_provider_backend_missing" | "expected_route_kind_missing" | "expected_route_target_missing" | "expected_route_epoch_missing" | "expected_workspace_generation_missing" | "expected_workspace_status_missing" | "expected_restore_status_missing" | "expected_restore_failure_missing" | "expected_archive_generation_missing" | "expected_archive_complete_missing" | "expected_archive_descriptor_version_missing" | "expected_archive_revision_missing" | "expected_archive_object_kind_missing" | "expected_archive_object_id_missing" | "expected_descriptor_reference_bytes_missing" | "expected_descriptor_reference_sha256_missing" | "expected_reference_bytes_missing" | "expected_reference_sha256_missing" | "expected_tree_fingerprint_algorithm_missing" | "expected_tree_fingerprint_sha256_missing" | "expected_tree_entry_count_missing" | "expected_tree_file_count_missing" | "expected_total_file_bytes_missing" | "expected_archive_captured_at_missing" | "expected_archive_verification_state_missing" | "expected_archive_verified_revision_missing" | "expected_archive_verified_at_missing" | "epoch_relation_invalid" | "session_not_found" | "session_group_mismatch" | "lease_not_found" | "lease_id_mismatch" | "lease_backend_mismatch" | "lost_provider_backend_mismatch" | "lease_not_cold" | "lease_instance_present" | "current_epoch_mismatch" | "refcount_mismatch" | "workspace_generation_mismatch" | "workspace_status_mismatch" | "restore_status_mismatch" | "restore_failure_mismatch" | "archive_generation_mismatch" | "archive_completeness_mismatch" | "lost_provider_recovery_unverified" | "archive_descriptor_missing" | "archive_generation_incomplete" | "archive_base64_invalid" | "archive_bytes_mismatch" | "archive_descriptor_version_mismatch" | "archive_revision_mismatch" | "archive_object_kind_mismatch" | "archive_object_id_mismatch" | "archive_descriptor_reference_bytes_mismatch" | "archive_descriptor_reference_sha256_mismatch" | "archive_reference_bytes_mismatch" | "archive_reference_sha256_mismatch" | "archive_tree_fingerprint_algorithm_mismatch" | "archive_tree_fingerprint_sha256_mismatch" | "archive_tree_entry_count_mismatch" | "archive_tree_file_count_mismatch" | "archive_total_file_bytes_mismatch" | "archive_captured_at_mismatch" | "archive_verification_state_mismatch" | "archive_verified_revision_mismatch" | "archive_verified_at_mismatch" | "archive_verification_unavailable" | "archive_provider_object_identity_unavailable" | "provider_object_observation_missing" | "provider_object_identity_mismatch" | "provider_object_missing" | "provider_object_status_unknown" | "provider_object_observation_time_invalid" | "exact_route_mismatch" | "unmatched_active_processes" | "unmatched_unsettled_admissions" | "unmatched_open_ptys" | "unmatched_process_holders" | "active_direct_holders" | "active_turn_writer_possible" | "turn_holder_attempt_linkage_unknown" | "unsettled_interruptions" | "blocker_inventory_incomplete"; export type ColdLostReconciliationPreview = { version: 1; status: "eligible" | "blocked"; previewId: string; snapshotAt: string; database: { role: string; roleSuperuser: boolean; roleBypassRls: boolean; transactionReadOnly: boolean; rowSecurity: boolean; forceRls: boolean; accountId: string; workspaceId: string; } | null; locator: { accountId: string; workspaceId: string; sessionId: string; sandboxGroupId: string; }; expected: { leaseId: string | null; backend: string | null; currentEpoch: number | null; lostEpoch: number | null; lostInstanceId: string | null; refcount: number | null; providerBackend: string | null; routeKind: "home" | "active" | null; routeTargetId: string | null; routeTargetSupplied: boolean; routeEpoch: number | null; workspaceGeneration: number | null; workspaceStatus: SandboxWorkspaceReadiness | null; restoreStatus: SandboxRestoreStatus | null; restoreFailureCode: string | null; restoreFailureSupplied: boolean; archiveGeneration: number | null; archiveGenerationSupplied: boolean; archiveComplete: boolean | null; archiveDescriptorVersion: 1 | null; archiveRevision: string | null; archiveObjectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot" | null; archiveObjectId: string | null; descriptorReferenceBytes: number | null; descriptorReferenceSha256: string | null; referenceBytes: number | null; referenceSha256: string | null; treeFingerprintAlgorithm: "sha256" | null; treeFingerprintSha256: string | null; treeEntryCount: number | null; treeFileCount: number | null; totalFileBytes: number | null; archiveCapturedAt: string | null; archiveVerificationState: "verified" | "unverified" | null; archiveVerifiedRevision: string | null; archiveVerifiedRevisionSupplied: boolean; archiveVerifiedAt: string | null; archiveVerifiedAtSupplied: boolean; }; session: { id: string; status: string; sandboxGroupId: string; activeSandboxId: string | null; activeEpoch: number; } | null; lease: { id: string; liveness: SandboxLeaseLiveness; instanceId: string | null; backend: string; leaseEpoch: number; workspaceGeneration: number; archiveGeneration: number | null; archiveComplete: boolean; refcount: number; turnHolders: number; viewerHolders: number; recoveryProviderStatus: SandboxProviderExistence; recoveryProviderInstanceId: string | null; workspaceStatus: SandboxWorkspaceReadiness; restoreStatus: SandboxRestoreStatus; restoreFailureCode: string | null; } | null; archive: { status: SandboxArchiveAvailability; descriptorVersion: 1 | 2 | null; revision: string | null; generation: number | null; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot" | null; objectId: string | null; descriptorReferenceBytes: number | null; descriptorReferenceSha256: string | null; referenceBytes: number | null; referenceSha256: string | null; referenceVerified: boolean; treeFingerprintAlgorithm: "sha256" | null; treeFingerprintSha256: string | null; entryCount: number | null; fileCount: number | null; totalFileBytes: number | null; complete: boolean; verificationState: "verified" | "unverified"; capturedAt: string | null; verifiedRevision: string | null; verifiedAt: string | null; providerObservation: { providerBackend: string | null; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot" | null; objectId: string | null; status: "exists" | "missing" | "unknown"; observedAt: string | null; }; }; active: { exactProcesses: number; exactAdmissions: number; exactPtys: number; exactProcessHolders: number; unmatchedProcesses: number; unmatchedAdmissions: number; unmatchedPtys: number; unmatchedProcessHolders: number; directHolders: number; possibleWriterTurnHolders: number; unknownTurnHolderLinks: number; unsettledInterruptions: number; turnHolders: number; viewerHolders: number; inventoryComplete: boolean; }; identities: { processes: ColdLostProcessRow[]; admissions: ColdLostAdmissionRow[]; ptys: ColdLostPtyRow[]; holders: ColdLostHolderRow[]; interruptions: ColdLostInterruptionRow[]; }; settlement: LostProviderWorkspaceSettlement; blockerSetHash: string; blockers: ColdLostReconciliationBlockerCode[]; }; type ColdLostProcessRow = { id: string; sessionId: string; parentAdmissionId: string; holder_id: string; ownerActorKind: string; ownerActorId: string; ownerTurnId: string | null; ownerAttemptId: string | null; ownerExecutionGeneration: number | null; lease_epoch: number | string; providerBackend: string; provider_instance_id: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; providerSessionId: number; state: string; }; type ColdLostAdmissionRow = { id: string; sessionId: string; actorKind: string; actorId: string; turnId: string | null; attemptId: string | null; executionGeneration: number | null; holderKind: string; holderId: string; lease_epoch: number | string; providerBackend: string; provider_instance_id: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; workspaceGeneration: number; operation: string; providerOutcome: string | null; settled_at: Date | string | null; }; type ColdLostPtyRow = { id: string; sessionId: string; retainedProcessId: string | null; openAdmissionId: string | null; execSessionId: number | null; lease_epoch: number | string; providerBackend: string | null; provider_instance_id: string | null; routeKind: "home" | "active" | null; routeTargetId: string | null; routeEpoch: number | null; status: string; }; type ColdLostHolderRow = { id: string; kind: string; holder_id: string; subjectId: string | null; turnId: string | null; attemptId: string | null; attemptExecutionGeneration: number | null; attemptState: string | null; attemptOutcome: string | null; attemptQuiescedAt: string | null; }; type ColdLostInterruptionRow = { id: string; sessionId: string; operationId: string; attemptId: string; turnId: string; attemptExecutionGeneration: number; attemptState: string; attemptOutcome: string | null; attemptQuiescedAt: string | null; kind: string; state: string; requestedAt: string; }; type ColdLostSessionRow = { id: string; status: string; sandbox_group_id: string; active_sandbox_id: string | null; active_epoch: number | string; }; type ColdLostDatabasePosture = NonNullable; type ColdLostSnapshotRows = { snapshotAt: string; inventoryComplete: boolean; session: ColdLostSessionRow | null; lease: LeaseRow | null; processes: ColdLostProcessRow[]; admissions: ColdLostAdmissionRow[]; ptys: ColdLostPtyRow[]; holders: ColdLostHolderRow[]; interruptions: ColdLostInterruptionRow[]; }; const MODAL_ARCHIVE_PREFIXES = [ "MODAL_SANDBOX_FS_SNAPSHOT_V1\n", "MODAL_SANDBOX_DIR_SNAPSHOT_V1\n", ] as const; const COLD_LOST_PROVIDER_OBSERVATION_MAX_AGE_MS = 5 * 60 * 1_000; const COLD_LOST_PROVIDER_OBSERVATION_MAX_FUTURE_MS = 60 * 1_000; function sha256String(value: string | Uint8Array): string { return createHash("sha256").update(value).digest("hex"); } function decodeCanonicalBase64(value: unknown): Uint8Array | null { if ( typeof value !== "string" || value.length === 0 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value) ) { return null; } // Archives reach hundreds of MB: decode once into a view (no copy), and // prove canonical form from the length and the final quantum, the only place // non-zero pad bits can hide, instead of re-encoding the whole payload. const decoded = Buffer.from(value, "base64"); const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0; if (decoded.length !== (value.length / 4) * 3 - padding) return null; const lastQuantumStart = (value.length / 4 - 1) * 3; if (decoded.subarray(lastQuantumStart).toString("base64") !== value.slice(-4)) return null; return new Uint8Array(decoded.buffer, decoded.byteOffset, decoded.length); } function modalProviderObject(bytes: Uint8Array | null): { kind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; id: string; } | null { if (!bytes) return null; const text = new TextDecoder().decode(bytes); for (const prefix of MODAL_ARCHIVE_PREFIXES) { if (!text.startsWith(prefix)) continue; try { const parsed = JSON.parse(text.slice(prefix.length)) as { snapshot_id?: unknown; }; if (typeof parsed.snapshot_id !== "string" || parsed.snapshot_id.length === 0) { return null; } return { kind: prefix === MODAL_ARCHIVE_PREFIXES[0] ? "modal_filesystem_snapshot" : "modal_directory_snapshot", id: parsed.snapshot_id, }; } catch { return null; } } return null; } function stableSetHash(value: unknown): string { return sha256String(JSON.stringify(value)); } function isFreshCanonicalProviderObservationTime( observedAt: string | null, snapshotAt: string, ): boolean { if (observedAt === null) return false; const observedAtMs = Date.parse(observedAt); const snapshotAtMs = Date.parse(snapshotAt); return ( Number.isFinite(observedAtMs) && Number.isFinite(snapshotAtMs) && new Date(observedAtMs).toISOString() === observedAt && observedAtMs >= snapshotAtMs - COLD_LOST_PROVIDER_OBSERVATION_MAX_AGE_MS && observedAtMs <= snapshotAtMs + COLD_LOST_PROVIDER_OBSERVATION_MAX_FUTURE_MS ); } function isExactLostScope( row: { lease_epoch: number | string; providerBackend: string | null; provider_instance_id: string | null; routeKind: "home" | "active" | null; routeTargetId: string | null; routeEpoch: number | null; }, input: PreviewColdLostLeaseInstanceBlockersInput, ): boolean { return ( input.expectedLostEpoch !== undefined && input.expectedLostInstanceId !== undefined && input.expectedProviderBackend !== undefined && input.expectedRouteKind !== undefined && input.expectedRouteTargetId !== undefined && input.expectedRouteEpoch !== undefined && Number(row.lease_epoch) === input.expectedLostEpoch && row.providerBackend === input.expectedProviderBackend && row.provider_instance_id === input.expectedLostInstanceId && row.routeKind === input.expectedRouteKind && row.routeTargetId === input.expectedRouteTargetId && row.routeEpoch === input.expectedRouteEpoch ); } function archiveSessionState(row: LeaseRow | null): Record | null { const resume = row?.resume_state; if (!resume || typeof resume !== "object") return null; const sessionState = resume.sessionState; return sessionState && typeof sessionState === "object" ? (sessionState as Record) : null; } async function readColdLostSnapshotRowsTx( tx: Database, input: PreviewColdLostLeaseInstanceBlockersInput, ): Promise { const timestampRows = await tx.execute<{ snapshot_at: Date | string }>(sql` select transaction_timestamp() as snapshot_at `); const [sessionRows, leaseRows] = await Promise.all([ tx.execute(sql` select id, status, sandbox_group_id, active_sandbox_id, active_epoch from sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and id = ${input.sessionId} `), tx.execute(sql` select * from sandbox_leases where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} `), ]); const session = sessionRows[0] ?? null; const lease = leaseRows[0] ?? null; if (!lease) { const snapshotAt = timestampRows[0]?.snapshot_at; return { snapshotAt: snapshotAt instanceof Date ? snapshotAt.toISOString() : new Date(snapshotAt ?? Date.now()).toISOString(), inventoryComplete: false, session, lease: null, processes: [], admissions: [], ptys: [], holders: [], interruptions: [], }; } const [processes, admissions, ptys, holders, interruptions] = await Promise.all([ tx.execute(sql` select id, session_id as "sessionId", parent_admission_id as "parentAdmissionId", holder_id, owner_actor_kind as "ownerActorKind", owner_actor_id as "ownerActorId", owner_turn_id as "ownerTurnId", owner_attempt_id as "ownerAttemptId", owner_execution_generation as "ownerExecutionGeneration", lease_epoch, provider_backend as "providerBackend", provider_instance_id, route_kind as "routeKind", route_target_id as "routeTargetId", route_epoch as "routeEpoch", provider_session_id as "providerSessionId", state from sandbox_retained_processes where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${lease.id} and sandbox_group_id = ${input.sandboxGroupId} and (state = 'active' or ( lease_epoch = ${input.expectedLostEpoch ?? -1} and provider_backend = ${input.expectedProviderBackend ?? ""} and provider_instance_id = ${input.expectedLostInstanceId ?? ""} and route_kind = ${input.expectedRouteKind ?? "home"} and route_target_id is not distinct from ${input.expectedRouteTargetId ?? null} and route_epoch = ${input.expectedRouteEpoch ?? -1} )) order by id `), tx.execute(sql` select id, session_id as "sessionId", actor_kind as "actorKind", actor_id as "actorId", turn_id as "turnId", attempt_id as "attemptId", execution_generation as "executionGeneration", holder_kind as "holderKind", holder_id as "holderId", lease_epoch, provider_backend as "providerBackend", provider_instance_id, route_kind as "routeKind", route_target_id as "routeTargetId", route_epoch as "routeEpoch", workspace_generation as "workspaceGeneration", operation, provider_outcome as "providerOutcome", settled_at from sandbox_workspace_mutation_admissions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${lease.id} and sandbox_group_id = ${input.sandboxGroupId} and (settled_at is null or ( lease_epoch = ${input.expectedLostEpoch ?? -1} and provider_backend = ${input.expectedProviderBackend ?? ""} and provider_instance_id = ${input.expectedLostInstanceId ?? ""} and route_kind = ${input.expectedRouteKind ?? "home"} and route_target_id is not distinct from ${input.expectedRouteTargetId ?? null} and route_epoch = ${input.expectedRouteEpoch ?? -1} )) order by id `), tx.execute(sql` select id, session_id as "sessionId", retained_process_id as "retainedProcessId", open_admission_id as "openAdmissionId", exec_session_id as "execSessionId", lease_epoch, provider_backend as "providerBackend", provider_instance_id, route_kind as "routeKind", route_target_id as "routeTargetId", route_epoch as "routeEpoch", status from sandbox_pty_sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${lease.id} and sandbox_group_id = ${input.sandboxGroupId} and (status = 'open' or ( lease_epoch = ${input.expectedLostEpoch ?? -1} and provider_backend = ${input.expectedProviderBackend ?? ""} and provider_instance_id = ${input.expectedLostInstanceId ?? ""} and route_kind = ${input.expectedRouteKind ?? "home"} and route_target_id is not distinct from ${input.expectedRouteTargetId ?? null} and route_epoch = ${input.expectedRouteEpoch ?? -1} )) order by id `), tx.execute(sql` select holder.id, holder.kind, holder.holder_id, holder.subject_id as "subjectId", attempt.turn_id as "turnId", attempt.id as "attemptId", attempt.execution_generation as "attemptExecutionGeneration", attempt.state as "attemptState", attempt.outcome as "attemptOutcome", attempt.quiesced_at as "attemptQuiescedAt" from sandbox_lease_holders holder left join session_turn_attempts attempt on holder.kind = 'turn' and holder.holder_id = ('turn-attempt:' || attempt.id::text) and attempt.account_id = holder.account_id and attempt.workspace_id = holder.workspace_id where holder.account_id = ${input.accountId} and holder.workspace_id = ${input.workspaceId} and holder.lease_id = ${lease.id} order by holder.kind, holder.holder_id `), tx.execute(sql` select interruption.id, interruption.session_id as "sessionId", interruption.operation_id as "operationId", interruption.attempt_id as "attemptId", attempt.turn_id as "turnId", attempt.execution_generation as "attemptExecutionGeneration", attempt.state as "attemptState", attempt.outcome as "attemptOutcome", attempt.quiesced_at as "attemptQuiescedAt", interruption.kind, interruption.state, interruption.requested_at as "requestedAt" from session_attempt_interruptions interruption join sessions session on session.workspace_id = interruption.workspace_id and session.id = interruption.session_id and session.sandbox_group_id = ${input.sandboxGroupId} join session_turn_attempts attempt on attempt.workspace_id = interruption.workspace_id and attempt.id = interruption.attempt_id where interruption.account_id = ${input.accountId} and interruption.workspace_id = ${input.workspaceId} and interruption.state in ('pending', 'delivered', 'acknowledged') order by interruption.id `), ]); const snapshotAt = timestampRows[0]?.snapshot_at; return { snapshotAt: snapshotAt instanceof Date ? snapshotAt.toISOString() : new Date(snapshotAt ?? Date.now()).toISOString(), inventoryComplete: true, session, lease, processes, admissions, ptys, holders, interruptions, }; } function evaluateColdLostSnapshot( input: PreviewColdLostLeaseInstanceBlockersInput, rows: ColdLostSnapshotRows, database: ColdLostDatabasePosture | null, options: { requireReadOnly: boolean } = { requireReadOnly: true }, ): ColdLostReconciliationPreview { const blockers: ColdLostReconciliationBlockerCode[] = []; const add = (code: ColdLostReconciliationBlockerCode, blocked: boolean): void => { if (blocked && !blockers.includes(code)) blockers.push(code); }; if (database) { add( "database_transaction_not_read_only", options.requireReadOnly && !database.transactionReadOnly, ); add("database_row_security_disabled", !database.rowSecurity); add("database_role_is_superuser", database.roleSuperuser); add("database_role_bypasses_rls", database.roleBypassRls); add("database_force_rls_unverified", !database.forceRls); } else { add("database_force_rls_unverified", true); } add("expected_lease_id_missing", input.expectedLeaseId === undefined); add("expected_backend_missing", input.expectedBackend === undefined); add("expected_current_epoch_missing", input.expectedCurrentEpoch === undefined); add("expected_lost_epoch_missing", input.expectedLostEpoch === undefined); add("expected_lost_instance_missing", input.expectedLostInstanceId === undefined); add("expected_refcount_missing", input.expectedRefcount === undefined); add("expected_provider_backend_missing", input.expectedProviderBackend === undefined); add("expected_route_kind_missing", input.expectedRouteKind === undefined); add("expected_route_target_missing", input.expectedRouteTargetId === undefined); add("expected_route_epoch_missing", input.expectedRouteEpoch === undefined); add("expected_workspace_generation_missing", input.expectedWorkspaceGeneration === undefined); add("expected_workspace_status_missing", input.expectedWorkspaceStatus === undefined); add("expected_restore_status_missing", input.expectedRestoreStatus === undefined); add("expected_restore_failure_missing", input.expectedRestoreFailureCode === undefined); add("expected_archive_generation_missing", input.expectedArchiveGeneration === undefined); add("expected_archive_complete_missing", input.expectedArchiveComplete === undefined); add( "expected_archive_descriptor_version_missing", input.expectedArchiveDescriptorVersion === undefined, ); add("expected_archive_revision_missing", input.expectedArchiveRevision === undefined); add("expected_archive_object_kind_missing", input.expectedArchiveObjectKind === undefined); add("expected_archive_object_id_missing", input.expectedArchiveObjectId === undefined); add( "expected_descriptor_reference_bytes_missing", input.expectedDescriptorReferenceBytes === undefined, ); add( "expected_descriptor_reference_sha256_missing", input.expectedDescriptorReferenceSha256 === undefined, ); add("expected_reference_bytes_missing", input.expectedReferenceBytes === undefined); add("expected_reference_sha256_missing", input.expectedReferenceSha256 === undefined); add( "expected_tree_fingerprint_algorithm_missing", input.expectedTreeFingerprintAlgorithm === undefined, ); add( "expected_tree_fingerprint_sha256_missing", input.expectedTreeFingerprintSha256 === undefined, ); add("expected_tree_entry_count_missing", input.expectedTreeEntryCount === undefined); add("expected_tree_file_count_missing", input.expectedTreeFileCount === undefined); add("expected_total_file_bytes_missing", input.expectedTotalFileBytes === undefined); add("expected_archive_captured_at_missing", input.expectedArchiveCapturedAt === undefined); add( "expected_archive_verification_state_missing", input.expectedArchiveVerificationState === undefined, ); add( "expected_archive_verified_revision_missing", input.expectedArchiveVerifiedRevision === undefined, ); add("expected_archive_verified_at_missing", input.expectedArchiveVerifiedAt === undefined); add( "epoch_relation_invalid", input.expectedCurrentEpoch !== undefined && input.expectedLostEpoch !== undefined && input.expectedCurrentEpoch !== input.expectedLostEpoch + 1, ); const session = rows.session; add("blocker_inventory_incomplete", !rows.inventoryComplete); add("session_not_found", session === null); add( "session_group_mismatch", session !== null && session.sandbox_group_id !== input.sandboxGroupId, ); const row = rows.lease; const lease = row ? mapLeaseRow(row) : null; const recovery = row ? recoveryStateFromLeaseRow(row) : null; add("lease_not_found", row === null); add( "lease_id_mismatch", row !== null && input.expectedLeaseId !== undefined && row.id !== input.expectedLeaseId, ); add( "lease_backend_mismatch", row !== null && input.expectedBackend !== undefined && row.backend !== input.expectedBackend, ); add( "lost_provider_backend_mismatch", row !== null && input.expectedProviderBackend !== undefined && row.backend !== input.expectedProviderBackend, ); add("lease_not_cold", row !== null && row.liveness !== "cold"); add("lease_instance_present", row !== null && row.instance_id !== null); add( "current_epoch_mismatch", row !== null && input.expectedCurrentEpoch !== undefined && Number(row.lease_epoch) !== input.expectedCurrentEpoch, ); add( "refcount_mismatch", row !== null && input.expectedRefcount !== undefined && Number(row.refcount) !== input.expectedRefcount, ); add( "workspace_generation_mismatch", row !== null && input.expectedWorkspaceGeneration !== undefined && Number(row.workspace_generation) !== input.expectedWorkspaceGeneration, ); add( "workspace_status_mismatch", recovery !== null && input.expectedWorkspaceStatus !== undefined && recovery.workspace.status !== input.expectedWorkspaceStatus, ); add( "restore_status_mismatch", recovery !== null && input.expectedRestoreStatus !== undefined && recovery.restore.status !== input.expectedRestoreStatus, ); add( "restore_failure_mismatch", recovery !== null && input.expectedRestoreFailureCode !== undefined && (recovery.restore.failureCode ?? null) !== input.expectedRestoreFailureCode, ); const archiveGeneration = row ? row.archive_generation === null ? null : Number(row.archive_generation) : null; add( "archive_generation_mismatch", row !== null && input.expectedArchiveGeneration !== undefined && archiveGeneration !== input.expectedArchiveGeneration, ); const archiveComplete = row ? hasCompleteWorkspaceArchive(row) : false; add( "archive_completeness_mismatch", row !== null && input.expectedArchiveComplete !== undefined && archiveComplete !== input.expectedArchiveComplete, ); add( "lost_provider_recovery_unverified", row !== null && (recovery?.provider.status !== "missing" || input.expectedLostInstanceId === undefined || recovery.provider.instanceId !== input.expectedLostInstanceId), ); add( "exact_route_mismatch", (input.expectedRouteKind === "home" && input.expectedRouteTargetId !== undefined && input.expectedRouteEpoch !== undefined && (input.expectedRouteTargetId !== null || input.expectedRouteEpoch !== 0)) || (input.expectedRouteKind === "active" && session !== null && input.expectedRouteTargetId !== undefined && input.expectedRouteEpoch !== undefined && (session.active_sandbox_id !== input.expectedRouteTargetId || Number(session.active_epoch) !== input.expectedRouteEpoch)), ); const descriptor = recovery?.archive.current ?? null; const treeDescriptor = descriptor?.version === 1 ? descriptor : null; const sessionState = archiveSessionState(row); const base64 = sessionState?.workspaceArchive; const objectRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchiveRef); const inlineBytes = decodeCanonicalBase64(base64); const inlineObjectMismatch = Boolean( inlineBytes && objectRef && (sha256String(inlineBytes) !== objectRef.sha256 || inlineBytes.length !== objectRef.bytes), ); const bytes = inlineBytes; const referenceBytes = inlineBytes?.length ?? objectRef?.bytes ?? null; const referenceSha256 = inlineBytes ? sha256String(inlineBytes) : (objectRef?.sha256 ?? null); const referenceVerified = descriptor !== null && !inlineObjectMismatch && referenceBytes === descriptor.archiveBytes && referenceSha256 === descriptor.archiveSha256; const archiveObject = modalProviderObject(bytes); const archiveVerificationMatches = descriptor !== null && recovery?.workspace.status === "ready" && recovery.workspace.verifiedRevision === descriptor.revision && recovery.workspace.verifiedAt !== null && Number.isFinite(Date.parse(recovery.workspace.verifiedAt)); const archiveVerificationState = archiveVerificationMatches ? ("verified" as const) : ("unverified" as const); const verifiedRevision = recovery?.workspace.verifiedRevision ?? null; const verifiedAt = archiveVerificationMatches ? recovery!.workspace.verifiedAt : null; add("archive_descriptor_missing", descriptor === null); add( "archive_generation_incomplete", row !== null && (archiveGeneration === null || archiveGeneration !== Number(row.workspace_generation) || !archiveComplete), ); add("archive_base64_invalid", row !== null && bytes === null && objectRef === null); add("archive_bytes_mismatch", descriptor !== null && !referenceVerified); add( "archive_descriptor_version_mismatch", input.expectedArchiveDescriptorVersion !== undefined && descriptor?.version !== input.expectedArchiveDescriptorVersion, ); add( "archive_revision_mismatch", input.expectedArchiveRevision !== undefined && descriptor?.revision !== input.expectedArchiveRevision, ); add( "archive_object_kind_mismatch", input.expectedArchiveObjectKind !== undefined && archiveObject?.kind !== input.expectedArchiveObjectKind, ); add( "archive_object_id_mismatch", input.expectedArchiveObjectId !== undefined && archiveObject?.id !== input.expectedArchiveObjectId, ); add( "archive_descriptor_reference_bytes_mismatch", input.expectedDescriptorReferenceBytes !== undefined && descriptor?.archiveBytes !== input.expectedDescriptorReferenceBytes, ); add( "archive_descriptor_reference_sha256_mismatch", input.expectedDescriptorReferenceSha256 !== undefined && descriptor?.archiveSha256 !== input.expectedDescriptorReferenceSha256, ); add( "archive_reference_bytes_mismatch", input.expectedReferenceBytes !== undefined && referenceBytes !== input.expectedReferenceBytes, ); add( "archive_reference_sha256_mismatch", input.expectedReferenceSha256 !== undefined && referenceSha256 !== input.expectedReferenceSha256, ); add( "archive_tree_fingerprint_algorithm_mismatch", input.expectedTreeFingerprintAlgorithm !== undefined && treeDescriptor?.workspace.algorithm !== input.expectedTreeFingerprintAlgorithm, ); add( "archive_tree_fingerprint_sha256_mismatch", input.expectedTreeFingerprintSha256 !== undefined && treeDescriptor?.workspace.sha256 !== input.expectedTreeFingerprintSha256, ); add( "archive_tree_entry_count_mismatch", input.expectedTreeEntryCount !== undefined && treeDescriptor?.workspace.entryCount !== input.expectedTreeEntryCount, ); add( "archive_tree_file_count_mismatch", input.expectedTreeFileCount !== undefined && treeDescriptor?.workspace.fileCount !== input.expectedTreeFileCount, ); add( "archive_total_file_bytes_mismatch", input.expectedTotalFileBytes !== undefined && treeDescriptor?.workspace.totalFileBytes !== input.expectedTotalFileBytes, ); add( "archive_captured_at_mismatch", input.expectedArchiveCapturedAt !== undefined && descriptor?.capturedAt !== input.expectedArchiveCapturedAt, ); add( "archive_verification_state_mismatch", input.expectedArchiveVerificationState !== undefined && archiveVerificationState !== input.expectedArchiveVerificationState, ); add( "archive_verified_revision_mismatch", input.expectedArchiveVerifiedRevision !== undefined && verifiedRevision !== input.expectedArchiveVerifiedRevision, ); add( "archive_verified_at_mismatch", input.expectedArchiveVerifiedAt !== undefined && verifiedAt !== input.expectedArchiveVerifiedAt, ); add("archive_verification_unavailable", descriptor !== null && !archiveVerificationMatches); add("archive_provider_object_identity_unavailable", row !== null && archiveObject === null); add( "provider_object_observation_missing", input.providerObject.providerBackend === null || input.providerObject.objectKind === null || input.providerObject.objectId === null, ); add( "provider_object_identity_mismatch", archiveObject !== null && (input.providerObject.providerBackend !== row?.backend || input.providerObject.providerBackend !== input.expectedProviderBackend || input.providerObject.objectKind !== archiveObject.kind || input.providerObject.objectId !== archiveObject.id), ); add("provider_object_missing", input.providerObject.status === "missing"); add("provider_object_status_unknown", input.providerObject.status === "unknown"); add( "provider_object_observation_time_invalid", !isFreshCanonicalProviderObservationTime(input.providerObject.observedAt, rows.snapshotAt), ); const exactProcesses = rows.processes.filter((process) => isExactLostScope(process, input)); const exactAdmissions = rows.admissions.filter((admission) => isExactLostScope(admission, input)); const exactPtys = rows.ptys.filter((pty) => isExactLostScope(pty, input)); const activeExactProcesses = exactProcesses.filter((process) => process.state === "active"); const activeExactAdmissions = exactAdmissions.filter( (admission) => admission.settled_at === null, ); const activeExactPtys = exactPtys.filter((pty) => pty.status === "open"); const activeExactProcessHolderIds = new Set( activeExactProcesses.map((process) => process.holder_id), ); const exactProcessHolders = rows.holders.filter( (holder) => holder.kind === "process" && activeExactProcessHolderIds.has(holder.holder_id), ); const unmatchedProcesses = rows.processes.filter( (process) => process.state === "active" && !isExactLostScope(process, input), ); const unmatchedAdmissions = rows.admissions.filter( (admission) => admission.settled_at === null && !isExactLostScope(admission, input), ); const unmatchedPtys = rows.ptys.filter( (pty) => pty.status === "open" && !isExactLostScope(pty, input), ); const unmatchedProcessHolders = rows.holders.filter( (holder) => holder.kind === "process" && !activeExactProcessHolderIds.has(holder.holder_id), ); add("unmatched_active_processes", unmatchedProcesses.length > 0); add("unmatched_unsettled_admissions", unmatchedAdmissions.length > 0); add("unmatched_open_ptys", unmatchedPtys.length > 0); add("unmatched_process_holders", unmatchedProcessHolders.length > 0); const directHolders = rows.holders.filter((holder) => holder.kind === "direct"); const turnHoldersWithUnknownAttempt = rows.holders.filter( (holder) => holder.kind === "turn" && holder.attemptId === null, ); const possibleWriterTurnHolders = rows.holders.filter( (holder) => holder.kind === "turn" && (holder.attemptState === "claimed" || holder.attemptState === "running") && holder.attemptQuiescedAt === null, ); const unsettledInterruptions = rows.interruptions; add("active_direct_holders", directHolders.length > 0); add("turn_holder_attempt_linkage_unknown", turnHoldersWithUnknownAttempt.length > 0); add("active_turn_writer_possible", possibleWriterTurnHolders.length > 0); add("unsettled_interruptions", unsettledInterruptions.length > 0); const exactIdentity = { processes: exactProcesses.map((process) => ({ id: process.id, sessionId: process.sessionId, parentAdmissionId: process.parentAdmissionId, holderId: process.holder_id, ownerActorKind: process.ownerActorKind, ownerActorId: process.ownerActorId, ownerTurnId: process.ownerTurnId, ownerAttemptId: process.ownerAttemptId, ownerExecutionGeneration: process.ownerExecutionGeneration, leaseEpoch: Number(process.lease_epoch), providerBackend: process.providerBackend, providerInstanceId: process.provider_instance_id, routeKind: process.routeKind, routeTargetId: process.routeTargetId, routeEpoch: process.routeEpoch, providerSessionId: process.providerSessionId, })), admissions: exactAdmissions.map((admission) => ({ id: admission.id, sessionId: admission.sessionId, actorKind: admission.actorKind, actorId: admission.actorId, turnId: admission.turnId, attemptId: admission.attemptId, executionGeneration: admission.executionGeneration, holderKind: admission.holderKind, holderId: admission.holderId, leaseEpoch: Number(admission.lease_epoch), providerBackend: admission.providerBackend, providerInstanceId: admission.provider_instance_id, routeKind: admission.routeKind, routeTargetId: admission.routeTargetId, routeEpoch: admission.routeEpoch, workspaceGeneration: admission.workspaceGeneration, operation: admission.operation, })), ptys: exactPtys.map((pty) => ({ id: pty.id, sessionId: pty.sessionId, retainedProcessId: pty.retainedProcessId, openAdmissionId: pty.openAdmissionId, execSessionId: pty.execSessionId, leaseEpoch: Number(pty.lease_epoch), providerBackend: pty.providerBackend, providerInstanceId: pty.provider_instance_id, routeKind: pty.routeKind, routeTargetId: pty.routeTargetId, routeEpoch: pty.routeEpoch, })), }; const unmatchedIdentity = { processes: unmatchedProcesses, admissions: unmatchedAdmissions, ptys: unmatchedPtys, processHolders: unmatchedProcessHolders, directHolders, possibleWriterTurnHolders, unknownTurnHolderLinks: turnHoldersWithUnknownAttempt, interruptions: unsettledInterruptions, }; const blockerSetHash = stableSetHash({ exactIdentity, exactCounts: { processes: exactProcesses.length, admissions: exactAdmissions.length, ptys: exactPtys.length, processHolders: exactProcessHolders.length, }, unmatchedIdentity, }); const previewIdentity = { version: 1, locator: { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sandboxGroupId: input.sandboxGroupId, }, expected: { leaseId: input.expectedLeaseId ?? null, backend: input.expectedBackend ?? null, currentEpoch: input.expectedCurrentEpoch ?? null, lostEpoch: input.expectedLostEpoch ?? null, lostInstanceId: input.expectedLostInstanceId ?? null, refcount: input.expectedRefcount ?? null, providerBackend: input.expectedProviderBackend ?? null, routeKind: input.expectedRouteKind ?? null, routeTargetId: input.expectedRouteTargetId === undefined ? "missing" : input.expectedRouteTargetId, routeEpoch: input.expectedRouteEpoch ?? null, workspaceGeneration: input.expectedWorkspaceGeneration ?? null, workspaceStatus: input.expectedWorkspaceStatus ?? null, restoreStatus: input.expectedRestoreStatus ?? null, restoreFailureCode: input.expectedRestoreFailureCode === undefined ? "missing" : input.expectedRestoreFailureCode, archiveGeneration: input.expectedArchiveGeneration === undefined ? "missing" : input.expectedArchiveGeneration, archiveComplete: input.expectedArchiveComplete ?? null, archiveDescriptorVersion: input.expectedArchiveDescriptorVersion ?? null, archiveRevision: input.expectedArchiveRevision ?? null, archiveObjectKind: input.expectedArchiveObjectKind ?? null, archiveObjectId: input.expectedArchiveObjectId ?? null, descriptorReferenceBytes: input.expectedDescriptorReferenceBytes ?? null, descriptorReferenceSha256: input.expectedDescriptorReferenceSha256 ?? null, referenceBytes: input.expectedReferenceBytes ?? null, referenceSha256: input.expectedReferenceSha256 ?? null, treeFingerprintAlgorithm: input.expectedTreeFingerprintAlgorithm ?? null, treeFingerprintSha256: input.expectedTreeFingerprintSha256 ?? null, treeEntryCount: input.expectedTreeEntryCount ?? null, treeFileCount: input.expectedTreeFileCount ?? null, totalFileBytes: input.expectedTotalFileBytes ?? null, archiveCapturedAt: input.expectedArchiveCapturedAt ?? null, archiveVerificationState: input.expectedArchiveVerificationState ?? null, archiveVerifiedRevision: input.expectedArchiveVerifiedRevision === undefined ? "missing" : input.expectedArchiveVerifiedRevision, archiveVerifiedAt: input.expectedArchiveVerifiedAt === undefined ? "missing" : input.expectedArchiveVerifiedAt, }, session: session ? { id: session.id, status: session.status, sandboxGroupId: session.sandbox_group_id, activeSandboxId: session.active_sandbox_id, activeEpoch: Number(session.active_epoch), } : null, lease: row ? { id: row.id, liveness: row.liveness, instanceId: row.instance_id, backend: row.backend, leaseEpoch: Number(row.lease_epoch), refcount: Number(row.refcount), turnHolders: Number(row.turn_holders), viewerHolders: Number(row.viewer_holders), workspaceGeneration: Number(row.workspace_generation), archiveGeneration, archiveComplete, recoveryProviderStatus: recovery!.provider.status, recoveryProviderInstanceId: recovery!.provider.instanceId, workspaceStatus: recovery!.workspace.status, restoreStatus: recovery!.restore.status, restoreFailureCode: recovery!.restore.failureCode ?? null, } : null, archive: { descriptor, referenceBytes, referenceSha256, referenceVerified, object: archiveObject, verificationState: archiveVerificationMatches ? "verified" : "unverified", capturedAt: descriptor?.capturedAt ?? null, verifiedAt: archiveVerificationMatches ? recovery!.workspace.verifiedAt : null, providerObservation: input.providerObject, }, inventoryComplete: rows.inventoryComplete, identities: { processes: rows.processes, admissions: rows.admissions, ptys: rows.ptys, holders: rows.holders, interruptions: rows.interruptions, }, blockerSetHash, }; const previewId = `clrp1:${stableSetHash(previewIdentity)}`; const turnHolders = rows.holders.filter((holder) => holder.kind === "turn").length; const viewerHolders = rows.holders.filter((holder) => holder.kind === "viewer").length; return { version: 1, status: blockers.length === 0 ? "eligible" : "blocked", previewId, snapshotAt: rows.snapshotAt, database, locator: { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sandboxGroupId: input.sandboxGroupId, }, expected: { leaseId: input.expectedLeaseId ?? null, backend: input.expectedBackend ?? null, currentEpoch: input.expectedCurrentEpoch ?? null, lostEpoch: input.expectedLostEpoch ?? null, lostInstanceId: input.expectedLostInstanceId ?? null, refcount: input.expectedRefcount ?? null, providerBackend: input.expectedProviderBackend ?? null, routeKind: input.expectedRouteKind ?? null, routeTargetId: input.expectedRouteTargetId ?? null, routeTargetSupplied: input.expectedRouteTargetId !== undefined, routeEpoch: input.expectedRouteEpoch ?? null, workspaceGeneration: input.expectedWorkspaceGeneration ?? null, workspaceStatus: input.expectedWorkspaceStatus ?? null, restoreStatus: input.expectedRestoreStatus ?? null, restoreFailureCode: input.expectedRestoreFailureCode ?? null, restoreFailureSupplied: input.expectedRestoreFailureCode !== undefined, archiveGeneration: input.expectedArchiveGeneration ?? null, archiveGenerationSupplied: input.expectedArchiveGeneration !== undefined, archiveComplete: input.expectedArchiveComplete ?? null, archiveDescriptorVersion: input.expectedArchiveDescriptorVersion ?? null, archiveRevision: input.expectedArchiveRevision ?? null, archiveObjectKind: input.expectedArchiveObjectKind ?? null, archiveObjectId: input.expectedArchiveObjectId ?? null, descriptorReferenceBytes: input.expectedDescriptorReferenceBytes ?? null, descriptorReferenceSha256: input.expectedDescriptorReferenceSha256 ?? null, referenceBytes: input.expectedReferenceBytes ?? null, referenceSha256: input.expectedReferenceSha256 ?? null, treeFingerprintAlgorithm: input.expectedTreeFingerprintAlgorithm ?? null, treeFingerprintSha256: input.expectedTreeFingerprintSha256 ?? null, treeEntryCount: input.expectedTreeEntryCount ?? null, treeFileCount: input.expectedTreeFileCount ?? null, totalFileBytes: input.expectedTotalFileBytes ?? null, archiveCapturedAt: input.expectedArchiveCapturedAt ?? null, archiveVerificationState: input.expectedArchiveVerificationState ?? null, archiveVerifiedRevision: input.expectedArchiveVerifiedRevision ?? null, archiveVerifiedRevisionSupplied: input.expectedArchiveVerifiedRevision !== undefined, archiveVerifiedAt: input.expectedArchiveVerifiedAt ?? null, archiveVerifiedAtSupplied: input.expectedArchiveVerifiedAt !== undefined, }, session: session ? { id: session.id, status: session.status, sandboxGroupId: session.sandbox_group_id, activeSandboxId: session.active_sandbox_id, activeEpoch: Number(session.active_epoch), } : null, lease: lease ? { id: lease.id, liveness: lease.liveness, instanceId: lease.instanceId, backend: lease.backend, leaseEpoch: lease.leaseEpoch, workspaceGeneration: lease.workspaceGeneration, archiveGeneration: lease.archiveGeneration, archiveComplete: lease.archiveComplete, refcount: lease.refcount, turnHolders: lease.turnHolders, viewerHolders: lease.viewerHolders, recoveryProviderStatus: lease.recovery.provider.status, recoveryProviderInstanceId: lease.recovery.provider.instanceId, workspaceStatus: lease.recovery.workspace.status, restoreStatus: lease.recovery.restore.status, restoreFailureCode: lease.recovery.restore.failureCode ?? null, } : null, archive: { status: recovery?.archive.status ?? "none", descriptorVersion: descriptor?.version ?? null, revision: descriptor?.revision ?? null, generation: archiveGeneration, objectKind: archiveObject?.kind ?? null, objectId: archiveObject?.id ?? null, descriptorReferenceBytes: descriptor?.archiveBytes ?? null, descriptorReferenceSha256: descriptor?.archiveSha256 ?? null, referenceBytes, referenceSha256, referenceVerified, treeFingerprintAlgorithm: treeDescriptor?.workspace.algorithm ?? null, treeFingerprintSha256: treeDescriptor?.workspace.sha256 ?? null, entryCount: treeDescriptor?.workspace.entryCount ?? null, fileCount: treeDescriptor?.workspace.fileCount ?? null, totalFileBytes: treeDescriptor?.workspace.totalFileBytes ?? null, complete: archiveComplete, verificationState: archiveVerificationMatches ? "verified" : "unverified", capturedAt: descriptor?.capturedAt ?? null, verifiedRevision, verifiedAt: archiveVerificationMatches ? recovery!.workspace.verifiedAt : null, providerObservation: { providerBackend: input.providerObject.providerBackend, objectKind: input.providerObject.objectKind, objectId: input.providerObject.objectId, status: input.providerObject.status, observedAt: input.providerObject.observedAt, }, }, active: { exactProcesses: activeExactProcesses.length, exactAdmissions: activeExactAdmissions.length, exactPtys: activeExactPtys.length, exactProcessHolders: exactProcessHolders.length, unmatchedProcesses: unmatchedProcesses.length, unmatchedAdmissions: unmatchedAdmissions.length, unmatchedPtys: unmatchedPtys.length, unmatchedProcessHolders: unmatchedProcessHolders.length, directHolders: directHolders.length, possibleWriterTurnHolders: possibleWriterTurnHolders.length, unknownTurnHolderLinks: turnHoldersWithUnknownAttempt.length, unsettledInterruptions: unsettledInterruptions.length, turnHolders, viewerHolders, inventoryComplete: rows.inventoryComplete, }, identities: { processes: rows.processes, admissions: rows.admissions, ptys: rows.ptys, holders: rows.holders, interruptions: rows.interruptions, }, settlement: { processesLost: activeExactProcesses.length, admissionsRejected: activeExactAdmissions.length, ptysClosed: activeExactPtys.length, processHoldersDeleted: exactProcessHolders.length, }, blockerSetHash, blockers, }; } async function readColdLostDatabasePostureTx(tx: Database): Promise { const postureRows = await tx.execute<{ role: string; role_superuser: boolean; role_bypass_rls: boolean; transaction_read_only: string; row_security: string; account_id: string; workspace_id: string; force_rls: boolean; }>(sql` select current_user as role, coalesce((select rolsuper from pg_roles where rolname = current_user), true) as role_superuser, coalesce((select rolbypassrls from pg_roles where rolname = current_user), true) as role_bypass_rls, current_setting('transaction_read_only') as transaction_read_only, current_setting('row_security') as row_security, current_setting('opengeni.account_id', true) as account_id, current_setting('opengeni.workspace_id', true) as workspace_id, coalesce(( select bool_and(c.relrowsecurity and c.relforcerowsecurity) from pg_class c where c.oid = any(array[ 'sessions'::regclass, 'session_turns'::regclass, 'session_turn_attempts'::regclass, 'session_attempt_interruptions'::regclass, 'sandbox_leases'::regclass, 'sandbox_lease_holders'::regclass, 'sandbox_retained_processes'::regclass, 'sandbox_workspace_mutation_admissions'::regclass, 'sandbox_pty_sessions'::regclass ]) ), false) as force_rls `); const posture = postureRows[0]; if (!posture) throw new Error("Cold lost-provider preview could not read database posture"); return { role: posture.role, roleSuperuser: posture.role_superuser, roleBypassRls: posture.role_bypass_rls, transactionReadOnly: posture.transaction_read_only === "on", rowSecurity: posture.row_security === "on", forceRls: posture.force_rls, accountId: posture.account_id, workspaceId: posture.workspace_id, }; } /** * Build the official structurally non-mutating recovery preview. The transaction * is repeatable-read/read-only, RLS context is verified on the same backend, and * no row lock, provider operation, or state transition is performed. */ export async function previewColdLostLeaseInstanceBlockers( db: Database, input: PreviewColdLostLeaseInstanceBlockersInput, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const posture = await readColdLostDatabasePostureTx(scopedDb); const rows = await readColdLostSnapshotRowsTx(scopedDb, input); return evaluateColdLostSnapshot(input, rows, posture); }, { isolationLevel: "repeatable read", accessMode: "read only" }, ); } export type MarkWarmLeaseInstanceLostResult = | { status: "marked"; lease: LeaseSnapshot; settlement: LostProviderWorkspaceSettlement; /** Terminal events of linked background commands, already durable in * this commit; present only when a command settled. */ backgroundCommandEvents?: SessionEvent[]; /** Committed wakes of sessions waiting on those commands; signal them * after commit (see `signalBackgroundCommandWakes`). */ backgroundCommandWakes?: SessionWorkflowWake[]; } | { status: "stale"; lease: LeaseSnapshot | null }; const LOST_PROVIDER_PROCESS_REASON = "provider_instance_lost"; /** Lock the exact provider-owned blocker set before taking the lease row. Normal * retained-process settlement locks process -> admission -> lease, so provider * loss must not hold the lease while waiting for one of those rows. The lease * tuple is revalidated under FOR UPDATE after these locks are acquired. */ async function lockExactLostProviderWorkspaceBlockersTx( tx: Database, input: LostProviderBlockerScope, ): Promise { await tx.execute(sql` select id from sandbox_retained_processes where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${input.leaseId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.lostEpoch} and provider_backend = ${input.lostBackend} and provider_instance_id = ${input.lostInstanceId} and state = 'active' order by id for update `); await tx.execute(sql` select id from sandbox_workspace_mutation_admissions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${input.leaseId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.lostEpoch} and provider_backend = ${input.lostBackend} and provider_instance_id = ${input.lostInstanceId} and settled_at is null order by id for update `); await tx.execute(sql` select id from sandbox_pty_sessions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and lease_id = ${input.leaseId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.lostEpoch} and provider_backend = ${input.lostBackend} and provider_instance_id = ${input.lostInstanceId} and status = 'open' order by id for update `); } type LostProviderBlockerScope = { accountId: string; workspaceId: string; leaseId: string; sandboxGroupId: string; lostEpoch: number; lostBackend: string; lostInstanceId: string; }; /** Take the session-event write prefix (workspace control share, workspace, * sessions, cursors) for linked background commands and attempt owners in the * exact lost-provider scope. Call it before the * process/admission/PTY/lease locks so terminal command delivery keeps the * canonical control -> session -> process -> admission -> lease order. */ async function linkedLostProviderCommandSessionIdsTx( tx: Database, input: LostProviderBlockerScope, ): Promise { const sessions = await rawRows<{ session_id: string }>( tx, sql` select distinct session_id from ( select command.session_id from session_background_commands command join sandbox_retained_processes process on process.id = command.retained_process_id and process.workspace_id = command.workspace_id and process.session_id = command.session_id where process.account_id = ${input.accountId} and process.workspace_id = ${input.workspaceId} and process.lease_id = ${input.leaseId} and process.sandbox_group_id = ${input.sandboxGroupId} and process.lease_epoch = ${input.lostEpoch} and process.provider_backend = ${input.lostBackend} and process.provider_instance_id = ${input.lostInstanceId} and process.state = 'active' and command.state in ('running', 'stopping') union select process.session_id from sandbox_retained_processes process join session_turn_attempts attempt on attempt.id = process.owner_attempt_id and attempt.workspace_id = process.workspace_id and attempt.session_id = process.session_id where process.account_id = ${input.accountId} and process.workspace_id = ${input.workspaceId} and process.lease_id = ${input.leaseId} and process.sandbox_group_id = ${input.sandboxGroupId} and process.lease_epoch = ${input.lostEpoch} and process.provider_backend = ${input.lostBackend} and process.provider_instance_id = ${input.lostInstanceId} and process.state = 'active' union -- A closed, unquiesced owner of an open request on the lost box is woken -- by the settlement; lock its session in the canonical prefix first. A -- process actor's request (e.g. supervised stdin) pins the attempt that -- owns its process. select attempt.session_id from sandbox_workspace_mutation_admissions admission left join sandbox_retained_processes actor_process on admission.actor_kind = 'process' and actor_process.id = admission.actor_id and actor_process.workspace_id = admission.workspace_id join session_turn_attempts attempt on attempt.id = coalesce(admission.attempt_id, actor_process.owner_attempt_id) and attempt.workspace_id = admission.workspace_id where admission.account_id = ${input.accountId} and admission.workspace_id = ${input.workspaceId} and admission.lease_id = ${input.leaseId} and admission.sandbox_group_id = ${input.sandboxGroupId} and admission.lease_epoch = ${input.lostEpoch} and admission.provider_backend = ${input.lostBackend} and admission.provider_instance_id = ${input.lostInstanceId} and admission.settled_at is null and attempt.state = 'closed' and attempt.quiesced_at is null ) owners order by session_id `, ); return sessions.map((row) => row.session_id); } async function lockLostProviderCommandSessionsTx( tx: Database, input: LostProviderBlockerScope, alsoLockSessionIds: readonly string[] = [], ): Promise> { const sessionIds = await linkedLostProviderCommandSessionIdsTx(tx, input); // One call, so every session row is taken in the same sorted order. const toLock = [...new Set([...sessionIds, ...alsoLockSessionIds])]; if (toLock.length) { await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "share", sessionIds: toLock, }); } return new Set(sessionIds); } class LostProviderCommandSessionsChangedError extends Error { readonly name = "LostProviderCommandSessionsChangedError"; } /** Re-read the linked sessions once every blocker and the lease are locked. * A command adopted in the gap before the process locks would otherwise make * delivery lock its session after process/admission/lease rows, inverting the * canonical order; abort that transaction and retry instead. */ async function assertLostProviderCommandSessionsLockedTx( tx: Database, input: LostProviderBlockerScope, locked: ReadonlySet, ): Promise { const current = await linkedLostProviderCommandSessionIdsTx(tx, input); if (current.some((sessionId) => !locked.has(sessionId))) { throw new LostProviderCommandSessionsChangedError( "A background command was linked to the lost provider while its sessions were being locked", ); } } async function withLostProviderCommandSessionRetry(run: () => Promise): Promise { for (let attempt = 1; ; attempt += 1) { try { return await run(); } catch (error) { if (!(error instanceof LostProviderCommandSessionsChangedError) || attempt >= 3) throw error; } } } async function settleExactLostProviderWorkspaceBlockersTx( tx: Database, input: LostProviderBlockerScope, options: { /** Enrolled legacy commands that containment stopped after a verified * checkpoint settle with this truthful reason instead of plain loss. */ containment?: { processIds: readonly string[]; reason: string }; /** Append each linked command's terminal event and agent input in this * transaction, like ordinary exit/loss settlement. Requires a session * activity scope and lockLostProviderCommandSessionsTx beforehand. */ deliverCommandResults?: { activityTx: SessionActivityDatabase; idleContainmentMinutes: number | null; events: SessionEvent[]; /** Receives the committed wake of each session waiting on a command. */ wakes?: SessionWorkflowWake[]; }; } = {}, ): Promise { const containedIds = options.containment?.processIds ?? []; // Only callers that locked and revalidated this exact provider tuple reach // here. Migration0495 independently checks the cold missing-provider outcome // at commit. This is loss classification, not a supervision/EOF receipt. const [priorLossBinding] = await tx.execute<{ value: string | null }>(sql` select current_setting('opengeni.supervised_provider_loss_binding', true) as value `); await tx.execute(sql` select set_config('opengeni.supervised_provider_loss_binding', ${JSON.stringify(input)}, true) `); const lostProcesses = await tx .update(schema.sandboxRetainedProcesses) .set({ state: "lost", exitCode: null, settlementReason: options.containment && containedIds.length ? sql`case when ${schema.sandboxRetainedProcesses.id} = any(${`{${containedIds.join(",")}}`}::uuid[]) then ${options.containment.reason} else ${LOST_PROVIDER_PROCESS_REASON} end` : LOST_PROVIDER_PROCESS_REASON, settledAt: new Date(), }) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.leaseId, input.leaseId), eq(schema.sandboxRetainedProcesses.sandboxGroupId, input.sandboxGroupId), eq(schema.sandboxRetainedProcesses.leaseEpoch, input.lostEpoch), eq(schema.sandboxRetainedProcesses.providerBackend, input.lostBackend), eq(schema.sandboxRetainedProcesses.providerInstanceId, input.lostInstanceId), eq(schema.sandboxRetainedProcesses.state, "active"), ), ) .returning({ id: schema.sandboxRetainedProcesses.id, holderId: schema.sandboxRetainedProcesses.holderId, sessionId: schema.sandboxRetainedProcesses.sessionId, settlementReason: schema.sandboxRetainedProcesses.settlementReason, }); await tx.execute(sql` select set_config('opengeni.supervised_provider_loss_binding', ${priorLossBinding?.value ?? ""}, true) `); const rejectedAdmissions = await tx .update(schema.sandboxWorkspaceMutationAdmissions) .set({ providerOutcome: "rejected", settledAt: new Date() }) .where( and( eq(schema.sandboxWorkspaceMutationAdmissions.accountId, input.accountId), eq(schema.sandboxWorkspaceMutationAdmissions.workspaceId, input.workspaceId), eq(schema.sandboxWorkspaceMutationAdmissions.leaseId, input.leaseId), eq(schema.sandboxWorkspaceMutationAdmissions.sandboxGroupId, input.sandboxGroupId), eq(schema.sandboxWorkspaceMutationAdmissions.leaseEpoch, input.lostEpoch), eq(schema.sandboxWorkspaceMutationAdmissions.providerBackend, input.lostBackend), eq(schema.sandboxWorkspaceMutationAdmissions.providerInstanceId, input.lostInstanceId), isNull(schema.sandboxWorkspaceMutationAdmissions.settledAt), ), ) .returning({ id: schema.sandboxWorkspaceMutationAdmissions.id }); const closedPtys = await tx .update(schema.sandboxPtySessions) .set({ status: "closed", closedAt: new Date() }) .where( and( eq(schema.sandboxPtySessions.accountId, input.accountId), eq(schema.sandboxPtySessions.workspaceId, input.workspaceId), eq(schema.sandboxPtySessions.leaseId, input.leaseId), eq(schema.sandboxPtySessions.sandboxGroupId, input.sandboxGroupId), eq(schema.sandboxPtySessions.leaseEpoch, input.lostEpoch), eq(schema.sandboxPtySessions.providerBackend, input.lostBackend), eq(schema.sandboxPtySessions.providerInstanceId, input.lostInstanceId), eq(schema.sandboxPtySessions.status, "open"), ), ) .returning({ id: schema.sandboxPtySessions.id }); const deletedHolders = lostProcesses.length === 0 ? [] : await tx .delete(schema.sandboxLeaseHolders) .where( and( eq(schema.sandboxLeaseHolders.accountId, input.accountId), eq(schema.sandboxLeaseHolders.workspaceId, input.workspaceId), eq(schema.sandboxLeaseHolders.leaseId, input.leaseId), eq(schema.sandboxLeaseHolders.kind, "process"), inArray( schema.sandboxLeaseHolders.holderId, lostProcesses.map((process) => process.holderId), ), ), ) .returning({ holderId: schema.sandboxLeaseHolders.holderId }); await tx.execute(sql` update sandbox_leases as lease set refcount = counts.total, turn_holders = counts.turns, viewer_holders = counts.viewers, updated_at = now() from ( select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers from sandbox_lease_holders where lease_id = ${input.leaseId} ) as counts where lease.id = ${input.leaseId} `); const delivery = options.deliverCommandResults; if (delivery && lostProcesses.length) { // The retained-process trigger already moved each linked command row to // this terminal state. Append the same event/input/wake that ordinary // exit/loss settlement commits, in this transaction and in stable order. const linked = await rawRows<{ session_id: string; retained_process_id: string }>( tx, sql` select session_id, retained_process_id from session_background_commands where workspace_id = ${input.workspaceId} and retained_process_id = any(${`{${lostProcesses.map((p) => p.id).join(",")}}`}::uuid[]) order by session_id, retained_process_id `, ); for (const command of linked) { const process = lostProcesses.find((p) => p.id === command.retained_process_id); if (!process) continue; const mutation = backgroundCommandTerminalMutation({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: command.session_id, idleContainmentMinutes: delivery.idleContainmentMinutes, }); await settleSessionBackgroundCommandForRetainedProcessInTransaction( delivery.activityTx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: command.session_id, retainedProcessId: process.id, outcome: "lost", exitCode: null, reason: process.settlementReason ?? LOST_PROVIDER_PROCESS_REASON, }, mutation, ); delivery.events.push(...mutation.events); delivery.wakes?.push(...mutation.wakes); } } if (lostProcesses.length) { // The session prefix was locked before blockers and revalidated afterward. // Unadopted writers have no background-command delivery to wake their owner; // persist that obligation atomically with physical provider settlement. const owners = await rawRows<{ session_id: string; temporal_workflow_id: string }>( tx, sql` select distinct attempt.session_id, attempt.temporal_workflow_id from session_turn_attempts attempt join sandbox_retained_processes process on process.owner_attempt_id = attempt.id and process.workspace_id = attempt.workspace_id and process.session_id = attempt.session_id where attempt.workspace_id = ${input.workspaceId} and attempt.account_id = ${input.accountId} and attempt.state = 'closed' and attempt.quiesced_at is null and attempt.temporal_workflow_id is not null and process.id = any(${`{${lostProcesses.map((p) => p.id).join(",")}}`}::uuid[]) order by attempt.session_id, attempt.temporal_workflow_id `, ); for (const owner of owners) { await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: owner.session_id, temporalWorkflowId: owner.temporal_workflow_id, reason: "attempt_writer_provider_settled", }); } } if (rejectedAdmissions.length) { // A rejected request whose closed owner still awaits its quiescence receipt // (a crashed worker's orphan, or a process actor's request whose process // owner closed) has no process delivery to wake that owner either; the // receipt reconciliation runs from this durable wake. const owners = await rawRows<{ session_id: string; temporal_workflow_id: string }>( tx, sql` select distinct attempt.session_id, attempt.temporal_workflow_id from sandbox_workspace_mutation_admissions admission left join sandbox_retained_processes actor_process on admission.actor_kind = 'process' and actor_process.id = admission.actor_id and actor_process.workspace_id = admission.workspace_id join session_turn_attempts attempt on attempt.id = coalesce(admission.attempt_id, actor_process.owner_attempt_id) and attempt.workspace_id = admission.workspace_id where attempt.workspace_id = ${input.workspaceId} and attempt.account_id = ${input.accountId} and attempt.state = 'closed' and attempt.quiesced_at is null and attempt.temporal_workflow_id is not null and admission.id = any(${`{${rejectedAdmissions.map((a) => a.id).join(",")}}`}::uuid[]) order by attempt.session_id, attempt.temporal_workflow_id `, ); for (const owner of owners) { await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: owner.session_id, temporalWorkflowId: owner.temporal_workflow_id, reason: "attempt_writer_provider_settled", }); } } return { processesLost: lostProcesses.length, admissionsRejected: rejectedAdmissions.length, ptysClosed: closedPtys.length, processHoldersDeleted: deletedHolders.length, }; } /** * Atomically retire one exact warm provider instance after a resume-only caller * receives a provider NotFound. The epoch + instance predicates are the * ownership fence: concurrent attached callers may all observe the same missing * box, but only the first one transitions the lease to cold and advances its * epoch. The next ordinary acquire elects one cold->warming spawner. * * Logical turn/viewer interest remains intact, while holders for active * processes that physically belonged to the lost provider are removed with * their terminal loss proof. A persisted workspace archive is reduced to the * same minimal cold envelope used by the drain/failure paths, so the elected * replacement can hydrate it without carrying the dead box id. */ export async function markWarmLeaseInstanceLost( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; /** Optional for legacy callers; new provider observers should bind backend too. */ expectedBackend?: string; /** Bounded classifier output only; never raw provider error text. */ diagnostic?: string; /** The backend's bound on how long the lost box could still run (its hard * lifetime or unrenewed TTL), when it has one. Recorded as death proof. */ providerMaxRemainingLifetimeMs?: number | null; }, ): Promise { const backgroundCommandEvents: SessionEvent[] = []; const backgroundCommandWakes: SessionWorkflowWake[] = []; // Settling a linked command appends its terminal event and agent input, so // the loss commit runs inside the session activity gate. const result = await withLostProviderCommandSessionRetry(async () => { backgroundCommandEvents.length = 0; backgroundCommandWakes.length = 0; return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const observedRows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} `); const observed = observedRows[0]; if ( !observed || observed.liveness !== "warm" || Number(observed.lease_epoch) !== input.expectedEpoch || observed.instance_id !== input.expectedInstanceId || (input.expectedBackend !== undefined && observed.backend !== input.expectedBackend) ) { return { status: "stale" as const, lease: observed ? mapLeaseRow(observed) : null, }; } const blockerScope = { accountId: input.accountId, workspaceId: input.workspaceId, leaseId: observed.id, sandboxGroupId: input.sandboxGroupId, lostEpoch: input.expectedEpoch, lostBackend: observed.backend, lostInstanceId: input.expectedInstanceId, }; const lockedCommandSessions = await lockLostProviderCommandSessionsTx(tx, blockerScope); await lockExactLostProviderWorkspaceBlockersTx(tx, blockerScope); const currentRows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const current = currentRows[0]; if ( !current || current.id !== observed.id || current.liveness !== "warm" || Number(current.lease_epoch) !== input.expectedEpoch || current.instance_id !== input.expectedInstanceId || current.backend !== observed.backend ) { return { status: "stale" as const, lease: current ? mapLeaseRow(current) : null, }; } await assertLostProviderCommandSessionsLockedTx(tx, blockerScope, lockedCommandSessions); const settlement = await settleExactLostProviderWorkspaceBlockersTx(tx, blockerScope, { deliverCommandResults: { activityTx: tx, idleContainmentMinutes: null, events: backgroundCommandEvents, wakes: backgroundCommandWakes, }, }); const observedAt = new Date().toISOString(); const before = recoveryStateFromLeaseRow(current); const continuity = dockerContinuityRecoveryFromLeaseRow(current, input.expectedInstanceId); const archiveStatus = before.archive.status; const archiveComplete = hasCompleteWorkspaceArchive(current); const restoreStatus: SandboxRestoreStatus = continuity || (archiveStatus === "available" && archiveComplete) ? "pending" : archiveStatus === "available" || archiveStatus === "unverified" || archiveStatus === "invalid" ? "degraded" : "unrecoverable"; const workspaceStatus: SandboxWorkspaceReadiness = restoreStatus === "pending" ? "not_ready" : restoreStatus === "degraded" ? "degraded" : "unrecoverable"; const recovery: SandboxRecoveryState = { provider: { status: "missing", instanceId: current.instance_id, observedAt, ...(input.diagnostic ? { diagnostic: input.diagnostic.slice(0, 160) } : {}), }, archive: before.archive, restore: { status: restoreStatus, rematerializationId: null, selectedRevision: restoreStatus === "pending" ? (before.archive.current?.revision ?? null) : null, startedAt: null, completedAt: null, ...(restoreStatus === "degraded" ? { failureCode: archiveStatus === "available" ? "archive_generation_mismatch" : "archive_unverified", retryable: false, } : restoreStatus === "unrecoverable" ? { failureCode: "archive_unavailable", retryable: false } : {}), }, workspace: { status: workspaceStatus, verifiedRevision: null, verifiedAt: null, }, ...(continuity ? { continuity } : {}), }; const coldResumeState = recoveryResumeState( current, recovery, providerLossRecordForLostRow( current, "warm_resume", observedAt, input.providerMaxRemainingLifetimeMs, ), ); const coldResumeStateJson = JSON.stringify(coldResumeState); const updatedRows = await tx.execute(sql` update sandbox_leases set liveness = 'cold', instance_id = null, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, resume_state = ${coldResumeStateJson}::jsonb, resume_backend_id = coalesce(resume_backend_id, backend), provider_created_at = null, provider_deadline_at = null, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, updated_at = now() where id = ${current.id} returning * `); const updated = updatedRows[0]; if (!updated) { throw new Error(`Warm sandbox lease vanished while retiring instance ${current.id}`); } if (updated && current.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, input); } return { status: "marked" as const, lease: mapLeaseRow(updated), settlement, }; }, ); }); return result.status === "marked" && backgroundCommandEvents.length ? { ...result, backgroundCommandEvents, ...(backgroundCommandWakes.length ? { backgroundCommandWakes } : {}), } : result; } export type ReconcileColdLostLeaseInstanceBlockersResult = | { status: "reconciled"; lease: LeaseSnapshot; settlement: LostProviderWorkspaceSettlement; } | { status: "blocked"; preview: ColdLostReconciliationPreview } | { status: "stale"; preview: ColdLostReconciliationPreview }; /** * Settle blockers left by a provider-loss transition that predates exact loss * cleanup. This is deliberately narrower than markWarmLeaseInstanceLost: it * requires the already-cold lease to match the full operator-observed * generation/archive tuple, the current epoch to be exactly lostEpoch + 1, and * recovery truth to name the same missing provider. It never advances an epoch, * rematerializes a provider, or changes archive/recovery completeness. */ export async function reconcileColdLostLeaseInstanceBlockers( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; sandboxGroupId: string; expectedLeaseId: string; expectedBackend: string; expectedCurrentEpoch: number; expectedLostEpoch: number; expectedLostInstanceId: string; expectedRefcount: number; expectedProviderBackend: string; expectedRouteKind: "home" | "active"; expectedRouteTargetId: string | null; expectedRouteEpoch: number; expectedWorkspaceGeneration: number; expectedWorkspaceStatus: SandboxWorkspaceReadiness; expectedRestoreStatus: SandboxRestoreStatus; expectedRestoreFailureCode: string | null; expectedArchiveGeneration: number | null; expectedArchiveComplete: boolean; expectedArchiveDescriptorVersion: 1; expectedArchiveRevision: string; expectedArchiveObjectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; expectedArchiveObjectId: string; expectedDescriptorReferenceBytes: number; expectedDescriptorReferenceSha256: string; expectedReferenceBytes: number; expectedReferenceSha256: string; expectedTreeFingerprintAlgorithm: "sha256"; expectedTreeFingerprintSha256: string; expectedTreeEntryCount: number; expectedTreeFileCount: number; expectedTotalFileBytes: number; expectedArchiveCapturedAt: string; expectedArchiveVerificationState: "verified" | "unverified"; expectedArchiveVerifiedRevision: string | null; expectedArchiveVerifiedAt: string | null; providerObject: ColdLostProviderObjectObservation; expectedPreviewId: string; }, ): Promise { if ( !Number.isSafeInteger(input.expectedCurrentEpoch) || !Number.isSafeInteger(input.expectedLostEpoch) || input.expectedCurrentEpoch !== input.expectedLostEpoch + 1 ) { throw new Error("Cold lost-provider reconciliation requires currentEpoch = lostEpoch + 1"); } if (!/^clrp1:[a-f0-9]{64}$/.test(input.expectedPreviewId)) { throw new Error("Cold lost-provider reconciliation requires an exact clrp1 preview id"); } const previewInput: PreviewColdLostLeaseInstanceBlockersInput = { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sandboxGroupId: input.sandboxGroupId, expectedLeaseId: input.expectedLeaseId, expectedBackend: input.expectedBackend, expectedCurrentEpoch: input.expectedCurrentEpoch, expectedLostEpoch: input.expectedLostEpoch, expectedLostInstanceId: input.expectedLostInstanceId, expectedRefcount: input.expectedRefcount, expectedProviderBackend: input.expectedProviderBackend, expectedRouteKind: input.expectedRouteKind, expectedRouteTargetId: input.expectedRouteTargetId, expectedRouteEpoch: input.expectedRouteEpoch, expectedWorkspaceGeneration: input.expectedWorkspaceGeneration, expectedWorkspaceStatus: input.expectedWorkspaceStatus, expectedRestoreStatus: input.expectedRestoreStatus, expectedRestoreFailureCode: input.expectedRestoreFailureCode, expectedArchiveGeneration: input.expectedArchiveGeneration, expectedArchiveComplete: input.expectedArchiveComplete, expectedArchiveDescriptorVersion: input.expectedArchiveDescriptorVersion, expectedArchiveRevision: input.expectedArchiveRevision, expectedArchiveObjectKind: input.expectedArchiveObjectKind, expectedArchiveObjectId: input.expectedArchiveObjectId, expectedDescriptorReferenceBytes: input.expectedDescriptorReferenceBytes, expectedDescriptorReferenceSha256: input.expectedDescriptorReferenceSha256, expectedReferenceBytes: input.expectedReferenceBytes, expectedReferenceSha256: input.expectedReferenceSha256, expectedTreeFingerprintAlgorithm: input.expectedTreeFingerprintAlgorithm, expectedTreeFingerprintSha256: input.expectedTreeFingerprintSha256, expectedTreeEntryCount: input.expectedTreeEntryCount, expectedTreeFileCount: input.expectedTreeFileCount, expectedTotalFileBytes: input.expectedTotalFileBytes, expectedArchiveCapturedAt: input.expectedArchiveCapturedAt, expectedArchiveVerificationState: input.expectedArchiveVerificationState, expectedArchiveVerifiedRevision: input.expectedArchiveVerifiedRevision, expectedArchiveVerifiedAt: input.expectedArchiveVerifiedAt, providerObject: input.providerObject, }; // Settling a linked command appends its terminal event and agent input, as // the automatic loss transaction does, so apply runs in the activity gate. return await withLostProviderCommandSessionRetry(async () => { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const database = await readColdLostDatabasePostureTx(tx); const observedRows = await readColdLostSnapshotRowsTx(tx, previewInput); const observedPreview = evaluateColdLostSnapshot(previewInput, observedRows, database, { requireReadOnly: false, }); if (observedPreview.previewId !== input.expectedPreviewId) { return { status: "stale" as const, preview: observedPreview }; } if (observedPreview.status !== "eligible") { return { status: "blocked" as const, preview: observedPreview }; } const observed = observedRows.lease!; const blockerScope = { accountId: input.accountId, workspaceId: input.workspaceId, leaseId: observed.id, sandboxGroupId: input.sandboxGroupId, lostEpoch: input.expectedLostEpoch, lostBackend: observed.backend, lostInstanceId: input.expectedLostInstanceId, }; const lockedCommandSessions = await lockLostProviderCommandSessionsTx(tx, blockerScope); await lockExactLostProviderWorkspaceBlockersTx(tx, blockerScope); const currentRows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const current = currentRows[0]; if (!current || current.id !== observed.id) { const currentSnapshotRows = await readColdLostSnapshotRowsTx(tx, previewInput); return { status: "stale" as const, preview: evaluateColdLostSnapshot(previewInput, currentSnapshotRows, database, { requireReadOnly: false, }), }; } const currentSnapshotRows = await readColdLostSnapshotRowsTx(tx, previewInput); const currentPreview = evaluateColdLostSnapshot( previewInput, currentSnapshotRows, database, { requireReadOnly: false }, ); if (currentPreview.previewId !== input.expectedPreviewId) { return { status: "stale" as const, preview: currentPreview }; } if (currentPreview.status !== "eligible") { return { status: "blocked" as const, preview: currentPreview }; } await assertLostProviderCommandSessionsLockedTx(tx, blockerScope, lockedCommandSessions); const settlement = await settleExactLostProviderWorkspaceBlockersTx(tx, blockerScope, { deliverCommandResults: { activityTx: tx, idleContainmentMinutes: null, events: [], }, }); const refreshedRows = await tx.execute(sql` select * from sandbox_leases where id = ${current.id} `); const refreshed = refreshedRows[0]; if (!refreshed) throw new Error("Cold sandbox lease vanished during reconciliation"); return { status: "reconciled" as const, lease: mapLeaseRow(refreshed), settlement, }; }, ); }); } export type EndedEpochBlockerTuple = { accountId: string; workspaceId: string; leaseId: string; sandboxGroupId: string; lostEpoch: number; lostBackend: string; lostInstanceId: string; }; /** * Exact provider tuples (lease, epoch, Modal box) that still hold an open * request although the lease has moved to a later epoch and another box. (An * open PTY always belongs to an active process on its tuple.) Lease succession alone does not prove the old box is gone: the caller * inspects it and settles only on a terminal observation * (`settleEndedEpochWorkspaceBlockers`). Tuples with an active retained * process are left to retained-process reconciliation. */ export async function listEndedEpochWorkspaceBlockers( db: Database, input: { limit: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 500) { throw new Error("Ended-epoch blocker batch is invalid"); } const rows = await rawRows<{ account_id: string; workspace_id: string; lease_id: string; sandbox_group_id: string; lease_epoch: number | string; provider_backend: string; provider_instance_id: string; }>( db, sql`select * from opengeni_private.list_sandbox_ended_epoch_blockers(${input.limit}::integer)`, ); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, leaseId: row.lease_id, sandboxGroupId: row.sandbox_group_id, lostEpoch: Number(row.lease_epoch), lostBackend: row.provider_backend, lostInstanceId: row.provider_instance_id, })); } export type EndedEpochSandboxSetupUncertainty = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; sandboxGroupId: string; box: TerminatedSandboxSetupBox; }; /** * Recovering turns whose sandbox setup start outcome is unknown and whose * every setup request ran on one exact Modal box the lease has since moved * past. Lease succession is not proof the box is gone: the caller inspects the * exact historical sandbox and passes it to `reconcileCompletedSandboxSetup` * only on a terminated observation. Directly paused sessions are not listed. */ export async function listEndedEpochSandboxSetupUncertainties( db: Database, input: { limit: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 500) { throw new Error("Ended-epoch setup batch is invalid"); } const rows = await rawRows<{ account_id: string; workspace_id: string; session_id: string; turn_id: string; attempt_id: string; lease_id: string; sandbox_group_id: string; lease_epoch: number | string; provider_backend: string; provider_instance_id: string; }>( db, sql`select * from opengeni_private.list_sandbox_ended_epoch_setup_uncertainties(${input.limit}::integer)`, ); return rows .filter((row) => row.provider_backend === "modal") .map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, turnId: row.turn_id, attemptId: row.attempt_id, sandboxGroupId: row.sandbox_group_id, box: { leaseId: row.lease_id, leaseEpoch: Number(row.lease_epoch), providerBackend: "modal" as const, providerInstanceId: row.provider_instance_id, }, })); } /** * Settle the open requests and PTYs of one listed tuple after the caller * observed its exact Modal box terminated. Requests are rejected (never * replayed), PTYs closed and closed unquiesced owners woken, through the same * full-identity settlement as provider loss, in the canonical * session -> blocker -> lease lock order. The lease must still be past the * tuple's epoch on another box, and no active retained process may remain on * the tuple (its own reconciliation owns it). Returns null when that no longer * holds. */ export async function settleEndedEpochWorkspaceBlockers( db: Database, tuple: EndedEpochBlockerTuple, ): Promise { const scope: LostProviderBlockerScope = { ...tuple }; return await withLostProviderCommandSessionRetry(async () => { return await withSessionActivityRlsContext( db, { accountId: scope.accountId, workspaceId: scope.workspaceId }, async (tx) => { const lockedCommandSessions = await lockLostProviderCommandSessionsTx(tx, scope); await lockExactLostProviderWorkspaceBlockersTx(tx, scope); const [lease] = await rawRows<{ ended: boolean }>( tx, sql` select ( lease.backend = 'modal' and ${scope.lostBackend} = 'modal' and lease.lease_epoch > ${scope.lostEpoch} and lease.instance_id is distinct from ${scope.lostInstanceId} and not exists ( select 1 from sandbox_retained_processes process where process.lease_id = lease.id and process.lease_epoch = ${scope.lostEpoch} and process.provider_backend = ${scope.lostBackend} and process.provider_instance_id = ${scope.lostInstanceId} and process.state = 'active' ) ) as ended from sandbox_leases lease where lease.id = ${scope.leaseId} and lease.account_id = ${scope.accountId} and lease.workspace_id = ${scope.workspaceId} and lease.sandbox_group_id = ${scope.sandboxGroupId} for update of lease `, ); if (lease?.ended !== true) return null; await assertLostProviderCommandSessionsLockedTx(tx, scope, lockedCommandSessions); return await settleExactLostProviderWorkspaceBlockersTx(tx, scope); }, ); }); } // §4.3 — caught spawn failure: warming -> cold (W3). Holders are intentionally // left intact — the arrival that triggered the spawn still wants a box, so the // next acquireLease re-CAS cold->warming. // // ARCHIVE PRESERVATION (sandbox-file-persistence): when the cold lease that was // selected for re-warm carried a persisted /workspace archive on its resume_state // (an archive-only envelope `{ backendId, sessionState: { workspaceArchive } }` // placed there by a prior drain), the spawn failed BEFORE commitWarmingToWarm, // so the LIVE box envelope was never folded onto resume_state. The warming row // still holds the ORIGINAL archive-only envelope. Nulling resume_state here would // destroy the snapshot the NEXT re-warm must replay — the same file-persistence // bug confirmDrainCold guards against. So we PRESERVE a minimal archive-only // envelope across this failure rollback (same shape confirmDrainCold keeps) and // retain resume_backend_id. No archive on the warming row (a never-persisted cold // start) -> resume_state is nulled as before. export async function failWarmingToCold( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; discardContinuity?: boolean; /** The continuity restore proved the lost workspace itself is gone (see * ProviderDeathProof `workspace_absent`). Implies discardContinuity. */ providerWorkspaceAbsent?: boolean; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row || row.liveness !== "warming" || Number(row.lease_epoch) !== input.expectedEpoch) { return; } if (row.provider_create_attempt?.instanceId === null) return; const current = recoveryStateFromLeaseRow(row); const hasArchive = current.archive.status !== "none"; const continuity = input.discardContinuity || input.providerWorkspaceAbsent ? null : continuityRecoveryFromLeaseRow(row); // A pending empty-workspace decision must survive a failed empty create; // otherwise a null envelope would look like an ordinary new lease. So // must the evidence of a lost workspace: dropping it would let the next // owner publish an empty box as if nothing had ever been there. const freshPending = pendingFreshWorkspaceRecovery(row.resume_state) !== null; const carriedLoss = providerLossRecord(row.resume_state); const hasRecovery = hasArchive || continuity !== null || freshPending || carriedLoss !== null || input.providerWorkspaceAbsent === true; const archiveComplete = hasCompleteWorkspaceArchive(row); // beginSandboxRematerialization already proved this exact registered // checkpoint unusable in this warming epoch. Keep that terminal truth // instead of re-deriving a pending restore that would fail every turn. const artifactInvalid = hasArchive && current.restore.status === "degraded" && current.restore.failureCode === "checkpoint_artifact_invalid"; const now = new Date().toISOString(); const restoreStatus: SandboxRestoreStatus = artifactInvalid ? "degraded" : continuity || (current.archive.status === "available" && archiveComplete) ? "pending" : hasArchive ? "degraded" : "unrecoverable"; const recovery: SandboxRecoveryState = { // A failed replacement box proves nothing about the lost workspace; // durable loss evidence is carried separately, never minted here. provider: { status: "not_created", instanceId: row.instance_id, observedAt: now, diagnostic: REPLACEMENT_FAILED_DIAGNOSTIC, }, archive: current.archive, restore: { status: restoreStatus, rematerializationId: null, selectedRevision: current.archive.current?.revision ?? null, startedAt: null, completedAt: now, ...(restoreStatus === "degraded" ? { failureCode: artifactInvalid ? "checkpoint_artifact_invalid" : current.archive.status === "available" ? "archive_generation_mismatch" : "archive_unverified", retryable: false, } : restoreStatus === "unrecoverable" ? { failureCode: "archive_unavailable", retryable: false } : {}), }, workspace: { status: restoreStatus === "pending" ? "not_ready" : restoreStatus === "degraded" ? "degraded" : "unrecoverable", verifiedRevision: null, verifiedAt: null, }, ...(continuity ? { continuity } : {}), }; const resumeStateJson = hasRecovery ? JSON.stringify( recoveryResumeState( row, recovery, input.providerWorkspaceAbsent ? providerLossRecordWithWorkspaceAbsent(row, now) : undefined, ), ) : null; await tx.execute(sql` update sandbox_leases set liveness = 'cold', instance_id = null, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, resume_state = ${resumeStateJson}::jsonb, resume_backend_id = case when ${hasRecovery} then coalesce(resume_backend_id, backend) else null end, provider_created_at = null, provider_deadline_at = null, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${input.expectedEpoch} `); if (row.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, input); } }), ); } // Opengeni compute sleeps an idle sandbox itself and keeps its memory // and disk, so a compute lease is never drained for being idle (0859): it stays // warm without holders until its group ends or it rotates. A rotation or an // archive capture still drains it. function computeLeaseStaysWarmWhenIdle( row: Pick, ): boolean { return ( row.backend === "compute" && row.rotation_requested_at === null && row.archive_capture_id === null ); } /** * End the groups of idle compute leases: a warm compute lease with no holder, * hold or capture becomes drainable now, so the reaper deletes its sandbox and * revokes its agent's enrollment. Runs inside a deletion transaction that has * already locked the leases; a lease with any holder is left alone and the * deletion keeps refusing until it drains. * * A browser or desktop an agent opened on the sandbox ends with it. On a * compute sandbox those stay open across idle (the sandbox sleeps with them * in memory), so their holders would otherwise keep a deleted chat's group * forever. Only a lease held by nothing else qualifies, and only while none of * those resources is mid-operation or mid-transition (the deletion retries). */ async function requestComputeGroupEndTx( tx: Database, input: { workspaceId: string; sandboxGroupIds?: readonly string[] }, ): Promise { if (input.sandboxGroupIds && input.sandboxGroupIds.length === 0) return 0; const groupFilter = input.sandboxGroupIds ? sql`and lease.sandbox_group_id in (${sql.join( input.sandboxGroupIds.map((id) => sql`${id}::uuid`), sql`, `, )})` : sql``; // A lease held only by its browsers and desktops, none of them busy. const interactionsOnlyAndSettled = sql` and lease.backend = 'compute' and lease.liveness = 'warm' and lease.turn_holders = 0 and lease.viewer_holders = 0 and lease.reaper_hold_id is null and lease.archive_capture_id is null and exists (select 1 from sandbox_lease_holders h where h.lease_id = lease.id and h.kind = 'interaction') and not exists (select 1 from sandbox_lease_holders h where h.lease_id = lease.id and h.kind <> 'interaction') and not exists ( select 1 from sandbox_lease_holders h join interaction_operations operation on operation.workspace_id = h.workspace_id and operation.state in ('prepared', 'dispatched') and h.holder_id = (case operation.resource_kind when 'browser_session' then 'browser-session:' else 'computer-session:' end) || operation.resource_id::text where h.lease_id = lease.id and h.kind = 'interaction') and not exists ( select 1 from sandbox_lease_holders h join browser_sessions browser on h.holder_id = 'browser-session:' || browser.id::text and browser.workspace_id = h.workspace_id where h.lease_id = lease.id and h.kind = 'interaction' and browser.lifecycle in ('starting', 'suspending', 'restoring', 'ending')) and not exists ( select 1 from sandbox_lease_holders h join computer_sessions computer on h.holder_id = 'computer-session:' || computer.id::text and computer.workspace_id = h.workspace_id where h.lease_id = lease.id and h.kind = 'interaction' and computer.lifecycle in ('starting', 'suspending', 'restoring', 'ending')) `; const candidates = await rawRows<{ id: string }>( tx, sql` select lease.id from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} ${groupFilter} ${interactionsOnlyAndSettled} order by lease.id for update of lease `, ); let interactionLeases: { id: string }[] = []; if (candidates.length > 0) { const candidateIds = sql`(${sql.join( candidates.map((lease) => sql`${lease.id}::uuid`), sql`, `, )})`; // A suspend, resume or end locks its browser or desktop while it prepares. // Lock them all first, then decide again on what is committed now: one // that began a transition while this deletion waited keeps its lease, and // none can begin one before this deletion commits. await tx.execute(sql` select browser.id from browser_sessions browser join sandbox_lease_holders h on h.holder_id = 'browser-session:' || browser.id::text and browser.workspace_id = h.workspace_id where h.lease_id in ${candidateIds} and h.kind = 'interaction' order by browser.id for update of browser `); await tx.execute(sql` select computer.id from computer_sessions computer join sandbox_lease_holders h on h.holder_id = 'computer-session:' || computer.id::text and computer.workspace_id = h.workspace_id where h.lease_id in ${candidateIds} and h.kind = 'interaction' order by computer.id for update of computer `); interactionLeases = await rawRows<{ id: string }>( tx, sql` select lease.id from sandbox_leases lease where lease.id in ${candidateIds} ${interactionsOnlyAndSettled} order by lease.id `, ); } if (interactionLeases.length > 0) { const leaseIds = sql`(${sql.join( interactionLeases.map((lease) => sql`${lease.id}::uuid`), sql`, `, )})`; // The controller dies with the sandbox, so its binding is released too. const browsers = await rawRows<{ id: string }>( tx, sql` update browser_sessions browser set lifecycle = 'lost', controller_id = null, controller_generation = null, placement_instance_id = null, controller_heartbeat_at = null, failure_code = ${COMPUTE_GROUP_ENDED}, updated_at = now() from sandbox_lease_holders h where h.lease_id in ${leaseIds} and h.kind = 'interaction' and h.holder_id = 'browser-session:' || browser.id::text and browser.workspace_id = h.workspace_id and browser.account_id = h.account_id and browser.lifecycle = 'active' returning browser.id `, ); const computers = await rawRows<{ id: string }>( tx, sql` update computer_sessions computer set lifecycle = 'lost', controller_id = null, controller_generation = null, placement_instance_id = null, controller_heartbeat_at = null, failure_code = ${COMPUTE_GROUP_ENDED}, updated_at = now() from sandbox_lease_holders h where h.lease_id in ${leaseIds} and h.kind = 'interaction' and h.holder_id = 'computer-session:' || computer.id::text and computer.workspace_id = h.workspace_id and computer.account_id = h.account_id and computer.lifecycle = 'active' returning computer.id `, ); await tx.execute(sql` delete from sandbox_lease_holders where lease_id in ${leaseIds} and kind = 'interaction' `); await tx.execute(sql` update sandbox_leases set refcount = 0, updated_at = now() where id in ${leaseIds} `); if (browsers.length + computers.length > 0) { await tx.execute(sql` update workspace_interaction_revisions set revision = revision + 1, updated_at = now() where workspace_id = ${input.workspaceId} `); } } const ended = await rawRows<{ id: string }>( tx, sql` update sandbox_leases lease set liveness = 'draining', group_end_requested_at = now(), expires_at = now() - interval '1 millisecond', updated_at = now() where lease.workspace_id = ${input.workspaceId} ${groupFilter} and lease.backend = 'compute' and lease.liveness = 'warm' and lease.refcount = 0 and lease.turn_holders = 0 and lease.viewer_holders = 0 and lease.reaper_hold_id is null and lease.archive_capture_id is null and not exists (select 1 from sandbox_lease_holders h where h.lease_id = lease.id) returning lease.id `, ); return ended.length; } /** * End the compute group of a sandbox every chat of which is archived, as * deleting those chats would: its idle lease drains now, and the reaper * deletes the sandbox and revokes its agent's enrollment without a capture. * A sandbox is kept for the chats that work in it, and an archived chat does * no work. One restored later starts on a new sandbox, as a chat does whose * sandbox was never created. * * A chat is archived with its root (see `sessionArchivedSql`), and one that * still has work under way counts as in use whatever its archive state. A * group no chat names is left alone: it is not a chat's sandbox. True when the * group's end was asked for now; false when a chat still uses the sandbox, * its lease is held, or its end was already asked for. A turn that arrives * before the reaper claims the sandbox keeps it (the lease is re-armed). */ export async function endComputeGroupOfArchivedChats( db: Database, input: { workspaceId: string; sandboxGroupId: string }, bound?: DatabaseWorkBound, ): Promise { const scoped = withinWorkBound(db, bound, (boundedDb, limit) => withWorkspaceRls(boundedDb, input.workspaceId, async (scopedDb) => { // The tenancy lock is held: the statements below get only the time left. await limit(scopedDb); const rows = await rawRows<{ unused: boolean }>( scopedDb, sql`select ${sandboxGroupOnlyOfArchivedChatsSql(input)} as unused`, ); if (rows[0]?.unused !== true) return false; const ended = await requestComputeGroupEndTx(scopedDb, { workspaceId: input.workspaceId, sandboxGroupIds: [input.sandboxGroupId], }); return ended > 0; }), ); try { return await scoped; } catch (error) { // A deleted workspace took its chats and leases with it. if (error instanceof Error && error.message === `Workspace not found: ${input.workspaceId}`) { return false; } throw error; } } /** * Whether a sandbox group is named by chats that are all archived (the rule * of {@link endComputeGroupOfArchivedChats}): each archived by the Archive * action at least {@link ARCHIVED_CHAT_SANDBOX_KEPT_SECONDS} ago or stored by * the idle archiver, a sub-chat with its root, and none with work under way. * False for a group no chat names. Migration 1404's inventory repeats it. */ function sandboxGroupOnlyOfArchivedChatsSql(input: { workspaceId: string; sandboxGroupId: string; }): SQL { const chat = sql`chat`; const root = sql`root`; // Archived for a day: a chat restored sooner, by Undo or later, returns // with the sandbox it had. One stored by the idle archiver (no archived_at) // was unused for weeks already. const archived = (alias: SQL) => sql`(${sessionArchivedSql(alias)} and (${alias}.archived_at is null or ${alias}.archived_at <= now() - make_interval(secs => ${ARCHIVED_CHAT_SANDBOX_KEPT_SECONDS})))`; return sql`(exists ( select 1 from sessions chat where chat.workspace_id = ${input.workspaceId} and chat.sandbox_group_id = ${input.sandboxGroupId} ) and not exists ( select 1 from sessions chat left join sessions root on root.workspace_id = chat.workspace_id and root.id = chat.root_session_id where chat.workspace_id = ${input.workspaceId} and chat.sandbox_group_id = ${input.sandboxGroupId} and ( chat.status in ('queued', 'running', 'requires_action', 'recovering', 'waiting_capacity') or not ( ${archived(chat)} or (root.id is not null and ${archived(root)}) ) ) ))`; } export type ColdSandboxOfArchivedChats = { accountId: string; workspaceId: string; sandboxGroupId: string; }; /** * True while a retained process row over alias `process` must stay: it still * runs, or it is a supervised command whose output has not been captured yet * (the database refuses to delete that evidence). */ function retainedProcessEvidenceKeptSql(process: SQL): SQL { return sql`(${process}.state = 'active' or (${process}.provider_command ? 'supervision' and ${process}.state <> 'lost' and (${process}.supervision_receipt is null or not ${process}.supervision_output_captured)))`; } /** * Delete the settled command records of sandboxes about to be forgotten, so * their lease rows can go. A finished or lost process names the workspace * write that started it, which deleting the lease removes; its background * command and closed terminal name the process in turn. The caller has * already checked that none of them still runs. */ async function deleteSettledRetainedProcessesOfLeasesTx( tx: Database, leaseIds: SQL, ): Promise { const processIds = sql`(select process.id from sandbox_retained_processes process where process.lease_id in ${leaseIds})`; await tx.execute( sql`delete from session_background_commands where retained_process_id in ${processIds}`, ); await tx.execute( sql`delete from sandbox_pty_sessions where retained_process_id in ${processIds}`, ); await tx.execute(sql`delete from sandbox_retained_processes where lease_id in ${leaseIds}`); } /** * Cold sandboxes of a backend other than compute (a stopped Modal or Docker * box with its saved workspace) whose chats are all archived, by * {@link sandboxGroupOnlyOfArchivedChatsSql}'s rule, in key order after * `after`. Routing ids only; {@link forgetColdSandboxOfArchivedChats} checks * again before it forgets one. */ export async function listColdSandboxesOfArchivedChats( db: Database, input: { after?: { workspaceId: string; sandboxGroupId: string } | null; limit: number }, ): Promise { const rows = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; }>( db, sql`select account_id, workspace_id, sandbox_group_id from opengeni_private.cold_sandboxes_of_archived_chats_v1( ${ARCHIVED_CHAT_SANDBOX_KEPT_SECONDS}::integer, ${input.after?.workspaceId ?? null}::uuid, ${input.after?.sandboxGroupId ?? null}::uuid, ${input.limit}::integer )`, ); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, sandboxGroupId: row.sandbox_group_id, })); } /** * Forget the cold sandbox of chats that are all archived, as deleting those * chats does: its lease rows go, with the saved workspace they name. The * checkpoint ledger then deletes the provider snapshots nothing names any * more (`gcSandboxCheckpointArtifacts`), and a chat restored later starts on * a new sandbox, as one does whose sandbox was never created. * * Only a group whose every lease is cold and unheld, with no unsettled * workspace write, running command or open terminal, is forgotten; anything * else (a turn that arrived, a lock another writer holds) leaves it for a * later pass. True when it was forgotten now. */ export async function forgetColdSandboxOfArchivedChats( db: Database, input: ColdSandboxOfArchivedChats, ): Promise { try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const leases = await rawRows<{ id: string; forgettable: boolean }>( tx, sql` select lease.id, (lease.liveness = 'cold' and lease.backend not in ('compute', 'selfhosted') and lease.refcount = 0 and lease.turn_holders = 0 and lease.viewer_holders = 0 and lease.instance_id is null and lease.archive_capture_id is null and lease.reaper_hold_id is null and lease.rotation_requested_at is null and lease.provider_deadline_at is null) as forgettable from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} for update nowait `, ); if (leases.length === 0 || leases.some((lease) => !lease.forgettable)) return false; const leaseIds = sql`(${sql.join( leases.map((lease) => sql`${lease.id}::uuid`), sql`, `, )})`; const [state] = await rawRows<{ unused: boolean; busy: boolean }>( tx, sql`select ${sandboxGroupOnlyOfArchivedChatsSql(input)} as unused, (exists (select 1 from sandbox_lease_holders h where h.lease_id in ${leaseIds}) or exists (select 1 from sandbox_workspace_mutation_admissions admission where admission.lease_id in ${leaseIds} and admission.settled_at is null) or exists (select 1 from sandbox_retained_processes process where process.lease_id in ${leaseIds} and ${retainedProcessEvidenceKeptSql(sql`process`)}) or exists (select 1 from sandbox_retained_processes process join session_background_commands command on command.retained_process_id = process.id where process.lease_id in ${leaseIds} and command.state in ('running', 'stopping')) or exists (select 1 from sandbox_pty_sessions pty where pty.workspace_id = ${input.workspaceId} and pty.sandbox_group_id = ${input.sandboxGroupId} and pty.status = 'open')) as busy`, ); if (state?.unused !== true || state.busy) return false; await deleteSettledRetainedProcessesOfLeasesTx(tx, leaseIds); await tx.execute(sql`delete from sandbox_leases where id in ${leaseIds}`); return true; }), ); } catch (error) { // Another writer holds the lease (55P03), or a row still names it: leave it // for a later pass, as deleting the chats would. let current: unknown = error; for (let depth = 0; depth < 8 && current; depth += 1) { const code = typeof current === "object" && "code" in current ? (current as { code?: unknown }).code : undefined; if (code === "55P03" || code === "23503") return false; current = typeof current === "object" && "cause" in current ? (current as { cause?: unknown }).cause : undefined; } if (error instanceof Error && error.message === `Workspace not found: ${input.workspaceId}`) { return false; } throw error; } } /** The SQL twin of {@link computeLeaseStaysWarmWhenIdle} over alias `L`. */ const COMPUTE_IDLE_DRAINABLE_SQL = sql.raw( "(L.backend <> 'compute' or L.rotation_requested_at is not null or L.archive_capture_id is not null)", ); // §4.4 — idempotent delete-my-row (+ opportunistic warm->draining guarded // refcount=0 AND turn_holders=0, so a paying turn is never drained). export async function releaseLeaseHolder( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; idleGraceMs: number; /** The caller has crossed the non-detachable physical boundary for this * exact turn holder: every admitted attempt-owned workspace writer has * resolved, rejected, or been physically quiesced. A cancellation listener * that merely prevents a holder leak must leave this false. */ workspaceWritersQuiesced?: boolean; /** Keep the holder-set clock when the box stays warm: an idle save's * cleanup is not use, so it must not restart retained-command * containment's idle window. */ preserveHoldersChangedAt?: boolean; }, ): Promise<{ liveness: SandboxLeaseLiveness; refcount: number } | null> { if (input.kind === "process") { throw new Error("Process lease holders require exact retained-process settlement"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // A direct request reaches this release seam only after its provider // operation has resolved, rejected, or been physically quiesced by the // Channel-A cancellation fence. A turn may use the same repair only // after its caller explicitly proves the stronger attempt-writer drain; // the eager cancellation listener drops the holder before that boundary // and therefore must not settle an admission. // // If the ordinary settlement callback failed after the physical // boundary (for example, later finalizer housekeeping threw), leaving a // null-outcome admission here would block archive capture forever after // the request holder leaves. // // Lock admission -> lease, the same suffix used by mutation settlement // and retained-process promotion. Taking the lease first recreates the // admission/lease deadlock this fallback exists to recover. A promoted // process has provider_outcome='retained' and is deliberately untouched; // its non-TTL process holder remains the only settlement authority. const settleAbandonedAdmissions = input.kind === "direct" || (input.kind === "turn" && input.workspaceWritersQuiesced === true); if (settleAbandonedAdmissions) { await tx.execute(sql` select id from sandbox_workspace_mutation_admissions where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and actor_kind = ${input.kind} and holder_kind = ${input.kind} and holder_id = ${input.holderId} and provider_outcome is null and settled_at is null order by id for update `); await tx.execute(sql` update sandbox_workspace_mutation_admissions set provider_outcome = 'rejected', settled_at = now() where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and actor_kind = ${input.kind} and holder_kind = ${input.kind} and holder_id = ${input.holderId} and provider_outcome is null and settled_at is null `); } const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row) return null; // already cold-and-reaped; release is an idempotent no-op const priorHoldersChangedAt = input.preserveHoldersChangedAt ? ( await rawRows<{ at: string }>( tx, sql`select holders_changed_at::text as at from sandbox_leases where id = ${row.id}`, ) )[0]!.at : null; // Cancellation can delete the holder before the shared rig coordinator // catches its abort. That coordinator must then fail closed because its // ordinary settlement requires the holder to remain present. Once the // later proof-bearing release confirms every attempt-owned sandbox // writer is physically quiesced, close the abandoned single-flight too. // Matching the canonical holder to the durable owner attempt keeps this // idempotent and prevents an eager, proof-free release from admitting a // replacement while the old rig command may still be running. if (input.kind === "turn" && input.workspaceWritersQuiesced === true) { await tx.execute(sql` update sandbox_leases set shared_preparation_status = 'failed', shared_preparation_revision = shared_preparation_revision + 1, shared_preparation_settled_at = now(), updated_at = now() where id = ${row.id} and shared_preparation_status = 'running' and lower(${input.holderId}) = 'turn-attempt:' || shared_preparation_owner_attempt_id::text `); } // Idempotent: deleting an already-gone holder affects 0 rows, fine. await tx.execute(sql` delete from sandbox_lease_holders where lease_id = ${row.id} and kind = ${input.kind} and holder_id = ${input.holderId} `); const counts = await tx.execute<{ total: number; turns: number; viewers: number; }>(sql` select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers from sandbox_lease_holders where lease_id = ${row.id} `); const c = counts[0]!; // warm + dropped to 0 (AND no turn holders) -> draining, stamp grace deadline. // Release during warming decrements only, NEVER touches liveness (the // spawner owns warming->warm and re-checks refcount after committing). const enterDraining = row.liveness === "warm" && c.total === 0 && c.turns === 0 && !computeLeaseStaysWarmWhenIdle(row); // A capture claim is already the durable teardown fence. Once its final // holder leaves, waiting through the ordinary idle grace only creates an // avoidable availability outage; dispatch recovery on the next sweep. const drainGraceMs = row.rotation_requested_at || row.archive_capture_id ? 0 : input.idleGraceMs; const updated = await tx.execute(sql` update sandbox_leases set refcount = ${c.total}, turn_holders = ${c.turns}, viewer_holders = ${c.viewers}, ${ enterDraining ? sql`liveness = 'draining', expires_at = now() + (${String(drainGraceMs)} || ' milliseconds')::interval,` : sql`` } updated_at = now() where id = ${row.id} returning * `); if (input.preserveHoldersChangedAt && !enterDraining) { // A separate statement: the counter trigger re-stamps the clock. await tx.execute(sql` update sandbox_leases set holders_changed_at = ${priorHoldersChangedAt}::timestamptz where id = ${row.id} `); } return { liveness: updated[0]!.liveness, refcount: Number(c.total) }; }), ); } // Canonical production turn holders carry the exact UUID attempt identity. // Their in-memory timer is never authority by itself: the attempt and turn must // still form the current active-writer chain. The non-UUID branch exists only // for old synthetic fixtures/legacy diagnostic rows; runtime construction uses // `turn-attempt:` exclusively, and migration 0138 removes canonical // orphan rows during the maintenance cutover. const LIVE_CANONICAL_TURN_HOLDER_PREDICATE = sql` ( holder.kind <> 'turn' or holder.holder_id !~* '^turn-attempt:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' or exists ( select 1 from session_turn_attempts attempt join session_turns turn on turn.account_id = attempt.account_id and turn.workspace_id = attempt.workspace_id and turn.session_id = attempt.session_id and turn.id = attempt.turn_id and turn.execution_generation = attempt.execution_generation and turn.active_attempt_id = attempt.id where holder.holder_id = ('turn-attempt:' || attempt.id::text) and attempt.account_id = holder.account_id and attempt.workspace_id = holder.workspace_id and attempt.session_id = holder.subject_id and attempt.state in ('claimed', 'running') ) ) `; async function touchLiveLeaseHolder( tx: Database, input: { workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; /** Viewer holders only: how long ago the viewer last saw real user * interaction. Moves `last_interaction_at` forward, never back. */ interactionAgeMs?: number | null | undefined; }, ): Promise { const interactionAgeMs = input.kind === "viewer" ? normalizeViewerInteractionAgeMs(input.interactionAgeMs) : null; const updated = await tx.execute<{ id: string }>(sql` update sandbox_lease_holders as holder set last_heartbeat_at = now() ${ interactionAgeMs === null ? sql`` : sql`, last_interaction_at = greatest( holder.last_interaction_at, now() - (${String(interactionAgeMs)} || ' milliseconds')::interval )` } where holder.lease_id = ( select id from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} ) and holder.kind = ${input.kind} and holder.holder_id = ${input.holderId} and ${LIVE_CANONICAL_TURN_HOLDER_PREDICATE} returning holder.id `); return updated.length > 0; } /** A viewer's reported interaction age, made safe for SQL: a finite, * non-negative whole number of milliseconds, at most 30 days. Anything else * (an older client, a malformed value) records nothing, so the reaper falls * back to the attach time and session activity. */ export function normalizeViewerInteractionAgeMs(value: unknown): number | null { if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null; return Math.min(Math.floor(value), 30 * 24 * 60 * 60 * 1000); } // §4.5 — heartbeat. EPOCH-FENCED (the C1b fix — the real split-brain bug, on the // HEARTBEAT path): a stale (superseded) owner's lease refresh is rejected so it // self-evicts. Also liveness-guarded to warm/warming (C2) so a heartbeat can't // wedge a draining lease forever by pushing its grace deadline. // // CONTRACT (two independent signals, one transaction): // - `holderAlive`: this exact holder row still exists and (for a canonical // `turn-attempt:` holder) its attempt is still the active writer. The // row's `last_heartbeat_at` was refreshed, so the dead-worker reap cannot // remove it. This is the ONLY signal that licenses a caller to drop its // in-memory ownership (stop timers, release the holder). // - `leaseExtended`: the lease TTL was refreshed. It is false while the lease is // rotation-fenced, draining, or at another epoch even though the holder is // alive. A false here means "finish orderly work (rotation checkpoint) and // then release"; it never means "the holder is gone". Releasing a live holder // on this signal alone drops the lease to draining under a running turn and // lets the reaper terminate the box it is using. // `heartbeatLeaseHolder` keeps its historical boolean (= `leaseExtended`) for // callers that only need lease authority; liveness loops must use the status form. export type LeaseHolderHeartbeatFence = | "unsupported_kind" | "lease_missing" | "holder_gone" | "epoch" | "liveness" | "rotation_requested"; export type LeaseHolderHeartbeatStatus = | { holderAlive: false; leaseExtended: false; fence: "unsupported_kind" | "lease_missing" | "holder_gone"; } | { holderAlive: true; leaseExtended: true; fence: null } | { holderAlive: true; leaseExtended: false; fence: | "epoch" | "liveness" | "rotation_requested" | "funding" // Viewer holders only: the workspace's monthly warm allowance is // exhausted and no turn holds this box. The viewer must detach so the // box drains; the warm-cap admission gate refuses its re-attach. | "viewer_allowance_exhausted"; }; export async function heartbeatLeaseHolderStatus( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; leaseTtlMs: number; expectedEpoch: number; billingMode?: "usage_only" | "shadow" | "credits"; /** Viewer holders only: how long ago the viewer last saw real user * interaction (see normalizeViewerInteractionAgeMs). */ interactionAgeMs?: number | null | undefined; }, ): Promise { if (input.kind === "process") { return { holderAlive: false, leaseExtended: false, fence: "unsupported_kind", }; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw): Promise => { const tx = txRaw as unknown as Database; // Canonical lock order is lease -> holder. The global reaper uses the // same order, so a heartbeat reviving a stale holder can never deadlock // against stale-holder deletion. const leases = await tx.execute<{ id: string; account_id: string; workspace_id: string; resume_state: Record | null; lease_epoch: number | string; liveness: SandboxLeaseLiveness; rotation_requested_at: Date | string | null; turn_holders: number | string; }>(sql` select id, account_id, workspace_id, resume_state, lease_epoch, liveness, rotation_requested_at, turn_holders from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const lease = leases[0]; if (!lease) return { holderAlive: false, leaseExtended: false, fence: "lease_missing", }; // Holder liveness and lease authority are separate signals. Even after // rotation fences lease extension, the still-running owner can spend // minutes checkpointing before it aborts. Keep its holder alive so the // dead-worker reaper cannot race that checkpoint and terminate the box. // The guarded lease UPDATE below still returns no row, which tells the // owner to complete orderly rotation and release its holder. const holderAlive = await touchLiveLeaseHolder(tx, { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, kind: input.kind, holderId: input.holderId, interactionAgeMs: input.interactionAgeMs, }); if (!holderAlive) { // reaped or no longer the exact active attempt return { holderAlive: false, leaseExtended: false, fence: "holder_gone", }; } const snapshot = warmBillingSnapshot(lease); if (lease.resume_state?.opengeniWarmBilling && !snapshot) { throw new Error("sandbox warm billing snapshot is invalid"); } // An exhausted balance must not mask an older epoch or a drain/rotation // that requires the client to detach and negotiate a new viewer. if (Number(lease.lease_epoch) !== input.expectedEpoch) return { holderAlive: true, leaseExtended: false, fence: "epoch" }; if (lease.liveness !== "warm" && lease.liveness !== "warming") return { holderAlive: true, leaseExtended: false, fence: "liveness" }; if (lease.rotation_requested_at !== null) return { holderAlive: true, leaseExtended: false, fence: "rotation_requested" }; // The warm-cap gate refuses new viewers, but a viewer that attached // before the cap closed would otherwise keep a task-less box warm for // as long as it heartbeats. End that viewer-only hold here. A box a // turn holds keeps running, exactly like the reaper's force drain. if (input.kind === "viewer" && Number(lease.turn_holders) === 0) { const gates = await tx.execute<{ sandbox_viewer_force_drain_reason: SandboxViewerForceDrainReason | null; }>(sql` select sandbox_viewer_force_drain_reason from workspaces where id = ${input.workspaceId} `); if (gates[0]?.sandbox_viewer_force_drain_reason === "warm_cap") { return { holderAlive: true, leaseExtended: false, fence: "viewer_allowance_exhausted", }; } } if ( (input.billingMode ?? snapshot?.mode) === "credits" && snapshot?.mode === "credits" && snapshot.rateMicrosPerSecond > 0 && ( await getSpendableCreditBalance( tx, input.accountId, undefined, undefined, undefined, await attributionBillingOrigin(tx, { accountId: input.accountId, workspaceId: input.workspaceId, attribution: snapshot.attribution, }), ) ).balanceMicros <= 0 ) { // Touching the holder above is essential: the running writer remains // protected while it winds down. The provider/lease TTL is not renewed. return { holderAlive: true, leaseExtended: false, fence: "funding" }; } // Recheck the same fence in the write even though its row lock is held, // keeping the mutation independently auditable and future-proof. const leaseRows = await tx.execute<{ id: string }>(sql` update sandbox_leases set expires_at = now() + (${String(input.leaseTtlMs)} || ' milliseconds')::interval, updated_at = now() where id = ${lease.id} and lease_epoch = ${input.expectedEpoch} and liveness in ('warm','warming') and rotation_requested_at is null returning id `); if (leaseRows.length > 0) return { holderAlive: true, leaseExtended: true, fence: null }; if (Number(lease.lease_epoch) !== input.expectedEpoch) { return { holderAlive: true, leaseExtended: false, fence: "epoch" }; } if (lease.liveness !== "warm" && lease.liveness !== "warming") { return { holderAlive: true, leaseExtended: false, fence: "liveness", }; } return { holderAlive: true, leaseExtended: false, fence: "rotation_requested", }; }), ); } export async function heartbeatLeaseHolder( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; leaseTtlMs: number; expectedEpoch: number; billingMode?: "usage_only" | "shadow" | "credits"; }, ): Promise { return (await heartbeatLeaseHolderStatus(db, input)).leaseExtended; } export type ReinstateTurnLeaseHolderResult = | { status: "present" | "reinstated"; lease: LeaseSnapshot } | { status: | "lease_missing" | "lease_fenced" | "capture_in_progress" | "reaper_held" | "attempt_fenced"; }; /** * Defense in depth for the orderly provider-deadline rotation checkpoint: put the * exact canonical turn holder back onto the lease it is still physically using. * The warm capture claim requires exactly this holder, so a holder lost while * the attempt is still the active writer (a stale release, a reap race) would * otherwise silently disable the rotation checkpoint and let the reaper * terminate the box under the running turn. * * Fenced hard: the lease must still be the established epoch and provider * instance, carry no capture/teardown claim and no active reaper hold, and the * attempt must still be the turn's active `claimed`/`running` writer on a * session of this group. A draining lease that passes those fences re-arms to * warm exactly like a late arrival in `acquireLease`; a cold or superseded lease * is never touched. Idempotent: an existing holder is reported `present`. */ export async function reinstateTurnLeaseHolder( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; sessionId: string; attemptId: string; expectedEpoch: number; expectedInstanceId: string; leaseTtlMs: number; }, ): Promise { const holderId = `turn-attempt:${input.attemptId}`; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw): Promise => { const tx = txRaw as unknown as Database; const rows = await tx.execute(sql` select lease.*, (lease.reaper_hold_id is not null and lease.reaper_hold_until > now()) as reaper_hold_active from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row) return { status: "lease_missing" }; if ( Number(row.lease_epoch) !== input.expectedEpoch || row.instance_id !== input.expectedInstanceId || (row.liveness !== "warm" && row.liveness !== "draining") ) { return { status: "lease_fenced" }; } if (row.archive_capture_id !== null || row.rotation_reason === "teardown_claim") { return { status: "capture_in_progress" }; } if (row.reaper_hold_active) return { status: "reaper_held" }; const live = await tx.execute<{ id: string }>(sql` select attempt.id from session_turn_attempts attempt join session_turns turn on turn.account_id = attempt.account_id and turn.workspace_id = attempt.workspace_id and turn.session_id = attempt.session_id and turn.id = attempt.turn_id and turn.execution_generation = attempt.execution_generation and turn.active_attempt_id = attempt.id join sessions session on session.workspace_id = attempt.workspace_id and session.id = attempt.session_id where attempt.id = ${input.attemptId} and attempt.account_id = ${input.accountId} and attempt.workspace_id = ${input.workspaceId} and attempt.session_id = ${input.sessionId} and attempt.state in ('claimed', 'running') and session.sandbox_group_id = ${input.sandboxGroupId} limit 1 `); if (live.length === 0) return { status: "attempt_fenced" }; const present = await tx.execute<{ id: string }>(sql` select id from sandbox_lease_holders where lease_id = ${row.id} and kind = 'turn' and holder_id = ${holderId} `); if (present.length > 0) return { status: "present", lease: mapLeaseRow(row) }; await upsertLeaseHolder( tx, row.id, input.accountId, input.workspaceId, "turn", holderId, input.sessionId, ); const updated = await recomputeAndStampLease( tx, row.id, input.leaseTtlMs, row.liveness === "draining" ? "warm" : null, ); return { status: "reinstated", lease: mapLeaseRow(updated) }; }), ); } /** * HOLDER-LIVENESS touch: refresh ONLY this holder's last_heartbeat_at. The * warmup phase of a turn (acquire -> waitForWarm -> establish/cold-restore -> * display stack) can legitimately run for many minutes BEFORE the full turn * heartbeat (heartbeatLeaseHolder) starts, and the dead-worker turn-holder * reap judges liveness by this timestamp. Touching our own holder row needs no * lease-epoch fence — supersession is handled by the fenced * acquire/establish paths. Canonical turn holders are still attempt-fenced; * a closed/superseded attempt or a reaped/released row returns false. */ export async function touchLeaseHolder( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; }, ): Promise { if (input.kind === "process") return false; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await touchLiveLeaseHolder(scopedDb, { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, kind: input.kind, holderId: input.holderId, }); }, ); } // §4.6 — the reaper. DB-SIDE ONLY (no provider call — the provider stop() is // P1.3's runtime concern). Three actions in one pass: TTL-reap stale viewer // holders, recompute refcounts + warm->draining, reset warming-death to cold; // returns the drainable (workspaceId, sandboxGroupId) rows the caller terminates. // // This is the PER-WORKSPACE entry point (RLS-scoped). The cross-workspace global // sweep is the SECURITY-DEFINER opengeni_private.reap_sandbox_leases() fn — // reapStaleLeaseHoldersGlobal below. export interface ReapDrainable { workspaceId: string; sandboxGroupId: string; instanceId: string | null; leaseEpoch: number; } export async function reapStaleLeaseHolders( db: Database, input: { workspaceId: string; viewerHolderTtlMs: number; // delete viewer rows older than this /** Delete TURN rows whose heartbeat is older than this (the lease TTL: >> the * 10s turn heartbeat, so only a DEAD worker's holder ever crosses it). 0/absent * = legacy never-reap. */ turnHolderTtlMs?: number; /** Delete placement-controller holders after their BrowserSession or * ComputerSession heartbeat dies. Active controllers refresh both the * resource and holder in one API heartbeat; zero disables only for tests. */ interactionHolderTtlMs?: number; idleGraceMs: number; // drain-grace horizon (matches releaseLeaseHolder) }, ): Promise<{ reapedViewers: number; reapedDirect: number; reapedTurns: number; reapedInteractions: number; warmingReset: number; drained: ReapDrainable[]; }> { return await withWorkspaceRls( db, input.workspaceId, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Take every workspace lease before touching holders. Each following // statement receives a fresh READ COMMITTED snapshot after any active // acquire finishes, so refcounts can never be published from pre-wait // holder state. await tx.execute(sql` select id from sandbox_leases where workspace_id = ${input.workspaceId} order by id for update `); // (a) Reap stale short-lived VIEWER and DIRECT request holders. Process // holders are deliberately absent: they have no TTL and leave only by // exact retained-process exit/loss settlement. Lock victims with SKIP // LOCKED so a legacy heartbeat holding one holder row during a rolling // rollout cannot invert the lease -> holder order. const reaped = await tx.execute<{ lease_id: string; kind: string }>(sql` delete from sandbox_lease_holders where id in ( select id from sandbox_lease_holders where workspace_id = ${input.workspaceId} and kind in ('viewer', 'direct') and last_heartbeat_at < now() - (${String(input.viewerHolderTtlMs)} || ' milliseconds')::interval for update skip locked ) returning lease_id, kind `); const reapedViewers = reaped.filter( (row: { lease_id: string; kind: string }) => row.kind === "viewer", ).length; const reapedDirect = reaped.filter( (row: { lease_id: string; kind: string }) => row.kind === "direct", ).length; // Interaction resources own their placement until their durable // lifecycle ends. A browser/computer controller is not a web page: it // must survive a hidden tab, a closed laptop, a long login/MFA pause, // and agent-only use. The previous timestamp branch treated the React // viewer's heartbeat as controller liveness and falsely destroyed // healthy browserd sessions after a few minutes of UI inactivity. // Provider loss and workspace force-drain have their own authoritative // settlement paths; this sweep only removes orphaned holders. const staleInteractionRows = input.interactionHolderTtlMs && input.interactionHolderTtlMs > 0 ? await rawRows<{ id: string; workspace_id: string }>( tx, sql` select holder.id, holder.workspace_id from sandbox_lease_holders holder where holder.workspace_id = ${input.workspaceId} and holder.kind = 'interaction' and not ( exists ( select 1 from browser_sessions browser join sandbox_leases lease on lease.id = holder.lease_id where holder.holder_id = ('browser-session:' || browser.id::text) and browser.account_id = holder.account_id and browser.workspace_id = holder.workspace_id and browser.sandbox_group_id = lease.sandbox_group_id and browser.lifecycle in ( 'starting', 'active', 'suspending', 'restoring', 'ending' ) ) or exists ( select 1 from computer_sessions computer join sandbox_leases lease on lease.id = holder.lease_id where holder.holder_id = ('computer-session:' || computer.id::text) and computer.account_id = holder.account_id and computer.workspace_id = holder.workspace_id and computer.sandbox_group_id = lease.sandbox_group_id and computer.lifecycle in ( 'starting', 'active', 'suspending', 'restoring', 'ending' ) ) ) for update of holder skip locked `, ) : []; const staleInteractionIds = staleInteractionRows.map( (row: { id: string; workspace_id: string }) => row.id, ); let reapedInteractions = 0; if (staleInteractionIds.length > 0) { const changedBrowsers = await rawRows<{ workspace_id: string }>( tx, sql` update browser_sessions browser set lifecycle = 'lost', controller_id = null, controller_generation = null, placement_instance_id = null, controller_heartbeat_at = null, failure_code = 'controller_heartbeat_expired', updated_at = now() from sandbox_lease_holders holder where holder.id in ${sql`(${sql.join( staleInteractionIds.map((id) => sql`${id}`), sql`, `, )})`} and holder.holder_id = ('browser-session:' || browser.id::text) and holder.account_id = browser.account_id and holder.workspace_id = browser.workspace_id and browser.lifecycle in ( 'starting', 'active', 'suspending', 'restoring', 'ending' ) returning browser.workspace_id `, ); const changedComputers = await rawRows<{ workspace_id: string }>( tx, sql` update computer_sessions computer set lifecycle = 'lost', controller_id = null, controller_generation = null, placement_instance_id = null, controller_heartbeat_at = null, failure_code = 'controller_heartbeat_expired', updated_at = now() from sandbox_lease_holders holder where holder.id in ${sql`(${sql.join( staleInteractionIds.map((id) => sql`${id}`), sql`, `, )})`} and holder.holder_id = ('computer-session:' || computer.id::text) and holder.account_id = computer.account_id and holder.workspace_id = computer.workspace_id and computer.lifecycle in ( 'starting', 'active', 'suspending', 'restoring', 'ending' ) returning computer.workspace_id `, ); const changedWorkspaceIds = [ ...new Set( [...changedBrowsers, ...changedComputers].map( (row: { workspace_id: string }) => row.workspace_id, ), ), ]; if (changedWorkspaceIds.length > 0) { await tx.execute(sql` update workspace_interaction_revisions set revision = revision + 1, updated_at = now() where workspace_id in ${sql`(${sql.join( changedWorkspaceIds.map((id) => sql`${id}`), sql`, `, )})`} `); } const deleted = await rawRows<{ id: string }>( tx, sql` delete from sandbox_lease_holders where id in ${sql`(${sql.join( staleInteractionIds.map((id) => sql`${id}`), sql`, `, )})`} returning id `, ); reapedInteractions = deleted.length; } // (a2) Reap DEAD-WORKER turn holders. A live holder is touched every 10s // from registration (the resumeBoxForTurn holder-liveness loop covers the // warmup; the turn heartbeat covers the run — legit multi-day turns // included), so the caller's horizon is generous defense-in-depth, never // a bound a live path can reach. A holder staler than it belongs to a // worker that died without cleanup (SIGKILL/OOM/deploy churn); left in // place it pins refcount >= 1 FOREVER, so the lease never drains, the // reaper never persists /workspace, and the box rides the provider // hard-timeout to an UNPERSISTED death (the 2026-07-06 staging deploy // churn left holders frozen for hours). The redispatched turn re-acquires // under a NEW holder id, so deleting the corpse never touches a live // execution. const reapedTurnRows = input.turnHolderTtlMs && input.turnHolderTtlMs > 0 ? await tx.execute<{ lease_id: string }>(sql` delete from sandbox_lease_holders as holder where id in ( select holder.id from sandbox_lease_holders as holder where holder.workspace_id = ${input.workspaceId} and holder.kind = 'turn' -- Logical turn closure is not physical capture settlement. A -- warm claim was admitted with this turn as its sole holder; -- retain it through the ORIGINAL bounded capture window so the -- reaper cannot steal a live finalizer and escalate its budget. -- This affects reclamation only, never execution authority or -- holder heartbeats. Expired claims still enter normal recovery. and not exists ( select 1 from sandbox_leases capture_lease where capture_lease.id = holder.lease_id and capture_lease.liveness = 'warm' and capture_lease.archive_capture_id is not null and capture_lease.archive_capture_published_at is null and capture_lease.archive_capture_deadline_at > now() ) and ( holder.last_heartbeat_at < now() - (${String(input.turnHolderTtlMs)} || ' milliseconds')::interval or not ${LIVE_CANONICAL_TURN_HOLDER_PREDICATE} ) for update of holder skip locked ) returning lease_id `) : []; // (b) Recompute refcounts for every lease in the workspace; warm leases // that hit 0 (AND turn_holders=0) enter draining with a fresh grace // deadline (idleGraceMs — the SAME horizon releaseLeaseHolder stamps). await tx.execute(sql` update sandbox_leases L set refcount = c.total, turn_holders = c.turns, viewer_holders = c.viewers, liveness = case when L.liveness = 'warm' and c.total = 0 and c.turns = 0 and (L.reaper_hold_id is null or L.reaper_hold_until <= now()) and ${COMPUTE_IDLE_DRAINABLE_SQL} then 'draining' else L.liveness end, expires_at = case when L.liveness = 'warm' and c.total = 0 and c.turns = 0 and (L.reaper_hold_id is null or L.reaper_hold_until <= now()) and ${COMPUTE_IDLE_DRAINABLE_SQL} then case when L.rotation_requested_at is not null or L.archive_capture_id is not null then now() - interval '1 millisecond' else now() + (${String(input.idleGraceMs)} || ' milliseconds')::interval end else L.expires_at end, updated_at = now() from ( select L2.id, (select count(*) from sandbox_lease_holders h where h.lease_id = L2.id)::int as total, (select count(*) from sandbox_lease_holders h where h.lease_id = L2.id and h.kind = 'turn')::int as turns, (select count(*) from sandbox_lease_holders h where h.lease_id = L2.id and h.kind = 'viewer')::int as viewers from sandbox_leases L2 where L2.workspace_id = ${input.workspaceId} ) c where L.id = c.id and L.workspace_id = ${input.workspaceId} `); // (c1) WARMING-death before provider create returned: no instance_id was // ever persisted, so there is no provider box to stop. Preserve the // selected durable archive as a pending, archive-only cold envelope and // advance the epoch before re-election. The bump fences a late create() // callback from attributing its provider id to the successor attempt. const expiredWarming = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and liveness = 'warming' and expires_at < now() and instance_id is null and (reaper_hold_id is null or reaper_hold_until <= now()) for update `); let warmingReset = 0; for (const row of expiredWarming) { // A lost reply can still name a live provider. Keep the same epoch // available for late attribution; expiry alone is not termination // proof. Only the provider's maximum sandbox lifetime is, and // settleExpiredModalProviderCreate clears the attempt once it passes. if (row.provider_create_attempt?.instanceId === null) continue; const resetResumeState = warmingResetResumeState(row, new Date().toISOString()); const reset = await tx.execute<{ id: string }>(sql` update sandbox_leases set liveness = 'cold', instance_id = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, resume_backend_id = case when ${resetResumeState !== null} then coalesce(resume_backend_id, backend) else null end, resume_state = ${resetResumeState ? JSON.stringify(resetResumeState) : null}::jsonb, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, provider_created_at = null, provider_deadline_at = null, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, updated_at = now() where id = ${row.id} and liveness = 'warming' and lease_epoch = ${Number(row.lease_epoch)} and instance_id is null and (reaper_hold_id is null or reaper_hold_until <= now()) returning id `); if (reset.length > 0 && row.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, { workspaceId: input.workspaceId, sandboxGroupId: row.sandbox_group_id, expectedEpoch: Number(row.lease_epoch), }); } warmingReset += reset.length; } // (c2) WARMING-death after provider create returned: instance_id is known, // so do NOT drop it. Bump the epoch and convert to immediately-drainable // so the caller's provider terminate path stops the box before the lease // goes cold, while late creator callbacks are fenced. const warmingDrain = await tx.execute<{ id: string; sandbox_group_id: string; lease_epoch: number; rotation_requested_at: Date | null; }>(sql` update sandbox_leases set liveness = 'draining', refcount = 0, turn_holders = 0, viewer_holders = 0, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, expires_at = now() - interval '1 millisecond', updated_at = now() where workspace_id = ${input.workspaceId} and liveness = 'warming' and expires_at < now() and instance_id is not null and (reaper_hold_id is null or reaper_hold_until <= now()) returning id, sandbox_group_id, lease_epoch, rotation_requested_at `); for (const lease of warmingDrain) { if (lease.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, { workspaceId: input.workspaceId, sandboxGroupId: lease.sandbox_group_id, expectedEpoch: Number(lease.lease_epoch) - 1, }); } } // (d) DRAINING-grace elapsed: surface leases whose grace is up AND still // idle, with instance_id + epoch, so the caller can issue the provider // stop() then confirmDrainCold. DB-only: no provider call here. const drainable = await rawRows<{ sandbox_group_id: string; instance_id: string | null; lease_epoch: number | string; }>( tx, sql` select sandbox_group_id, instance_id, lease_epoch from sandbox_leases where workspace_id = ${input.workspaceId} and liveness = 'draining' and expires_at < now() and refcount = 0 and (reaper_hold_id is null or reaper_hold_until <= now()) `, ); return { reapedViewers, reapedDirect, reapedTurns: reapedTurnRows.length, reapedInteractions, warmingReset: warmingReset + warmingDrain.length, drained: drainable.map((r) => ({ workspaceId: input.workspaceId, sandboxGroupId: r.sandbox_group_id, instanceId: r.instance_id, leaseEpoch: Number(r.lease_epoch), })), }; }), ); } /** Settlement reasons for legacy retained commands that containment stopped * after a verified checkpoint. None is exit proof: the command settles * `lost` with no exit code. */ export const IDLE_COMMAND_CONTAINMENT_REASON = "idle_containment"; export const DEADLINE_COMMAND_CONTAINMENT_REASON = "provider_deadline_containment"; export const QUIESCENCE_COMMAND_CONTAINMENT_REASON = "quiescence_containment"; type SettledCommandOwner = { sessionId: string; attemptId: string; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; }; /** Exact dispatch settlement is enrollment authority, never physical proof. */ async function settledCommandOwnerMatchesTx( tx: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string }, owner: SettledCommandOwner, ): Promise { const [row] = await rawRows<{ eligible: boolean }>( tx, sql` select exists ( select 1 from session_turn_attempts attempt join sessions session on session.id = attempt.session_id and session.workspace_id = attempt.workspace_id where attempt.account_id = ${input.accountId} and attempt.workspace_id = ${input.workspaceId} and attempt.session_id = ${owner.sessionId} and attempt.id = ${owner.attemptId} and attempt.temporal_workflow_id = ${owner.temporalWorkflowId} and attempt.temporal_workflow_run_id = ${owner.temporalWorkflowRunId} and attempt.temporal_activity_id = ${owner.temporalActivityId} and attempt.state = 'closed' and attempt.quiesced_at is null and session.sandbox_group_id = ${input.sandboxGroupId} and not exists (select 1 from session_attempt_interruptions interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('pending', 'delivered', 'acknowledged')) ) and not exists ( select 1 from session_turn_attempts live join sessions member on member.id = live.session_id and member.workspace_id = live.workspace_id where live.workspace_id = ${input.workspaceId} and member.sandbox_group_id = ${input.sandboxGroupId} and live.state <> 'closed' ) as eligible `, ); return row?.eligible === true; } /** Bounded per-candidate containment inspection outcomes (metric labels). */ export type CommandContainmentInspection = | "idle_enrolled" | "deadline_enrolled" | "forced_deadline_enrolled" | "quiescence_enrolled" | "resumed_enrolled" | "not_eligible" | "inspection_failed"; export type CommandContainmentEnrollment = ReapDrainable & { /** `idle`/`deadline`/`quiescence` newly enrolled this call; `resumed` continues an * existing enrollment whose drain has not committed yet. */ mode: "idle" | "deadline" | "forced_deadline" | "quiescence" | "resumed"; }; /** Whole-group "unused" from durable facts only. Every session of the group, * and every session owning a process on the lease, must have no open turn * (queued, running, waiting_capacity), no unpaused recovery, no non-closed * attempt and no pending quiescence; the newest attempt close, turn finish, * holder-set change and admission (or settlement) on this lease epoch must all * be older than the window; and no active command on the lease may have * printed output inside the window. * * A wait is not use. A held `wait_for_input` or a turn parked in * `requires_action` waits for a person, a child or a timer, none of which needs * the machine; the wait's start is already on the clock as its turn finish or * attempt close, and the box resumes on demand. The only work that keeps the * box is a command that is visibly busy: the retained-process reconciler drains * a running command's output into durable `sandbox.command.output.delta` * events at most five minutes apart, so a command that printed nothing for the * whole window is treated as idle whatever the agent is waiting for. Process * age is deliberately not a fact here. */ async function sandboxGroupIdleForCommandContainmentTx( tx: Database, input: { workspaceId: string; sandboxGroupId: string; leaseId: string; windowMs: number; writerMode: "physical" | "containment"; }, ): Promise { const [facts] = await rawRows<{ idle: boolean; session_ids: string[]; recovering_session_ids: string[]; }>( tx, sql` with member_sessions as ( select session.id from sessions session where session.workspace_id = ${input.workspaceId} and session.sandbox_group_id = ${input.sandboxGroupId} union select process.session_id from sandbox_retained_processes process where process.lease_id = ${input.leaseId} and process.state = 'active' ), attempts as ( select attempt.state, coalesce(attempt.quiesced_at, attempt.closed_at, attempt.updated_at) as settled_at from session_turn_attempts attempt where attempt.workspace_id = ${input.workspaceId} and attempt.session_id in (select id from member_sessions) ) select not exists (select 1 from attempts where state <> 'closed') and not exists ( select 1 from session_turns turn where turn.workspace_id = ${input.workspaceId} and turn.session_id in (select id from member_sessions) and turn.status in ('queued', 'running', 'waiting_capacity')) and coalesce(greatest( (select lease.holders_changed_at from sandbox_leases lease where lease.id = ${input.leaseId}), (select max(settled_at) from attempts), (select max(turn.finished_at) from session_turns turn where turn.workspace_id = ${input.workspaceId} and turn.session_id in (select id from member_sessions)), -- Unclaimed turn-starting input is an idle-clock fact, not a -- permanent blocker: input a paused session can never deliver -- must not pin the box until its provider deadline. (select max(pending_update.created_at) from session_system_updates pending_update where pending_update.workspace_id = ${input.workspaceId} and pending_update.session_id in (select id from member_sessions) and pending_update.state = 'pending' and (pending_update.kind in (${sql.join( COMMAND_CONTAINMENT_TURN_STARTING_UPDATE_KINDS.always.map((kind) => sql`${kind}`), sql`, `, )}) or (pending_update.kind in (${sql.join( COMMAND_CONTAINMENT_TURN_STARTING_UPDATE_KINDS.withActiveGoal.map( (kind) => sql`${kind}`, ), sql`, `, )}) and exists (select 1 from session_goals goal where goal.workspace_id = pending_update.workspace_id and goal.session_id = pending_update.session_id and goal.status = 'active')))), (select max(coalesce(admission.settled_at, admission.admitted_at)) from sandbox_workspace_mutation_admissions admission join sandbox_leases lease on lease.id = admission.lease_id where admission.lease_id = ${input.leaseId} and admission.lease_epoch = lease.lease_epoch) ) < now() - (${input.windowMs}::bigint * interval '1 millisecond'), false) -- A command that printed inside the window is working, not idle. -- Only each command's newest output row is read (backward over the -- output page index), so the cost does not grow with its history. and not exists ( select 1 from sandbox_retained_processes busy where busy.lease_id = ${input.leaseId} and busy.state = 'active' and ( select output.created_at from session_events output where output.workspace_id = busy.workspace_id and output.session_id = busy.session_id and output.type = 'sandbox.command.output.delta' and output.payload->>'commandId' = busy.id::text order by output.sequence desc limit 1 ) >= now() - (${input.windowMs}::bigint * interval '1 millisecond') ) as idle, array(select id from member_sessions order by id) as session_ids, array(select distinct turn.session_id from session_turns turn where turn.workspace_id = ${input.workspaceId} and turn.session_id in (select id from member_sessions) and turn.status = 'recovering') as recovering_session_ids `, ); if (!facts?.idle) return false; for (const sessionId of facts.recovering_session_ids) { // Recovery is queued work, not an executing writer. An effective pause // keeps that work pending across a cold restore; it must not pin a box. // The locked enrollment rechecks control under the existing workspace // fence, while open attempts and physical quiescence still gate cleanup. const control = await evaluateSessionWriteAdmissionControl(tx, input.workspaceId, sessionId, { lock: "none", }); if (control.state !== "paused") return false; } for (const sessionId of facts.session_ids) { if ( await hasPendingSessionAttemptQuiescenceTx(tx, { workspaceId: input.workspaceId, sessionId, writerMode: input.writerMode, }) ) return false; } return true; } /** Pending machine input that would start a turn in an idle session, by the * wake class map: every immediate kind except terminal command results (held * for the next turn); child lifecycle notices only wake a parent with an active * goal. Migration 0547's inventory screen repeats this set as SQL literals; a * test pins the two together. */ export const COMMAND_CONTAINMENT_TURN_STARTING_UPDATE_KINDS = (() => { const immediate = ( Object.entries(SESSION_SYSTEM_UPDATE_WAKE_CLASS) as Array<[SessionSystemUpdateKind, string]> ) .filter( ([kind, wakeClass]) => wakeClass === "immediate" && kind !== "background_command_result", ) .map(([kind]) => kind); return { always: immediate.filter((kind) => !isChildLifecycleSystemUpdateKind(kind)), withActiveGoal: immediate.filter((kind) => isChildLifecycleSystemUpdateKind(kind)), }; })(); /** Whether a lease's drain capture images the box at one instant: a Modal * native filesystem/directory snapshot of the paused box, or a Docker host * workspace read after the drain stopped the exact container (possible only * when the envelope carries the durable ownership receipt that lets a retry * re-attach to a stopped container's root). Mirrors the runtime's * `providerDrainCaptureIsPointInTime` for the lease envelope: only such a * capture may run around a crashed worker's orphaned request, so * containment may treat the orphan as non-blocking only then; otherwise its * drain could never capture and the box would stay fenced until it died. */ function leaseDrainCaptureIsPointInTime(backend: string, resumeState: unknown): boolean { if ((backend !== "modal" && backend !== "docker") || !resumeState) return false; if (typeof resumeState !== "object") return false; const sessionState = (resumeState as { sessionState?: unknown }).sessionState; const session = sessionState && typeof sessionState === "object" ? (sessionState as Record) : (resumeState as Record); const providerState = session.providerState && typeof session.providerState === "object" ? (session.providerState as Record) : null; if (backend === "docker") { const receipt = providerState?.opengeniDockerWorkspaceOwnership; return Boolean(receipt && typeof receipt === "object" && !Array.isArray(receipt)); } const persistence = providerState?.workspacePersistence ?? session.workspacePersistence; return persistence === "snapshot_filesystem" || persistence === "snapshot_directory"; } /** The deadline backstop's owner test is the idle rule's: a closed turn owner * must hold no pending quiescence (unsettled interruption or attempt writer). */ async function deadlineOwnerQuiescencePending( tx: Database, workspaceId: string, processes: readonly { session_id: string; owner_attempt_id: string | null }[], writerMode: "physical" | "containment", ): Promise { for (const process of processes) { if ( process.owner_attempt_id && (await hasPendingSessionAttemptQuiescenceTx(tx, { workspaceId, sessionId: process.session_id, attemptId: process.owner_attempt_id, writerMode, })) ) return true; } return false; } /** Backends whose retained commands outlive their turn and can therefore be the * only thing keeping a box warm. Docker and local commands run under an * in-sandbox supervisor and have no provider deadline, so only this idle rule * ever drains such a box. Matches `list_command_containment_candidates`. */ const COMMAND_CONTAINMENT_BACKENDS: ReadonlySet = new Set(["modal", "docker", "local"]); /** * Contain unsupervised retained commands that are the only thing keeping a * Modal, Docker or local box warm (on Modal, the legacy ones without native * supervision). One rule decides, independent of command health: the lease holds only * process holders and their parent admissions, no supervised process, capture * or reaper hold, and either the whole sandbox group has been idle for * `idleCommandContainmentMs`, or a provider-deadline rotation's bounded stop * grace has elapsed for every command. Enrollment is lifecycle intent, not exit * proof: the existing drain captures the current generation excluding exactly * these holders/admissions, terminates the box, and settles the commands. * * The workspace control fence plus process -> admission -> lease row locks * serialize this decision with every new holder or admission: an arrival that * committed first is seen and refuses enrollment; a later one observes the * requested rotation and is fenced until the successor box. */ export async function enrollRetainedCommandContainment( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; /** Omit to evaluate only the provider-deadline rule. */ idleCommandContainmentMs?: number | undefined; /** Inside this window before the provider deadline the deadline save is * mandatory (see `sandboxDeadlineMandatoryCaptureLeadMs`). Omit to keep * only the orderly deadline rule. */ deadlineMandatoryCaptureLeadMs?: number | undefined; /** Internal recovery authority: caller verified exact Temporal settlement. */ settledOwner?: SettledCommandOwner; }, ): Promise { const screened = await withRlsContext(db, input, async (tx) => { // Cheap unlocked screen, before touching the lease row, so a group that is // in use does not take the exclusive workspace-control fence on every // sweep. Only the locked re-check below may enroll. const lease = await readLease(tx, input.workspaceId, input.sandboxGroupId); const pass = lease !== null && // Enrolled drains resume; any requested rotation also refreshes command // observation backoff below and may meet the deadline rule. (Boolean(lease.unobservableCommandDrainIds?.length) || (input.settledOwner !== undefined && (await settledCommandOwnerMatchesTx(tx, input, input.settledOwner))) || lease.rotationRequestedAt !== null || (input.idleCommandContainmentMs !== undefined && (await sandboxGroupIdleForCommandContainmentTx(tx, { ...input, leaseId: lease.id, windowMs: input.idleCommandContainmentMs, writerMode: leaseDrainCaptureIsPointInTime(lease.backend, lease.resumeState) ? "containment" : "physical", })))); // Round-robin inventory: an ineligible live lease cannot starve later rows. // This updates only the inspection cursor, never provider/holder authority. await tx.execute(sql`update sandbox_leases set unobservable_command_checked_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId}`); return pass; }); if (!screened) return null; return await withRlsContext(db, input, async (tx) => { await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const initial = await readLease(tx, input.workspaceId, input.sandboxGroupId); if ( !initial || !COMMAND_CONTAINMENT_BACKENDS.has(initial.backend) || !initial.instanceId || !["warm", "draining"].includes(initial.liveness) ) return null; // A command observation backoff must not suppress provider-death checks // during a mandatory rotation. Do not steal an in-flight reconciler claim. if (initial.rotationRequestedAt !== null) { await tx.execute(sql` update sandbox_retained_processes set reconcile_after = least(reconcile_after, now()) where lease_id = ${initial.id} and state = 'active' and reconcile_claim_id is null and ${unobservableRetainedProcessOutcomeSql(sql`last_reconcile_outcome`)} `); } // A deadline gives a legacy command two minutes after cancellation intent // to exit, then captures its current files while the old box still exists. const deadlineStopGraceMs = SANDBOX_DEADLINE_COMMAND_STOP_GRACE_MS; const deadlineRotation = initial.rotationReason === "provider_deadline" && initial.rotationRequestedAt !== null; const deadlineGrace = sql`now() - (${deadlineStopGraceMs}::bigint * interval '1 millisecond')`; // Preserve process -> admission -> lease ordering used by settlement. const processes = await rawRows<{ id: string; session_id: string; owner_attempt_id: string | null; parent_admission_id: string; holder_id: string; supervised: boolean; owned: boolean; deadline_ready: boolean; adopted: boolean; }>( tx, sql` select process.id, process.session_id, process.owner_attempt_id, process.parent_admission_id, process.holder_id, exists (select 1 from session_background_commands background where background.retained_process_id = process.id and background.workspace_id = process.workspace_id and background.session_id = process.session_id and background.state in ('running', 'stopping')) as adopted, (coalesce(process.provider_command, '{}'::jsonb) ? 'supervision') as supervised, (process.lease_epoch = ${initial.leaseEpoch} and process.provider_instance_id = ${initial.instanceId} and process.provider_backend = ${initial.backend} and process.route_target_id is null) as owned, coalesce(${deadlineRotation} and process.deadline_cancellation_requested_at < ${deadlineGrace} and process.reconcile_attempts >= 1 and ( -- Whatever its outcome, a closed owner is a writer no longer; its -- pending quiescence is re-checked below with the idle rule's test. (process.owner_actor_kind = 'turn' and attempt.state = 'closed' and greatest(coalesce(attempt.quiesced_at, attempt.closed_at, attempt.updated_at), process.started_at) < ${deadlineGrace}) or (process.owner_actor_kind = 'direct' and process.owner_attempt_id is null and process.started_at < ${deadlineGrace}) ), false) as deadline_ready from sandbox_retained_processes process left join session_turn_attempts attempt on attempt.id = process.owner_attempt_id and attempt.workspace_id = process.workspace_id and attempt.session_id = process.session_id where process.lease_id = ${initial.id} and process.state = 'active' order by process.id for update of process `, ); const admissions = await rawRows<{ id: string; orphaned: boolean; exact: boolean }>( tx, sql` select admission.id, (admission.lease_epoch = ${initial.leaseEpoch} and admission.provider_instance_id = ${initial.instanceId} and ${crashedWorkerOrphanAdmissionSql(sql`admission`)}) as orphaned, (admission.lease_epoch = ${initial.leaseEpoch} and admission.provider_instance_id = ${initial.instanceId}) as exact from sandbox_workspace_mutation_admissions admission where admission.lease_id = ${initial.id} and admission.settled_at is null order by admission.id for update of admission `, ); const rows = await tx.execute(sql` select *, (rotation_requested_at is not null and ${input.deadlineMandatoryCaptureLeadMs ?? null}::bigint is not null and provider_deadline_at is not null and provider_deadline_at <= now() + (${input.deadlineMandatoryCaptureLeadMs ?? null}::bigint * interval '1 millisecond')) as deadline_mandatory from sandbox_leases where id = ${initial.id} for update `); const lease = rows[0]; // Close to the provider deadline the save is mandatory: an orderly // shutdown can no longer finish in time, and waiting means the provider // kills the box uncaptured. const mandatory = lease?.deadline_mandatory === true; if ( !lease || Number(lease.lease_epoch) !== initial.leaseEpoch || lease.instance_id !== initial.instanceId || !["warm", "draining"].includes(lease.liveness) || (lease.reaper_hold_until && new Date(lease.reaper_hold_until).getTime() > Date.now()) ) return null; const enrolled = lease.unobservable_command_drain_ids; const ids = enrolled ?? processes.map((p) => p.id); if ( !ids.length || processes.some((p) => p.supervised) || (!enrolled && processes.some((p) => !p.owned)) || processes.some((p) => !ids.includes(p.id)) ) return null; // A request a crashed worker left on this exact box is not a writer that // can finish. Only a point-in-time drain captures around it (the cold // commit settles it once the box is terminated); for a tar-style capture // it stays a blocker, or the enrolled drain could never capture. const pointInTime = leaseDrainCaptureIsPointInTime(initial.backend, initial.resumeState); const writerMode = pointInTime ? ("containment" as const) : ("physical" as const); const parents = new Set(processes.map((p) => p.parent_admission_id)); // A tolerated orphan is captured around only by a point-in-time drain. const tolerated = (a: { id: string; orphaned: boolean }) => parents.has(a.id) || (pointInTime && a.orphaned); // A mandatory deadline save captures around every other request still // open on this exact box (a stdin write in flight, a request whose owner // vanished, an orphan under a tar-style capture) and settles it with the // box after termination. Requests on an older epoch or instance do not // touch this box's capture. const forced = mandatory ? admissions.filter((a) => a.exact && !tolerated(a)).map((a) => a.id) : []; if ( admissions.some((a) => !tolerated(a) && !(mandatory && (forced.includes(a.id) || !a.exact))) ) return null; const holders = await rawRows<{ kind: string; holder_id: string }>( tx, sql` select kind, holder_id from sandbox_lease_holders where lease_id = ${lease.id} `, ); if ( holders.some( (h) => h.kind !== "process" || !processes.some((p) => p.holder_id === h.holder_id), ) ) return null; const target = { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, instanceId: initial.instanceId, leaseEpoch: initial.leaseEpoch, }; if (enrolled) return { ...target, mode: "resumed" }; if (lease.archive_capture_id !== null) return null; let mode: "idle" | "deadline" | "forced_deadline" | "quiescence" | null = null; if (mandatory) { // No stop grace, owner quiescence or sibling activity can be waited for // any longer. Holders were checked above: a live turn, viewer or direct // request on the box still blocks, and supervised commands keep their // separate proof gate. mode = "forced_deadline"; } else if ( input.settledOwner !== undefined && processes.every( (p) => p.owner_attempt_id === input.settledOwner!.attemptId && p.session_id === input.settledOwner!.sessionId && !p.adopted, ) && (await settledCommandOwnerMatchesTx(tx, input, input.settledOwner)) ) { mode = "quiescence"; } else if ( deadlineRotation && processes.every((p) => p.deadline_ready) && !(await deadlineOwnerQuiescencePending(tx, input.workspaceId, processes, writerMode)) && !(await hasSandboxGroupAttemptActivityTx(tx, { ...input, idleGraceMs: deadlineStopGraceMs, writerMode, })) ) { mode = "deadline"; } else if ( input.idleCommandContainmentMs !== undefined && (await sandboxGroupIdleForCommandContainmentTx(tx, { ...input, leaseId: lease.id, windowMs: input.idleCommandContainmentMs, writerMode, })) ) { mode = "idle"; } if (!mode) return null; await tx.execute(sql` update sandbox_leases set unobservable_command_drain_ids = ${`{${ids.join(",")}}`}::uuid[], deadline_forced_admission_ids = ${forced.length ? `{${forced.join(",")}}` : null}::uuid[], command_containment_reason = ${ mode === "quiescence" ? QUIESCENCE_COMMAND_CONTAINMENT_REASON : mode === "deadline" || mode === "forced_deadline" ? DEADLINE_COMMAND_CONTAINMENT_REASON : IDLE_COMMAND_CONTAINMENT_REASON }, liveness = 'draining', rotation_requested_at = coalesce(rotation_requested_at, now()), rotation_reason = coalesce(rotation_reason, 'operator'), expires_at = now(), updated_at = now() where id = ${lease.id} `); return { ...target, mode }; }); } /** Bounded per-candidate idle interaction outcomes (metric labels). */ export type IdleInteractionInspection = | "released" | "checkpointing" | "not_eligible" | "inspection_failed"; export type IdleInteractionRelease = { /** Set when the box lost its last holder and drains now. */ drainable: ReapDrainable | null; /** Browsers whose idle save was prepared; their holders stay until saved. */ checkpoints: number; /** Browsers and desktops released without a save (marked lost). */ released: number; }; /** Failure code of a browser or desktop stopped because nobody used it. */ export const IDLE_INTERACTION_RELEASED = "idle_released"; /** A browser or desktop on a compute sandbox whose chat or workspace was deleted. */ export const COMPUTE_GROUP_ENDED = "sandbox_deleted"; const INTERACTION_HOLDER_RESOURCE = /^(browser-session|computer-session):([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; /** A browser an agent session holds while it works or waits. */ export type AgentHeldBrowserSession = { accountId: string; workspaceId: string; browserSessionId: string; /** The person to reach its controller as: the most recent person who * started a turn of a holding session, or null when no person did. */ routeSubjectId: string | null; }; /** * The browsers that agent sessions hold right now, across workspaces: active, * used within `BROWSER_WAIT_HOLD_MAX_MS`, and created or used by a session * that is still working (a turn queued, running, recovering, waiting for * capacity or waiting on a person) or has an armed input wait. The same rule * as the box release below; the API renews each one's hold on its controller. * Most recently used first, at most `limit`. Migration 1002 creates the * routine and 1093 grants it to the runtime. */ export async function listAgentHeldBrowserSessions( db: Database, input: { limit: number }, ): Promise { const rows = await rawRows<{ account_id: string; workspace_id: string; browser_session_id: string; route_subject_id: string | null; }>( db, sql`select * from opengeni_private.list_agent_held_browser_sessions( ${input.limit}::integer, ${BROWSER_WAIT_HOLD_MAX_MS}::bigint)`, ); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, browserSessionId: row.browser_session_id, routeSubjectId: row.route_subject_id, })); } /** * An idle browser or desktop does not keep its Modal box warm. Activity is * deliberate and durable: the newest of the interaction holder heartbeat and * the resource's last use and controller heartbeat. Every controller request * moves all three - an agent tool call, a person's input, and the live view's * poll and heartbeat, which run only while the page is visible - so a hidden * tab or a closed view stops counting within seconds. An in-flight lifecycle * operation counts too. Interventions waiting for a person do not: a wait is * not use (see `sandboxGroupIdleForCommandContainmentTx`). * * One kind of pause does keep a browser: an agent session that * created or is using it and is still working (a turn queued, running, * recovering, waiting for capacity or waiting on a person) or deliberately * waiting (an armed input wait) keeps it, page state and all, but never * longer than `BROWSER_WAIT_HOLD_MAX_MS` after the browser's last use. The * browser's own controller keeps it by the same rule; * `list_idle_interaction_leases` (migration 1002) skips such boxes. * * When every browser and desktop on the box, and the whole sandbox group by * the general idle rule, have been unused for `idleMs` (the sandbox idle * grace), all are released at once. A checkpoint-capable browser gets the * system profile save (the provider-deadline checkpoint with an `idle` * reason) and keeps its holder until that save is committed; anything else is * marked lost with `idle_released` and its holder is deleted. With no holder * left the box drains immediately: the ordinary drain saves /workspace and * stops it, and the next acquire restores it. * * The workspace control fence and lease -> holder -> operation -> resource * row locks serialize the decision with controller requests, which lock the * lease and holder before touching their resource. */ export async function releaseIdleInteractionHolders( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; idleMs: number; /** False when the worker cannot save browser profiles (no object storage, * delegation secret or encryption key, or no Temporal checkpoint worker); * browsers are then released like desktops. */ browserCheckpoints: boolean; }, ): Promise { if (!Number.isSafeInteger(input.idleMs) || input.idleMs < 60_000) { throw new Error("Idle interaction release needs an idle window of at least one minute"); } const screened = await withRlsContext(db, input, async (tx) => { const lease = await readLease(tx, input.workspaceId, input.sandboxGroupId); return ( lease !== null && lease.backend === "modal" && lease.liveness === "warm" && (await sandboxGroupIdleForCommandContainmentTx(tx, { ...input, leaseId: lease.id, windowMs: input.idleMs, writerMode: leaseDrainCaptureIsPointInTime(lease.backend, lease.resumeState) ? "containment" : "physical", })) ); }); if (!screened) return null; return await withRlsContext(db, input, async (tx) => { await lockWorkspaceInferenceControl(tx, input.workspaceId, "update"); const [lease] = await rawRows( tx, sql` select *, holders_changed_at::text as prior_holders_changed_at, holders_changed_at < now() - (${input.idleMs}::bigint * interval '1 millisecond') as idle from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `, ); if ( !lease || !lease.idle || lease.backend !== "modal" || lease.liveness !== "warm" || !lease.instance_id || lease.rotation_requested_at !== null || lease.archive_capture_id !== null || Boolean(lease.unobservable_command_drain_ids?.length) || (lease.reaper_hold_until && new Date(lease.reaper_hold_until).getTime() > Date.now()) ) return null; const holders = await rawRows<{ id: string; kind: string; holder_id: string; idle: boolean; }>( tx, sql` select id, kind, holder_id, last_heartbeat_at < now() - (${input.idleMs}::bigint * interval '1 millisecond') as idle from sandbox_lease_holders where lease_id = ${lease.id} order by id for update `, ); const interactions = holders.filter((holder) => holder.kind === "interaction"); if ( interactions.length === 0 || holders.some((holder) => holder.kind !== "interaction" && holder.kind !== "process") || interactions.some((holder) => !holder.idle) ) return null; if ( !(await sandboxGroupIdleForCommandContainmentTx(tx, { ...input, leaseId: lease.id, windowMs: input.idleMs, writerMode: leaseDrainCaptureIsPointInTime(lease.backend, lease.resume_state) ? "containment" : "physical", })) ) return null; const resources = interactions.map((holder) => { const match = INTERACTION_HOLDER_RESOURCE.exec(holder.holder_id); return { holder, kind: match?.[1] === "browser-session" ? ("browser_session" as const) : match ? ("computer_session" as const) : null, id: match?.[2] ?? null, }; }); const browserIds = resources.filter((r) => r.kind === "browser_session").map((r) => r.id!); const computerIds = resources.filter((r) => r.kind === "computer_session").map((r) => r.id!); const uuidList = (ids: string[]) => ids.length ? sql`(${sql.join( ids.map((id) => sql`${id}::uuid`), sql`, `, )})` : sql`(null::uuid)`; const operations = await rawRows<{ operation_id: string }>( tx, sql` select operation_id from interaction_operations where workspace_id = ${input.workspaceId} and state in ('prepared', 'dispatched') and ((resource_kind = 'browser_session' and resource_id in ${uuidList(browserIds)}) or (resource_kind = 'computer_session' and resource_id in ${uuidList(computerIds)})) order by operation_id for update `, ); if (operations.length > 0) return null; const idleBefore = sql`now() - (${input.idleMs}::bigint * interval '1 millisecond')`; const browsers = await rawRows<{ id: string; lifecycle: string; idle: boolean; checkpoint: boolean; controller_generation: string | null; }>( tx, sql` select id, lifecycle, controller_generation, (coalesce(greatest(last_used_at, controller_heartbeat_at) < ${idleBefore}, true) and not exists ( select 1 from browser_session_associations association join sessions waiting on waiting.id = association.session_id and waiting.workspace_id = association.workspace_id where association.workspace_id = browser_sessions.workspace_id and association.browser_session_id = browser_sessions.id and association.relationship in ('created', 'using') and (waiting.status in ('queued', 'running', 'requires_action', 'recovering', 'waiting_capacity') or waiting.input_wait_until > now()) and browser_sessions.last_used_at > now() - (${BROWSER_WAIT_HOLD_MAX_MS}::bigint * interval '1 millisecond') )) as idle, (placement_kind = 'sandbox_group' and controller_host_sandbox_group_id = ${input.sandboxGroupId} and placement_instance_id = ${lease.instance_id} and controller_generation is not null and controller_id is not null and capabilities->>'privateCheckpoint' = 'true') as checkpoint from browser_sessions where workspace_id = ${input.workspaceId} and account_id = ${input.accountId} and id in ${uuidList(browserIds)} order by id for update `, ); const computers = await rawRows<{ id: string; lifecycle: string; idle: boolean }>( tx, sql` select id, lifecycle, coalesce(greatest(last_used_at, controller_heartbeat_at) < ${idleBefore}, true) as idle from computer_sessions where workspace_id = ${input.workspaceId} and account_id = ${input.accountId} and id in ${uuidList(computerIds)} order by id for update `, ); const terminal = new Set(["ended", "failed", "lost"]); // A transition (starting, suspending, restoring, ending) or a saved // browser awaiting cleanup is not idle: the transition reaper and the // checkpoint own them. Any recently used resource keeps the whole box. if ( [...browsers, ...computers].some( (resource) => !resource.idle || (resource.lifecycle !== "active" && !terminal.has(resource.lifecycle)), ) ) return null; const checkpointed = new Set(); if (input.browserCheckpoints) { for (const browser of browsers) { if (browser.lifecycle !== "active" || !browser.checkpoint) continue; // Null when an idle save of this exact controller generation already // failed: the browser is then released without a second attempt. const claim = await browserDeadlineCheckpoint( tx, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, leaseId: lease.id, leaseEpoch: Number(lease.lease_epoch), instanceId: lease.instance_id, browserSessionId: browser.id, controllerGeneration: browser.controller_generation!, reason: "idle", idleMs: input.idleMs, }, { prepare: true }, ); if (claim?.state === "prepared") checkpointed.add(browser.id); } } const lostBrowsers = browsers.filter( (b) => b.lifecycle === "active" && !checkpointed.has(b.id), ); const lostComputers = computers.filter((c) => c.lifecycle === "active"); if (lostBrowsers.length > 0) { await tx.execute(sql` update browser_sessions set lifecycle = 'lost', failure_code = ${IDLE_INTERACTION_RELEASED}, updated_at = now() where workspace_id = ${input.workspaceId} and id in ${uuidList(lostBrowsers.map((b) => b.id))} and lifecycle = 'active' `); } if (lostComputers.length > 0) { await tx.execute(sql` update computer_sessions set lifecycle = 'lost', failure_code = ${IDLE_INTERACTION_RELEASED}, updated_at = now() where workspace_id = ${input.workspaceId} and id in ${uuidList(lostComputers.map((c) => c.id))} and lifecycle = 'active' `); } const released = resources .filter((r) => !(r.kind === "browser_session" && checkpointed.has(r.id!))) .map((r) => r.holder.id); if (released.length > 0) { await tx.execute(sql` delete from sandbox_lease_holders where lease_id = ${lease.id} and id in ${uuidList(released)} `); } if (lostBrowsers.length + lostComputers.length > 0) { await tx.execute(sql` update workspace_interaction_revisions set revision = revision + 1, updated_at = now() where workspace_id = ${input.workspaceId} `); } const [counts] = await rawRows<{ total: number; turns: number; viewers: number }>( tx, sql` select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers from sandbox_lease_holders where lease_id = ${lease.id} `, ); const drain = counts!.total === 0; await tx.execute(sql` update sandbox_leases set refcount = ${counts!.total}, turn_holders = ${counts!.turns}, viewer_holders = ${counts!.viewers}, ${drain ? sql`liveness = 'draining', expires_at = now() - interval '1 millisecond',` : sql``} updated_at = now() where id = ${lease.id} `); if (!drain) { // The holder-set clock measures use, not this release: a box left // with legacy retained commands keeps its containment clock, so // containment does not wait another full window because of it. await tx.execute(sql` update sandbox_leases set holders_changed_at = ${lease.prior_holders_changed_at}::timestamptz where id = ${lease.id} `); } return { drainable: drain ? { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, instanceId: lease.instance_id, leaseEpoch: Number(lease.lease_epoch), } : null, checkpoints: checkpointed.size, released: lostBrowsers.length + lostComputers.length, }; }); } export type IdleCheckpointCandidate = { accountId: string; workspaceId: string; sandboxGroupId: string; leaseEpoch: number; instanceId: string; }; /** Global inventory of warm Modal boxes that no turn holds and that viewers, * browser/computer interactions or running background commands (supervised or * not) keep warm, whose workspace has writes the newest archive may not cover, and * whose last capture attempt and last idle checkpoint attempt are both at least * `intervalMs` old (least recently tried first). Discovery only: the exact * warm capture claim (`claimWorkspaceArchiveCapture` with `idleCheckpoint`) * re-checks every fact under the lease lock before any provider capture. */ export async function listIdleCheckpointCandidates( db: Database, input: { limit: number; intervalMs: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) { throw new Error("Idle checkpoint batch is invalid"); } if (!Number.isSafeInteger(input.intervalMs) || input.intervalMs < 1) { throw new Error("Idle checkpoint interval is invalid"); } const rows = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; lease_epoch: number | string; instance_id: string; }>( db, sql`select * from opengeni_private.list_idle_checkpoint_candidates( ${input.limit}::integer, ${input.intervalMs}::bigint)`, ); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, sandboxGroupId: row.sandbox_group_id, leaseEpoch: Number(row.lease_epoch), instanceId: row.instance_id, })); } /** Stamp an idle checkpoint attempt on the exact warm box before the sweep * tries it, whatever the outcome. The inventory lists a box again only after * the snapshot interval, so a box whose claim is refused or whose provider * fails cannot hold a batch slot on every sweep and starve the others. */ export async function recordIdleCheckpointAttempt( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set idle_checkpoint_attempted_at = now() where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'warm' and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} returning id `); return rows.length === 1; }, ); } // §4.6 (global) — the cross-workspace reaper sweep (OD-3). Calls the // SECURITY-DEFINER opengeni_private.reap_sandbox_leases() fn so the global // reaper Temporal Schedule (P1.3) sees stale rows across ALL workspaces in ONE // pass, bypassing per-workspace FORCE RLS. DB-only — returns the drainable rows; // the provider stop() is the caller's concern. No RLS GUC is set (the DEFINER fn // is the sanctioned cross-workspace read). Each invocation runs in its own // transaction and opts into the recovery protocol fence; this also makes the // legacy fallback safe after PostgreSQL aborts an undefined-function call. export async function reapStaleLeaseHoldersGlobal( db: Database, input: { viewerHolderTtlMs: number; /** Reap DEAD-WORKER turn holders staler than this (the lease TTL; see * reapStaleLeaseHolders). 0/absent = never (legacy). */ turnHolderTtlMs?: number; interactionHolderTtlMs?: number; idleGraceMs: number; /** Whole-group idle window for legacy retained-command containment. * Omitted: only the provider-deadline rule may enroll commands. */ idleCommandContainmentMs?: number | undefined; /** Mandatory pre-deadline save window (sandboxDeadlineMandatoryCaptureLeadMs). */ deadlineMandatoryCaptureLeadMs?: number | undefined; onCommandContainment?: (outcome: CommandContainmentInspection) => void; onCommandContainmentError?: (error: unknown) => void; /** The general sandbox idle grace. Browsers and desktops unused for this * long stop holding their box (`releaseIdleInteractionHolders`). Omitted: * interaction holders keep their box until the provider deadline. */ idleInteractionReleaseMs?: number | undefined; /** Whether idle checkpoint-capable browsers are saved before release. */ idleBrowserCheckpoints?: boolean; onIdleInteractionRelease?: (outcome: IdleInteractionInspection) => void; }, ): Promise { // Active interaction holders represent durable BrowserSession/ComputerSession // ownership, not viewer presence, and therefore never expire by timestamp. // A separate lifecycle-aware function settles only stale starting/restoring/ // suspending/ending transitions. API controller mutations pulse their holder // while in flight, so the transition TTL detects an abandoned caller rather // than imposing a maximum duration on profile capture or restore. The same // lifecycle function is also the hard provider-deadline override: once a // requested finite-lifetime Modal lease is due, its controller resources are // lost and their holders are released without turning timestamp age into a // general active-session expiry policy. const rows = await db.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; await tx.execute(sql`select set_config('opengeni.sandbox_recovery_protocol_v2', '1', true)`); if (input.interactionHolderTtlMs && input.interactionHolderTtlMs > 0) { await tx.execute(sql` select opengeni_private.reap_stale_interaction_transitions( ${input.interactionHolderTtlMs} ) `); } return await rawRows<{ workspace_id: string; sandbox_group_id: string; instance_id: string | null; lease_epoch: number | string; }>( tx, sql` select workspace_id, sandbox_group_id, instance_id, lease_epoch from opengeni_private.reap_sandbox_leases( ${input.viewerHolderTtlMs}, ${input.turnHolderTtlMs ?? 0}, -- The legacy argument is intentionally zero: its timestamp branch -- includes healthy active controllers. Transitional expiry ran above. ${0}, ${input.idleGraceMs} ) `, ); }); const ordinary = rows.map((r) => ({ workspaceId: r.workspace_id, sandboxGroupId: r.sandbox_group_id, instanceId: r.instance_id, leaseEpoch: Number(r.lease_epoch), })); const reportContainmentError = input.onCommandContainmentError ?? ((error: unknown) => { console.warn("sandbox reaper: retained command containment inspection failed", error); }); const pushDrainable = (drainable: ReapDrainable) => { if ( !ordinary.some( (r) => r.workspaceId === drainable.workspaceId && r.sandboxGroupId === drainable.sandboxGroupId, ) ) ordinary.push(drainable); }; if (input.idleInteractionReleaseMs !== undefined) { // Before containment: a box whose idle browsers and desktops are released // here may be left with only legacy commands, which containment then sees. const idleLeases = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; }>( db, sql`select * from opengeni_private.list_idle_interaction_leases( 32, ${input.idleInteractionReleaseMs}::bigint)`, ).catch((error) => { reportContainmentError(error); return []; }); for (const candidate of idleLeases) { const release = await releaseIdleInteractionHolders(db, { accountId: candidate.account_id, workspaceId: candidate.workspace_id, sandboxGroupId: candidate.sandbox_group_id, idleMs: input.idleInteractionReleaseMs, browserCheckpoints: input.idleBrowserCheckpoints === true, }).catch((error: unknown) => { reportContainmentError(error); input.onIdleInteractionRelease?.("inspection_failed"); return undefined; }); if (release === undefined) continue; input.onIdleInteractionRelease?.( !release ? "not_eligible" : release.checkpoints > 0 ? "checkpointing" : "released", ); if (release?.drainable) pushDrainable(release.drainable); } } { // An idle-saved browser whose box went away before its local cleanup ran // keeps a durable profile; clear only the stale controller so it resumes. // Always on, so browsers saved before idle release was disabled resume. const orphaned = await rawRows<{ account_id: string; workspace_id: string; browser_session_id: string; controller_generation: string; }>(db, sql`select * from opengeni_private.list_orphaned_idle_browser_checkpoints(32)`).catch( (error) => { reportContainmentError(error); return []; }, ); for (const browser of orphaned) { await clearSuspendedBrowserSessionController(db, { accountId: browser.account_id, workspaceId: browser.workspace_id, browserSessionId: browser.browser_session_id, expectedControllerGeneration: browser.controller_generation, }).catch((error: unknown) => { // Ended, deleted or already cleared since the inventory: nothing to do. if ( error instanceof BrowserSessionNotFoundError || error instanceof BrowserSessionStateError || error instanceof BrowserSessionOperationConflictError ) return; reportContainmentError(error); }); } } const candidates = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; }>( db, sql`select * from opengeni_private.list_command_containment_candidates( 32, ${input.idleCommandContainmentMs ?? null}::bigint)`, ).catch((error) => { reportContainmentError(error); return []; }); for (const candidate of candidates) { const enrolled = await enrollRetainedCommandContainment(db, { accountId: candidate.account_id, workspaceId: candidate.workspace_id, sandboxGroupId: candidate.sandbox_group_id, ...(input.idleCommandContainmentMs === undefined ? {} : { idleCommandContainmentMs: input.idleCommandContainmentMs }), ...(input.deadlineMandatoryCaptureLeadMs === undefined ? {} : { deadlineMandatoryCaptureLeadMs: input.deadlineMandatoryCaptureLeadMs }), }).catch((error: unknown) => { reportContainmentError(error); input.onCommandContainment?.("inspection_failed"); return undefined; }); if (enrolled === undefined) continue; input.onCommandContainment?.(enrolled ? `${enrolled.mode}_enrolled` : "not_eligible"); if (enrolled) pushDrainable({ workspaceId: enrolled.workspaceId, sandboxGroupId: enrolled.sandboxGroupId, instanceId: enrolled.instanceId, leaseEpoch: enrolled.leaseEpoch, }); } return ordinary; } // §2.2 (global) — the warm-meter read for the REAPER tick (P2.1). Returns one row // per WARM viewer-only group (turn-held boxes are metered by the turn heartbeat, // so they are EXCLUDED here — no double-meter). Cross-workspace via the // SECURITY-DEFINER list fn (FORCE RLS would hide other workspaces from the scoped // connection). DB-only read; the worker accrues per row via accrueWarmSeconds. export interface MeterableWarmLease { accountId: string; workspaceId: string; sandboxGroupId: string; leaseEpoch: number; backend: string; } export async function listMeterableWarmLeases(db: Database): Promise { const rows = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; lease_epoch: number | string; backend: string; }>( db, sql` select account_id, workspace_id, sandbox_group_id, lease_epoch, backend from opengeni_private.list_meterable_warm_leases() `, ); return rows.map((r) => ({ accountId: r.account_id, workspaceId: r.workspace_id, sandboxGroupId: r.sandbox_group_id, leaseEpoch: Number(r.lease_epoch), backend: r.backend, })); } /** Workspaces whose durable viewer-drain admission intent must be reevaluated * even after every affected sandbox lease has become cold. */ export async function listSandboxViewerForceDrainWorkspaceIds(db: Database): Promise { const rows = await rawRows<{ workspace_id: string }>( db, sql`select workspace_id from opengeni_private.list_sandbox_viewer_force_drain_workspaces()`, ); return rows.map((row) => row.workspace_id); } export async function countQueuedTurns(db: Database): Promise { const rows = await rawRows<{ count: number | string }>( db, sql` select opengeni_private.count_queued_turns() as count `, ); return Number(rows[0]?.count ?? 0); } export type SessionRecoveryBacklogState = "quiescence_missing" | "projection_stale"; export async function countSessionRecoveryBacklog( db: Database, ): Promise> { const counts: Record = { quiescence_missing: 0, projection_stale: 0, }; const rows = await rawRows<{ state: SessionRecoveryBacklogState; count: number | string; }>( db, sql` select state, count from opengeni_private.count_session_recovery_backlog() `, ); for (const row of rows) { if (row.state in counts) counts[row.state] = Number(row.count); } return counts; } export type SessionRecoveryBacklogStateSummary = { /** Every candidate in this state (the same set countSessionRecoveryBacklog counts). */ count: number; /** Candidates still inside the backoff their recovery request recorded. */ scheduled: number; /** How long the single oldest candidate has been past its due time; 0 when none is. */ oldestOverdueSeconds: number; }; /** * Content-free cross-workspace recovery summary (migration 0633). A recovery * is due at its exact attempt's close plus the continueDelayMs recorded on that * attempt's turn.recovery.requested event, so a session sleeping in provider * Retry-After or connectivity backoff is `scheduled`, not overdue. */ export async function summarizeSessionRecoveryBacklog( db: Database, ): Promise> { const summary: Record = { quiescence_missing: { count: 0, scheduled: 0, oldestOverdueSeconds: 0 }, projection_stale: { count: 0, scheduled: 0, oldestOverdueSeconds: 0 }, }; const rows = await rawRows<{ state: SessionRecoveryBacklogState; count: number | string; scheduled: number | string; oldest_overdue_seconds: number | string; }>( db, sql` select state, count, scheduled, oldest_overdue_seconds from opengeni_private.summarize_session_recovery_backlog() `, ); for (const row of rows) { if (!(row.state in summary)) continue; summary[row.state] = { count: Number(row.count), scheduled: Number(row.scheduled), oldestOverdueSeconds: Number(row.oldest_overdue_seconds), }; } return summary; } /** What currently holds a durable queued turn, from its session's own state. */ export const QUEUED_TURN_HOLDS = [ "ready", "behind_active_turn", "paused", "failed", "requires_action", "waiting_capacity", "cancelled", ] as const; export type QueuedTurnHold = (typeof QUEUED_TURN_HOLDS)[number]; export type QueuedTurnHoldSummary = { count: number; /** Age of the oldest queued turn in this class; 0 when the class is empty. */ oldestAgeSeconds: number; }; /** * Content-free cross-workspace classification of every `status = 'queued'` * turn by what holds it (migration 0988). The classes sum to * {@link countQueuedTurns}. Only `ready` prompts are waiting for dispatch; * the rest wait for a running turn, Resume, a new message, or a person. * * 0988 created the routine with its runtime EXECUTE withheld; 1274 grants it * and readiness requires it. */ export async function summarizeQueuedTurnsByHold( db: Database, ): Promise> { return (await summarizeTurnHolds(db)).queued; } /** * The providers whose turns park on the shared subscription core's capacity * waiter, in the order {@link summarizeTurnHolds} reports them. The same set * as `subscription_capacity_waiters`' provider check. */ export const CAPACITY_WAITING_TURN_PROVIDERS = [ "claude", "codex", "xai", ] as const satisfies readonly SubscriptionCoreWaiterProvider[]; export type CapacityWaitingTurnProvider = (typeof CAPACITY_WAITING_TURN_PROVIDERS)[number]; export type CapacityWaitingTurnSummary = { /** Turns parked on this provider's capacity that run as soon as it returns. */ count: number; /** Seconds since the oldest of them parked; 0 when none is parked. */ oldestAgeSeconds: number; }; /** The summary's row class for one provider's parked turns (migration 1485). */ const CAPACITY_WAIT_HOLD_PREFIX = "capacity_wait:"; /** * Content-free cross-workspace turn hold summary for the control worker, one * call to `opengeni_private.summarize_queued_turns_by_hold()`: * * - `queued`: every `queued` turn by what holds it (0988). * - `capacityWaiting`: the turns parked waiting for subscription capacity, by * provider (1485), counted exactly when the capacity reconcile would resume * them once capacity returns (live waiter, not paused or stopped, goal * unchanged). A parked turn is its session's active turn, so the queued * `waiting_capacity` class never counts it: that class is only the prompts * queued behind one. Before 1485 the function returns no such rows and every * provider reads 0. */ export async function summarizeTurnHolds(db: Database): Promise<{ queued: Record; capacityWaiting: Record; }> { const queued = Object.fromEntries( QUEUED_TURN_HOLDS.map((hold) => [hold, { count: 0, oldestAgeSeconds: 0 }]), ) as Record; const capacityWaiting = Object.fromEntries( CAPACITY_WAITING_TURN_PROVIDERS.map((provider) => [ provider, { count: 0, oldestAgeSeconds: 0 }, ]), ) as Record; const rows = await rawRows<{ hold: string; count: number | string; oldest_age_seconds: number | string; }>( db, sql` select hold, count, oldest_age_seconds from opengeni_private.summarize_queued_turns_by_hold() `, ); for (const row of rows) { const value = { count: Number(row.count), oldestAgeSeconds: Number(row.oldest_age_seconds) }; if (row.hold in queued) { queued[row.hold as QueuedTurnHold] = value; } else if (row.hold.startsWith(CAPACITY_WAIT_HOLD_PREFIX)) { const provider = row.hold.slice(CAPACITY_WAIT_HOLD_PREFIX.length); if (provider in capacityWaiting) { capacityWaiting[provider as CapacityWaitingTurnProvider] = value; } } } return { queued, capacityWaiting }; } /** The parked-turn half of {@link summarizeTurnHolds}. */ export async function summarizeCapacityWaitingTurns( db: Database, ): Promise> { return (await summarizeTurnHolds(db)).capacityWaiting; } export type ContextCompactionPendingSummary = { pendingCount: number; oldestStartedAt: Date | null; }; /** * Content-free cross-workspace projection of exact active attempts whose latest * automatic compaction landmark is still `started`. The trigger-maintained * private ledger survives turn-worker loss without exposing tenant identities. */ export async function getContextCompactionPendingSummary( db: Database, ): Promise { const rows = await rawRows<{ pending_count: number | string; oldest_started_at: Date | string | null; }>( db, sql` select pending_count, oldest_started_at from opengeni_private.context_compaction_pending_summary() `, ); const row = rows[0]; return { pendingCount: Number(row?.pending_count ?? 0), oldestStartedAt: row?.oldest_started_at == null ? null : new Date(row.oldest_started_at), }; } export async function countSandboxLeasesByLiveness( db: Database, ): Promise> { const counts: Record = { cold: 0, warming: 0, warm: 0, draining: 0, }; const rows = await rawRows<{ liveness: SandboxLeaseLiveness; count: number | string; }>( db, sql` select liveness, count from opengeni_private.count_sandbox_leases_by_liveness() `, ); for (const row of rows) { if (row.liveness in counts) { counts[row.liveness] = Number(row.count); } } return counts; } export type CreditBalanceByAccount = { accountId: string; balanceMicros: number; }; export async function listCreditBalancesByAccount(db: Database): Promise { const rows = await rawRows<{ account_id: string; balance_micros: number | string; }>( db, sql` select account_id, balance_micros from opengeni_private.credit_balance_by_account() `, ); return rows.map((row) => ({ accountId: row.account_id, balanceMicros: Number(row.balance_micros), })); } // Cross-workspace live Modal lease read for the provider-side orphan sweep. The // SECURITY DEFINER function is the sanctioned RLS bypass; see migration 0036. export async function listLiveModalSandboxLeaseAttributions( db: Database, ): Promise { const rows = await rawRows<{ lease_id: string; workspace_id: string; sandbox_group_id: string; instance_id: string | null; liveness: SandboxLeaseLiveness; }>( db, sql` select lease_id, workspace_id, sandbox_group_id, instance_id, liveness from opengeni_private.list_live_modal_sandbox_leases() `, ); return rows.map((r) => ({ leaseId: r.lease_id, workspaceId: r.workspace_id, sandboxGroupId: r.sandbox_group_id, instanceId: r.instance_id, liveness: r.liveness, })); } // §4.7 — explicit re-arm seam (D1). acquireLease already re-arms a draining // lease inline; this is the standalone version for callers that learn a holder // is wanted without going through acquireLease first. Expiry is only scan // eligibility: the durable capture/teardown claim is the point of no return. export async function reArmDrainingLease( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; leaseTtlMs: number; warmBilling?: AcquireLeaseInput["warmBilling"]; }, ): Promise<{ rearmed: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [lease] = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); if (!lease || lease.liveness !== "draining" || !hasRearmableWorkspace(lease)) { return { rearmed: false }; } const snapshot = warmBillingSnapshot(lease); if (lease.resume_state?.opengeniWarmBilling && !snapshot) { throw new Error("sandbox warm billing snapshot is invalid"); } const activeMode = input.warmBilling?.mode ?? snapshot?.mode ?? "usage_only"; if ( activeMode === "credits" && (snapshot ? snapshot.mode === "credits" && snapshot.rateMicrosPerSecond > 0 : input.warmBilling?.rateMicrosPerSecond !== undefined && input.warmBilling.rateMicrosPerSecond > 0) && ( await getSpendableCreditBalance( tx, input.accountId, undefined, undefined, undefined, await attributionBillingOrigin(tx, { accountId: input.accountId, workspaceId: input.workspaceId, attribution: snapshot?.attribution ?? null, }), ) ).balanceMicros <= 0 ) { throw new SandboxPaidComputeAdmissionError(input.workspaceId, input.sandboxGroupId); } if ( activeMode === "credits" && snapshot?.mode === "credits" && snapshot.rateMicrosPerSecond > 0 ) { const attribution = snapshot.attribution ?? { kind: "unknown" as const }; if (attribution.kind === "unknown") { throw new SandboxDebitAttributionUnavailableError( input.workspaceId, input.sandboxGroupId, ); } const refusal = await checkWorkspaceAllowance(tx, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: attribution.kind === "turn" || attribution.kind === "human" ? attribution.initiatingHumanSubjectId : null, }); if (refusal) throw Object.assign( new SandboxPaidComputeAdmissionError(input.workspaceId, input.sandboxGroupId), refusal, ); } const rows = await tx.execute<{ id: string }>(sql` update sandbox_leases set liveness = 'warm', -- Re-armed: whatever group end was requested did not happen. group_end_requested_at = null, -- The drain ended without a save; its failures do not carry over to -- the next drain (see sandboxDrainCaptureFallback). drain_capture_failures = 0, drain_capture_failure_epoch = null, drain_capture_first_failed_at = null, drain_capture_last_failed_at = null, resume_state = resume_state #- '{opengeniWarmBilling,stopChargeAt}', expires_at = now() + (${String(input.leaseTtlMs)} || ' milliseconds')::interval, updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'draining' and archive_capture_id is null and rotation_requested_at is null and ( (${providerlessLeaseBackendPredicateSql()} and instance_id is null) or ( instance_id is not null and case when coalesce( resume_state ->> ${OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD}, '' ) <> '' then resume_state ->> ${OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD} = instance_id and not (${legacyLeaseProviderIdentityConflictsSql()}) else ${legacyLeaseProviderIdentityMatchesSql()} and not (${legacyLeaseProviderIdentityConflictsSql()}) end ) ) returning id `); return { rearmed: rows.length > 0 }; }), ); } // §4.8 — the reaper's final teardown commit (D3). Called AFTER the caller issued // provider stop() on instance_id. The exact capture id is the durable teardown // claim: holder admission cannot re-arm after that claim is acquired, and a // recovered/replaced claim makes an older worker's final commit a no-op. The // liveness/refcount/epoch checks remain defense-in-depth for pre-claim races. export async function confirmDrainCold( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; /** Exact durable teardown ownership. Omission asserts that no claim exists; * a replaced, newly installed, or expired claim always fences this commit. */ expectedCaptureId?: string; /** Definitive provider NotFound before this drain could capture /workspace. * With no durable archive this must become typed unrecoverable, never a * clean cold lease that can expose an empty replacement. */ providerMissingBeforeCapture?: boolean; /** The backend's bound on how long a box reported missing could still * run, when it has one. Recorded as death proof on the loss. */ providerMaxRemainingLifetimeMs?: number | null; /** The idle window named in contained commands' agent notice. */ idleCommandContainmentMs?: number | undefined; /** The reaper stopped the exact provider box (or proved it gone) before * this commit. Only then may a crashed worker's orphaned request on it be * settled; a selfhosted machine or backend-less lease is never stopped. */ providerStopped?: boolean; /** With `providerMissingBeforeCapture`: the drain stopped the box itself * after its saves kept failing. Its failed capture can never publish late. */ captureAbandoned?: boolean; /** With `captureAbandoned`: the `sandbox.box.terminated` record telling * the people in the chat which changes were not saved (since the last * good save, `unsavedSince`). Appended in the same commit as the loss, so * a later restore of exactly that save never announces it again. */ captureAbandonedNotice?: { unsavedSince: string | null; payload: Record }; }, ): Promise<{ wentCold: boolean; /** The missing provider was an unpublished warming replacement: its loss * recorded no lost workspace (see `unpublishedWarmingLoss`). */ unpublishedProviderLost?: boolean; backgroundCommandEvents?: SessionEvent[]; /** Committed wakes of sessions waiting on those commands. */ backgroundCommandWakes?: SessionWorkflowWake[]; /** With `captureAbandoned`: a save of this exact claim had published after * all, before this commit. It committed an ordinary saved teardown instead: * no loss, no notice. Carries the save the box now restores from. */ capturePublishedBeforeStop?: { archiveRevision: string | null; omittedPaths?: string[] }; }> { const backgroundCommandEvents: SessionEvent[] = []; const backgroundCommandWakes: SessionWorkflowWake[] = []; // Settling a command appends its terminal session event and agent input, so // the cold commit runs inside the session activity gate. const result = await withLostProviderCommandSessionRetry(async () => { backgroundCommandEvents.length = 0; backgroundCommandWakes.length = 0; return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { // draining->cold: the box is terminated, so EVERY live-box field is cleared // (instance_id / data-plane URLs). resume_state, however, is NOT blindly // nulled — if the reaper PERSISTED a /workspace snapshot onto it // (persistDrainSnapshot folds the archive at resume_state.sessionState. // workspaceArchive BEFORE this CAS, in the SAME sweep), nulling it here would // immediately destroy the snapshot the next cold-restore must replay — the // file-persistence bug. So we PRESERVE a MINIMAL archive-only envelope // `{ backendId, sessionState: { workspaceArchive } }` (dropping the dead box's // providerState/sandboxId — the box is gone, resume-by-id would only fail) and // KEEP resume_backend_id so cold-restore knows which client to hydrate with. // No archive (a non-persisted drain, or a 'none'/tar config that stored none) // -> resume_state is nulled as before. The archive then rides the COLD lease's // resume_state until the next spawner reads + hydrates it; it is re-superseded // (GC'd) on the next drain and finally cleared on workspace teardown. const observedRows = await tx.execute(sql` select *, (reaper_hold_id is not null and reaper_hold_until > now()) as reaper_hold_active from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} `); const observed = observedRows[0]; if ( !observed || observed.liveness !== "draining" || observed.reaper_hold_active || (observed.refcount !== 0 && !observed.unobservable_command_drain_ids?.length) || Number(observed.lease_epoch) !== input.expectedEpoch || observed.archive_capture_id !== (input.expectedCaptureId ?? null) ) { return { wentCold: false }; } // A save of this exact claim that published before the stop makes this // an ordinary saved teardown (decided under the lease lock below). The // blocker decisions taken before that lock use the same effective // truth, so a stopped box whose save landed keeps its supervised // commands to their own supervision, like any saved teardown. const observedPublishedBeforeStop = input.captureAbandoned === true && observed.archive_capture_published_at !== null; const observedProviderMissing = input.providerMissingBeforeCapture === true && !observedPublishedBeforeStop; // The box is stopped (or proven gone) before this commit, and the cold // commit retires its epoch for good. Every open blocker it leaves on // that exact box can therefore never progress: a request a crashed // worker left behind (the capture ran around it), a request of an // attempt that already recorded quiescence, a deadline-forced request, // or an unheld process (with its terminals). // Settle them all here with the exact provider blockers. Left open on // an old epoch they would pin their attempt's quiescence, and with it // the session, forever. A selfhosted machine or backend-less lease is // never stopped by a drain and keeps its rows. A supervised command // settles as lost only with the missing-provider truth (0496), so a // stopped box keeps it to its own supervision path. const staleBlockers = observed.instance_id && (input.providerStopped === true || observedProviderMissing) ? await rawRows<{ present: boolean }>( tx, sql` select ( exists ( select 1 from sandbox_workspace_mutation_admissions admission where admission.lease_id = ${observed.id} and admission.lease_epoch = ${input.expectedEpoch} and admission.provider_backend = ${observed.backend} and admission.provider_instance_id = ${observed.instance_id} and admission.settled_at is null ) or exists ( select 1 from sandbox_pty_sessions pty where pty.lease_id = ${observed.id} and pty.lease_epoch = ${input.expectedEpoch} and pty.provider_backend = ${observed.backend} and pty.provider_instance_id = ${observed.instance_id} and pty.status = 'open' ) or exists ( select 1 from sandbox_retained_processes process where process.lease_id = ${observed.id} and process.lease_epoch = ${input.expectedEpoch} and process.provider_backend = ${observed.backend} and process.provider_instance_id = ${observed.instance_id} and process.state = 'active' ) ) and ( ${observedProviderMissing} or not exists ( select 1 from sandbox_retained_processes supervised where supervised.lease_id = ${observed.id} and supervised.lease_epoch = ${input.expectedEpoch} and supervised.provider_backend = ${observed.backend} and supervised.provider_instance_id = ${observed.instance_id} and supervised.state = 'active' and supervised.provider_command ? 'supervision' ) ) as present `, ) : []; const blockerScope = (observedProviderMissing || observed.unobservable_command_drain_ids?.length || observed.deadline_forced_admission_ids?.length || staleBlockers[0]?.present === true) && observed.instance_id ? { accountId: input.accountId, workspaceId: input.workspaceId, leaseId: observed.id, sandboxGroupId: input.sandboxGroupId, lostEpoch: input.expectedEpoch, lostBackend: observed.backend, lostInstanceId: observed.instance_id, } : null; // Provider loss settles process/admission/PTY rows before taking the // lease lock, matching the canonical session -> blocker -> lease lock // order used by retained-process settlement. Revalidate the lease after // locking the entire exact provider-owned blocker set. // A box the drain stopped itself tells every member session in this // commit (below). Appending locks the workspace and those session rows, // so take them here, before any blocker or the lease, in the canonical // order; the append then finds them already held. const abandonedNoticeSessionIds = input.captureAbandoned === true && input.captureAbandonedNotice ? await withCompleteSandboxGroupScope(tx, async () => ( await tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.sandboxGroupId, input.sandboxGroupId), ), ) .orderBy(asc(schema.sessions.id)) ).map((session) => session.id), ) : []; let lockedCommandSessions: ReadonlySet = new Set(); if (blockerScope) { lockedCommandSessions = abandonedNoticeSessionIds.length > 0 ? await withCompleteSandboxGroupScope(tx, () => lockLostProviderCommandSessionsTx(tx, blockerScope, abandonedNoticeSessionIds), ) : await lockLostProviderCommandSessionsTx(tx, blockerScope); await lockExactLostProviderWorkspaceBlockersTx(tx, blockerScope); } else if (abandonedNoticeSessionIds.length > 0) { await withCompleteSandboxGroupScope(tx, () => lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: abandonedNoticeSessionIds, }), ); } const locked = await tx.execute(sql` select *, (reaper_hold_id is not null and reaper_hold_until > now()) as reaper_hold_active from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = locked[0]; if ( !row || row.id !== observed.id || row.liveness !== "draining" || row.reaper_hold_active || (row.refcount !== 0 && !row.unobservable_command_drain_ids?.length) || Number(row.lease_epoch) !== input.expectedEpoch || row.archive_capture_id !== (input.expectedCaptureId ?? null) || (blockerScope && row.instance_id !== blockerScope.lostInstanceId) || (blockerScope && row.backend !== blockerScope.lostBackend) ) { return { wentCold: false }; } // The drain stopped the box because its save had not published, but // a slow save of this exact claim can land between that decision and // the stop (or report an error after its store committed). The claim // is still ours (checked above), so a publication on it is this box's // save: commit an ordinary saved teardown. The decision is final here, // under the lease lock; nothing can publish on the claim after it. const capturePublishedBeforeStop = input.captureAbandoned === true && row.archive_capture_published_at !== null; if (capturePublishedBeforeStop !== observedPublishedBeforeStop) { // The save published between the unlocked read and the lock: the // blocker set above was decided on the other outcome. Retry. throw new LostProviderCommandSessionsChangedError( "drain capture published while the cold commit locked its blockers", ); } const providerMissingBeforeCapture = input.providerMissingBeforeCapture === true && !capturePublishedBeforeStop; const captureAbandoned = input.captureAbandoned === true && !capturePublishedBeforeStop; if (blockerScope) { // Enrolled commands are contained only when this drain published the // current checkpoint before stopping the box; otherwise the truthful // reason is provider loss and no saved-workspace claim is made. // A pre-0547 enrollment records no reason: settle it as plain loss. const reason = row.command_containment_reason; const contained = !providerMissingBeforeCapture && row.archive_capture_published_at !== null && (reason === IDLE_COMMAND_CONTAINMENT_REASON || reason === DEADLINE_COMMAND_CONTAINMENT_REASON || reason === QUIESCENCE_COMMAND_CONTAINMENT_REASON) && row.unobservable_command_drain_ids?.length ? row.unobservable_command_drain_ids : []; await assertLostProviderCommandSessionsLockedTx(tx, blockerScope, lockedCommandSessions); await settleExactLostProviderWorkspaceBlockersTx(tx, blockerScope, { containment: { processIds: contained, reason: typeof reason === "string" ? reason : LOST_PROVIDER_PROCESS_REASON, }, deliverCommandResults: { activityTx: tx, idleContainmentMinutes: input.idleCommandContainmentMs === undefined ? null : Math.max(1, Math.round(input.idleCommandContainmentMs / 60_000)), events: backgroundCommandEvents, wakes: backgroundCommandWakes, }, }); } const current = recoveryStateFromLeaseRow(row); const hasArchive = current.archive.status !== "none"; const archiveComplete = hasCompleteWorkspaceArchive(row); const now = new Date().toISOString(); // A warming replacement whose creator died (worker shutdown/crash) // before commitWarmingToWarm was never published: no holder attached // to it and no workspace mutation can be admitted on a non-warm lease. // The reaper's warming-death drain (c2) is the only way such a box // reaches here. Its disappearance therefore loses nothing beyond what // the pre-warming cold row already recorded; mirror failWarmingToCold // instead of minting a lost-workspace verdict that would block every // later turn of the session. A published box keeps the loss contract. const unpublishedWarmingLoss = providerMissingBeforeCapture && current.provider.status === "creating" && current.provider.instanceId !== null && current.provider.instanceId === row.instance_id; const workspaceLost = providerMissingBeforeCapture && !unpublishedWarmingLoss; const lateArchiveCapture = workspaceLost && !captureAbandoned && row.archive_capture_id !== null && // A warm claim that ran around commands may predate their writes; a // late adoption would publish it as the complete workspace. row.archive_capture_concurrent_capture_id !== row.archive_capture_id && row.archive_capture_provider_request_id !== null && row.archive_capture_generation !== null && row.archive_capture_published_at === null && row.instance_id !== null ? { version: 1 as const, captureId: row.archive_capture_id, providerRequestId: row.archive_capture_provider_request_id, sourceLeaseId: row.id, sourceLeaseEpoch: Number(row.lease_epoch), sourceInstanceId: row.instance_id, sourceWorkspaceGeneration: Number(row.archive_capture_generation), recordedAt: now, } : null; // A pending empty-workspace decision whose box drained before warm // publication stays a blocked lost workspace, never a clean new lease. const freshPending = pendingFreshWorkspaceRecovery(row.resume_state) !== null; // A missing Docker container is not a missing workspace: its owned host // directory is the durable resource. Keep the same continuity receipt // markWarmLeaseInstanceLost keeps, so the elected next owner restarts a // container on that exact directory (or reattaches one a false NotFound // missed) instead of the lineage being declared lost. const continuity = workspaceLost ? dockerContinuityRecoveryFromLeaseRow(row, row.instance_id) : null; const restoreStatus: SandboxRestoreStatus = continuity || (current.archive.status === "available" && archiveComplete) ? "pending" : hasArchive ? "degraded" : workspaceLost || freshPending ? "unrecoverable" : "not_required"; const recovery: SandboxRecoveryState = { provider: unpublishedWarmingLoss ? { // Same shape failWarmingToCold records for a failed replacement: // proves nothing about the workspace, never a loss record. status: "not_created", instanceId: row.instance_id, observedAt: now, diagnostic: REPLACEMENT_FAILED_DIAGNOSTIC, } : { status: workspaceLost ? "missing" : "not_created", instanceId: workspaceLost ? row.instance_id : null, observedAt: now, ...(workspaceLost ? { diagnostic: "provider_not_found_before_workspace_capture" } : {}), }, archive: current.archive, restore: { status: restoreStatus, rematerializationId: null, selectedRevision: current.archive.current?.revision ?? null, startedAt: null, completedAt: now, ...(restoreStatus === "degraded" ? { failureCode: current.archive.status === "available" ? "archive_generation_mismatch" : "archive_unverified", retryable: false, } : restoreStatus === "unrecoverable" ? { failureCode: "archive_unavailable", retryable: false } : {}), }, workspace: { status: restoreStatus === "pending" ? "not_ready" : restoreStatus === "degraded" ? "degraded" : restoreStatus === "unrecoverable" ? "unrecoverable" : "unknown", verifiedRevision: null, verifiedAt: null, }, ...(lateArchiveCapture ? { lateArchiveCapture } : {}), ...(continuity ? { continuity } : {}), }; const preserveRecovery = hasArchive || restoreStatus === "unrecoverable" || continuity !== null; const resumeStateJson = preserveRecovery ? JSON.stringify( recoveryResumeState( row, recovery, workspaceLost ? { ...providerLossRecordForLostRow( row, "drain_probe", now, input.providerMaxRemainingLifetimeMs, ), ...(captureAbandoned ? { captureAbandoned: true as const, ...(input.captureAbandonedNotice ? { unsavedSince: input.captureAbandonedNotice.unsavedSince } : {}), } : {}), } : undefined, ), ) : null; // Migration 0184 also enforces exact teardown ownership at the table // boundary so a pre-0184 confirm cannot erase a newer worker's claim. // Set the receipt transaction-locally only after the locked row passed // every CAS guard; the trigger compares it with OLD.archive_capture_id. if (input.expectedCaptureId) { await tx.execute( sql`select set_config('opengeni.sandbox_drain_capture_id', ${input.expectedCaptureId}, true)`, ); } const rows = await tx.execute<{ id: string }>(sql` update sandbox_leases set liveness = 'cold', instance_id = null, data_plane_url = null, terminal_data_plane_url = null, controller_data_plane_url = null, lease_epoch = lease_epoch + 1, reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, resume_state = ${resumeStateJson}::jsonb, resume_backend_id = case when ${preserveRecovery} then coalesce(resume_backend_id, backend) else null end, provider_created_at = null, provider_deadline_at = null, rotation_requested_at = null, group_end_requested_at = null, compute_asleep_since = null, compute_handing_off_since = null, rotation_reason = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, updated_at = now() where id = ${row.id} and liveness = 'draining' and refcount = 0 and lease_epoch = ${input.expectedEpoch} and (reaper_hold_id is null or reaper_hold_until <= now()) and archive_capture_id is not distinct from ${input.expectedCaptureId ?? null}::uuid returning id `); if (rows.length > 0 && workspaceLost) { const eventId = crypto.randomUUID(); await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { id: eventId, accountId: input.accountId, workspaceId: input.workspaceId, subjectId: "opengeni:sandbox-reaper", action: "sandbox.provider_missing_before_capture", targetType: "sandbox_group", targetId: input.sandboxGroupId, metadata: { leaseId: row.id, leaseEpoch: input.expectedEpoch, workspaceGeneration: Number(row.workspace_generation), archiveGeneration: row.archive_generation === null ? null : Number(row.archive_generation), }, }, "metadata", "metadataCodecVersion", ), ); await tx.execute(sql`select opengeni_private.record_sandbox_recovery_operator_event( ${eventId}::uuid, 'provider_missing_before_capture')`); } if (rows.length > 0 && workspaceLost && captureAbandoned && input.captureAbandonedNotice) { const notice = input.captureAbandonedNotice; await withCompleteSandboxGroupScope(tx, () => appendSessionEventToSandboxGroup(tx, input.workspaceId, input.sandboxGroupId, { type: "sandbox.box.terminated", payload: notice.payload, }), ); } if (rows.length > 0 && row.rotation_requested_at !== null) { await wakeSandboxLifecycleWaitersTx(tx, input); } return { wentCold: rows.length > 0, ...(rows.length > 0 && unpublishedWarmingLoss ? { unpublishedProviderLost: true } : {}), ...(rows.length > 0 && capturePublishedBeforeStop ? { capturePublishedBeforeStop: { archiveRevision: current.archive.current?.revision ?? null, ...(current.archive.current?.version === 1 && current.archive.current.omittedPaths?.length ? { omittedPaths: [...current.archive.current.omittedPaths] } : {}), }, } : {}), }; }, ); }); return backgroundCommandEvents.length ? { ...result, backgroundCommandEvents, ...(backgroundCommandWakes.length ? { backgroundCommandWakes } : {}), } : result; } // §4.8b — persist the /workspace snapshot archive onto the lease BEFORE the // reaper terminates a drained box (sandbox-file-persistence). The reaper, after // resuming the live box and capturing `session.persistWorkspace()` (a base64 // snapshot-ref / tar archive), CAS-folds it onto the lease's resume_state under // the SAME epoch fence confirmDrainCold uses (draining AND refcount=0 AND // lease_epoch=expected). Folding it into resume_state.sessionState.workspaceArchive // means a later cold-restore (establishSandboxSessionFromEnvelope) reads it back // off the same envelope it already deserializes. confirmDrainCold retains only // this archive/recovery projection after provider teardown, excluding stale live // provider state. // // When workspaceArchive is null this function acts as a PURE CAS-GATE: it checks // (draining AND refcount=0 AND epoch=expected) under a FOR UPDATE lock and returns // wrote:true/false WITHOUT writing anything. This is useful to prove that no // re-arm raced an external action, but it does not itself license deleting a // resumable cloud box without a verified capture. // // Returns `wrote:false` when the CAS missed (re-armed / newer epoch / vanished); // the caller must NOT terminate because the box is wanted again. Provider-native // object deletion is never returned to this caller: artifact-ledger GC owns it. // The fence is the split-brain guard: a stale-epoch reaper writes ZERO rows and // is told not to terminate. export class SandboxWorkspaceMutationFencedError extends Error { readonly name: string = "SandboxWorkspaceMutationFencedError"; constructor( public readonly code: | "attempt_fenced" | "holder_fenced" | "lease_fenced" // The lease still matches the writer's exact epoch/instance/backend, but // a provider-deadline/operator rotation was requested: new mutations are // fenced only until the current holders checkpoint and the cold // successor is elected. Distinct from `lease_fenced` (a genuine // epoch/instance/backend mismatch) so callers can hand the turn to the // orderly rotation path instead of treating the box as lost. | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" // The writer predates migration 0277 and therefore carries no recorded // authority. Nothing may invent one, so a NEW mutation is refused; the // live provider process behind it is deliberately left running. | "authority_unattributed" // The exact grant identity behind this writer is no longer active. | "authority_revoked", message: string, /** Remaining exact archive-capture budget projected by PostgreSQL. This is * observational wait input only; it never licenses capture takeover. */ public readonly captureRemainingMs: number | null = null, ) { super(message); } } /** An operation named a durable retained process that has already reached a * terminal state. This remains a fence—the provider must not be called again * and contradictory proof must not overwrite durable truth—but carries the * existing terminal result so routing can reconcile a concurrent settlement * or report completion/loss instead of presenting a retryable platform failure * for a handle that can never become active again. */ export class SandboxRetainedProcessTerminalError extends SandboxWorkspaceMutationFencedError { readonly name = "SandboxRetainedProcessTerminalError"; constructor( public readonly state: "exited" | "lost", public readonly exitCode: number | null, ) { super( "process_fenced", `Workspace mutation rejected because the retained process already ${state}`, ); } } export type SandboxWorkspaceMutationAdmission = { id: string; leaseId: string; sandboxGroupId: string; sessionId: string; actorKind: "turn" | "direct" | "process"; actorId: string; holderKind: "turn" | "direct" | "process"; holderId: string; leaseEpoch: number; providerBackend: string; providerInstanceId: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; workspaceGeneration: number; }; export type SandboxWorkspaceMutationProviderOutcome = "resolved" | "rejected"; /** Evidence from a committed exact admission settlement. It establishes the * physical provider outcome only; mutable output authority remains rejected. */ export type SandboxWorkspaceMutationPhysicalSettlement = Readonly<{ accountId: string; workspaceId: string; admission: Readonly; operation: string; outcome: "resolved"; }>; /** Durable terminal truth of the retained process whose concurrent settlement * fenced a physically settled mutation's output. */ export type SandboxRetainedProcessTerminalState = Readonly<{ state: "exited" | "lost"; exitCode: number | null; }>; /** The exact provider outcome committed before its output failed an acceptance * fence. A generic admission fence or failed transaction carries no receipt. * This error never authorizes accepting output or replaying provider work. */ export class SandboxWorkspaceMutationOutputRejectedError extends SandboxWorkspaceMutationFencedError { readonly name = "SandboxWorkspaceMutationOutputRejectedError"; readonly physicalSettlement: SandboxWorkspaceMutationPhysicalSettlement; /** Non-null only when the fence was the retained process itself having * already reached a durable terminal state (for example the reaper settled * the exit between admission and settlement). The output stays rejected; * callers may report this stored terminal truth instead of failing. */ readonly retainedProcessTerminal: SandboxRetainedProcessTerminalState | null; constructor( code: SandboxWorkspaceMutationFencedError["code"], message: string, physicalSettlement: SandboxWorkspaceMutationPhysicalSettlement, retainedProcessTerminal: SandboxRetainedProcessTerminalState | null = null, ) { super(code, message); this.physicalSettlement = Object.freeze({ ...physicalSettlement, admission: Object.freeze({ ...physicalSettlement.admission }), }); this.retainedProcessTerminal = retainedProcessTerminal ? Object.freeze({ state: retainedProcessTerminal.state, exitCode: retainedProcessTerminal.exitCode, }) : null; } matchesPhysicalSettlement(input: { accountId: string; workspaceId: string; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }): boolean { return isDeepStrictEqual(this.physicalSettlement, input); } } export type SandboxRetainedProcessState = "active" | "exited" | "lost"; export type SandboxRetainedProcess = { id: string; accountId: string; workspaceId: string; sessionId: string; leaseId: string; sandboxGroupId: string; parentAdmissionId: string; holderId: string; ownerActorKind: "turn" | "direct"; ownerActorId: string; ownerTurnId: string | null; ownerAttemptId: string | null; ownerExecutionGeneration: number | null; leaseEpoch: number; providerBackend: string; providerInstanceId: string; providerBindingKey: string | null; providerBinding: ModalCheckpointProviderBinding | null; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; providerSessionId: number; state: SandboxRetainedProcessState; exitCode: number | null; settlementReason: string | null; startedAt: string; settledAt: string | null; reconcileAfter: string; reconcileClaimId: string | null; reconcileClaimedAt: string | null; reconcileAttempts: number; lastReconcileOutcome: string | null; cancellationRequestedAt: string | null; cancellationReason: string | null; deadlineCancellationRequestedAt: string | null; reconcileProofOutcome: "exited" | "lost" | null; reconcileProofExitCode: number | null; reconcileProofReason: | "provider_exit_banner" | "provider_session_lost_banner" | "provider_instance_not_found" | "provider_instance_terminated" | null; reconcileProofObservedAt: string | null; }; export type RetainedProcessProviderProof = | { outcome: "exited"; exitCode: number; reason: "provider_exit_banner" } | { outcome: "lost"; exitCode: null; reason: | "provider_session_lost_banner" | "provider_instance_not_found" | "provider_instance_terminated"; }; export type SandboxRetainedProcessIdentity = Pick< SandboxRetainedProcess, | "leaseId" | "sandboxGroupId" | "parentAdmissionId" | "holderId" | "leaseEpoch" | "providerBackend" | "providerInstanceId" | "routeKind" | "routeTargetId" | "routeEpoch" | "providerSessionId" >; export type SandboxRetainedProcessReconciliationClaim = { process: SandboxRetainedProcess; claimId: string; ownerState: string; ownerAttemptOutcome: string | null; }; export type ActiveRetainedProcessOwnerCount = { ownerState: string; activeCount: number; terminalOwnerCount: number; }; export type ExpiredDrainingSandboxLeaseCount = { backend: string; ageBucket: "lt_5m" | "5m_1h" | "1h_1d" | "gte_1d"; count: number; }; export function retainedProcessSettlementIdentity( process: SandboxRetainedProcess, ): SandboxRetainedProcessIdentity { return { leaseId: process.leaseId, sandboxGroupId: process.sandboxGroupId, parentAdmissionId: process.parentAdmissionId, holderId: process.holderId, leaseEpoch: process.leaseEpoch, providerBackend: process.providerBackend, providerInstanceId: process.providerInstanceId, routeKind: process.routeKind, routeTargetId: process.routeTargetId, routeEpoch: process.routeEpoch, providerSessionId: process.providerSessionId, }; } export function retainedProcessReconciliationProof( process: SandboxRetainedProcess, ): RetainedProcessProviderProof | null { if ( process.reconcileProofOutcome === "exited" && process.reconcileProofReason === "provider_exit_banner" && process.reconcileProofExitCode !== null ) { return { outcome: "exited", exitCode: process.reconcileProofExitCode, reason: "provider_exit_banner", }; } if ( process.reconcileProofOutcome === "lost" && (process.reconcileProofReason === "provider_session_lost_banner" || process.reconcileProofReason === "provider_instance_not_found" || process.reconcileProofReason === "provider_instance_terminated") ) { return { outcome: "lost", exitCode: null, reason: process.reconcileProofReason, }; } return null; } /** Durable promotion committed before a mutable route/turn authority check * rejected the provider output. The process identity is safe to hand to the * exact-backend cancellation path; callers must still reject the output and * must never replay the provider mutation. */ export class SandboxRetainedProcessPromotionFencedError extends SandboxWorkspaceMutationFencedError { readonly name = "SandboxRetainedProcessPromotionFencedError"; constructor( code: | "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "admission_fenced" | "authority_unattributed" | "authority_revoked", message: string, public readonly process: SandboxRetainedProcess, ) { super(code, message); } } type SandboxWorkspaceMutationSettlementResult = | { failure: null } | { failure: | "admission_fenced" | "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "authority_unattributed" | "authority_revoked"; detail: string; physicallySettled?: true; retainedProcessTerminal?: SandboxRetainedProcessTerminalState; }; type TurnWorkspaceMutationAuthority = { kind: "turn"; accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; holderId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch?: number; }; type DirectWorkspaceMutationAuthority = { kind: "direct"; accountId: string; workspaceId: string; sessionId: string; requestId: string; holderId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeKind: "active"; routeTargetId: string | null; routeEpoch: number; /** The exact authenticated principal that drove this API request. A direct * writer has no frozen turn snapshot, so this is its only causal identity and * it is required: an unattributed direct mutation is refused. */ initiatorSubjectId: string; }; /** Identity-and-epoch attribution recorded with an admitted workspace writer * (migration 0277). Never contains a secret value. */ type AdmittedWorkspaceMutationAuthority = { /** `legacy_unattributed` is honest, not broken: a turn frozen before * migration 0096 has no causal initiator to copy, and inventing one would be * exactly the ownership inference this authority model forbids. */ initiatorKind: "subject" | "service" | "legacy_unattributed"; initiatorSubjectId: string; initiatingHumanSubjectId: string | null; initiatorOrganizationMembershipId: string | null; initiatorAuthorizationRevision: number | null; authorityEpoch: number; authorityVisibility: "user_private" | "workspace_shared"; authorityOwnerOrganizationMembershipId: string | null; }; type ProcessWorkspaceMutationAuthority = { kind: "process"; accountId: string; workspaceId: string; sessionId: string; processId: string; }; type WorkspaceMutationAuthority = | TurnWorkspaceMutationAuthority | DirectWorkspaceMutationAuthority | ProcessWorkspaceMutationAuthority; type LockedWorkspaceMutationAuthority = { accountId: string; workspaceId: string; sessionId: string; sandboxGroupId: string; actorKind: "turn" | "direct" | "process"; actorId: string; turnId: string | null; attemptId: string | null; executionGeneration: number | null; holderKind: "turn" | "direct" | "process"; holderId: string; expectedLeaseId: string | null; expectedEpoch: number; expectedBackend: string | null; expectedInstanceId: string; routeKind: "home" | "active"; routeTargetId: string | null; routeEpoch: number; authority: AdmittedWorkspaceMutationAuthority; session: typeof schema.sessions.$inferSelect; retainedProcess: typeof schema.sandboxRetainedProcesses.$inferSelect | null; }; function normalizeWorkspaceMutationOperation(operation: string): string { const normalized = operation.trim(); const byteLength = new TextEncoder().encode(normalized).byteLength; if (byteLength < 1 || byteLength > 128) { throw new SandboxWorkspaceMutationFencedError( "operation_invalid", "Workspace mutation operation must contain between 1 and 128 UTF-8 bytes", ); } return normalized; } function normalizeRetainedProcessSettlementReason(reason: string): string { const normalized = reason.trim(); let bounded = ""; let bytes = 0; for (const character of normalized) { const characterBytes = Buffer.byteLength(character, "utf8"); if (bytes + characterBytes > 512) break; bounded += character; bytes += characterBytes; } if (bounded.length === 0) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process settlement requires a reason", ); } return bounded; } function normalizeRetainedProcessReconciliationOutcome(outcome: string): string { const normalized = outcome.trim(); const byteLength = Buffer.byteLength(normalized, "utf8"); if (byteLength < 1 || byteLength > 64) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process reconciliation outcome must contain between 1 and 64 UTF-8 bytes", ); } return normalized; } function mapWorkspaceMutationAdmission(row: { id: string; lease_id: string; sandbox_group_id: string; session_id: string; actor_kind: string; actor_id: string; holder_kind: string; holder_id: string; lease_epoch: number | string; provider_backend: string; provider_instance_id: string; route_kind: string; route_target_id: string | null; route_epoch: number | string; workspace_generation: number | string; }): SandboxWorkspaceMutationAdmission { return { id: row.id, leaseId: row.lease_id, sandboxGroupId: row.sandbox_group_id, sessionId: row.session_id, actorKind: row.actor_kind as SandboxWorkspaceMutationAdmission["actorKind"], actorId: row.actor_id, holderKind: row.holder_kind as SandboxWorkspaceMutationAdmission["holderKind"], holderId: row.holder_id, leaseEpoch: Number(row.lease_epoch), providerBackend: row.provider_backend, providerInstanceId: row.provider_instance_id, routeKind: row.route_kind as SandboxWorkspaceMutationAdmission["routeKind"], routeTargetId: row.route_target_id, routeEpoch: Number(row.route_epoch), workspaceGeneration: Number(row.workspace_generation), }; } function mapRetainedProcess( row: typeof schema.sandboxRetainedProcesses.$inferSelect, ): SandboxRetainedProcess { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, leaseId: row.leaseId, sandboxGroupId: row.sandboxGroupId, parentAdmissionId: row.parentAdmissionId, holderId: row.holderId, ownerActorKind: row.ownerActorKind as "turn" | "direct", ownerActorId: row.ownerActorId, ownerTurnId: row.ownerTurnId ?? null, ownerAttemptId: row.ownerAttemptId ?? null, ownerExecutionGeneration: row.ownerExecutionGeneration ?? null, leaseEpoch: row.leaseEpoch, providerBackend: row.providerBackend, providerInstanceId: row.providerInstanceId, providerBindingKey: row.providerBindingKey ?? null, providerBinding: row.providerBinding ? (canonicalModalCheckpointProviderBinding(row.providerBinding)?.binding ?? null) : null, routeKind: row.routeKind as "home" | "active", routeTargetId: row.routeTargetId ?? null, routeEpoch: row.routeEpoch, providerSessionId: row.providerSessionId, state: row.state as SandboxRetainedProcessState, exitCode: row.exitCode ?? null, settlementReason: row.settlementReason ?? null, startedAt: row.startedAt.toISOString(), settledAt: row.settledAt?.toISOString() ?? null, reconcileAfter: row.reconcileAfter.toISOString(), reconcileClaimId: row.reconcileClaimId ?? null, reconcileClaimedAt: row.reconcileClaimedAt?.toISOString() ?? null, reconcileAttempts: row.reconcileAttempts, lastReconcileOutcome: row.lastReconcileOutcome ?? null, cancellationRequestedAt: row.cancellationRequestedAt?.toISOString() ?? null, cancellationReason: row.cancellationReason ?? null, deadlineCancellationRequestedAt: row.deadlineCancellationRequestedAt?.toISOString() ?? null, reconcileProofOutcome: row.reconcileProofOutcome ?? null, reconcileProofExitCode: row.reconcileProofExitCode ?? null, reconcileProofReason: (row.reconcileProofReason as SandboxRetainedProcess["reconcileProofReason"]) ?? null, reconcileProofObservedAt: row.reconcileProofObservedAt?.toISOString() ?? null, }; } function retainedProcessMatchesSettlementIdentity( process: typeof schema.sandboxRetainedProcesses.$inferSelect, expected: SandboxRetainedProcessIdentity, ): boolean { return ( process.leaseId === expected.leaseId && process.sandboxGroupId === expected.sandboxGroupId && process.parentAdmissionId === expected.parentAdmissionId && process.holderId === expected.holderId && process.leaseEpoch === expected.leaseEpoch && process.providerBackend === expected.providerBackend && process.providerInstanceId === expected.providerInstanceId && process.routeKind === expected.routeKind && (process.routeTargetId ?? null) === expected.routeTargetId && process.routeEpoch === expected.routeEpoch && process.providerSessionId === expected.providerSessionId ); } async function lockWorkspaceMutationSessionTx( tx: Database, workspaceId: string, sessionId: string, ): Promise { const locks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions.find((row) => row.id === sessionId); if (!session) { throw new SandboxWorkspaceMutationFencedError( "attempt_fenced", "Workspace mutation rejected because its session no longer exists", ); } return session; } /** * False only when no attempt of the session can await its physical-quiescence * receipt (see `sessionMayAwaitQuiescenceSql`). It lets the hot peek and claim * paths skip the exact quiescence and writer queries, which cost tens of * milliseconds of planning on every call, for the sessions that have none of * their rows. */ async function sessionMayAwaitQuiescence( db: Database, scope: { workspaceId: string; sessionId: string }, ): Promise { const [row] = await db.execute<{ possible: boolean }>( sql`select ${sessionMayAwaitQuiescenceSql(scope)} as possible`, ); return row?.possible === true; } /** True while an exact closed attempt still owns the physical-quiescence gate. * Both user control interruptions and activity-owned recoverable shutdowns use * this predicate so wake delivery cannot turn an unfinished writer drain into * an acknowledged edge-trigger. */ async function hasPendingSessionAttemptQuiescenceTx( tx: Database, input: { workspaceId: string; sessionId: string; attemptId?: string; /** `containment` ignores crashed-worker orphan requests, which sandbox * containment and drains settle themselves after exact termination. */ writerMode?: "physical" | "containment"; }, ): Promise { if (!(await sessionMayAwaitQuiescence(tx, input))) return false; const [row] = await tx.execute<{ pending: boolean }>(sql` select exists ( select 1 from session_turn_attempts attempt where attempt.workspace_id = ${input.workspaceId} and attempt.session_id = ${input.sessionId} ${input.attemptId ? sql`and attempt.id = ${input.attemptId}` : sql``} and attempt.state = 'closed' and attempt.quiesced_at is null and attempt.id in ${sessionQuiescenceCandidateAttemptIdsSql(input)} and ( ${sessionAttemptPendingWritersSql(sql`attempt`, input.writerMode ?? "physical")} or exists ( select 1 from session_attempt_interruptions interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('settled', 'rejected_stale') ) or ( attempt.outcome = 'interrupted_recoverable' and not exists ( select 1 from session_turn_attempts successor where successor.account_id = attempt.account_id and successor.workspace_id = attempt.workspace_id and successor.session_id = attempt.session_id and ( successor.started_at > attempt.started_at or ( successor.started_at = attempt.started_at and successor.id > attempt.id ) ) ) and exists ( select 1 from session_events event where event.account_id = attempt.account_id and event.workspace_id = attempt.workspace_id and event.session_id = attempt.session_id and event.turn_id = attempt.turn_id and event.turn_attempt_id = attempt.id and event.type = 'turn.recovery.requested' ) ) ) ) as pending `); return row?.pending === true; } /** * Resolve the organization grant identity behind a causal human, and refuse the * operation when that grant has been revoked or suspended. * * `organization_memberships` is unique per (account, subject), so this is an * exact lookup and never a guess. A principal with no membership row at all is * not an organization human (deployment/API-key/local principals): it keeps its * subject attribution and carries no membership, because inventing one would be * exactly the ownership inference this authority model forbids. A `provisioning` membership * is not yet a grant and is likewise not recorded, but it is not a revocation * either and must not fence. */ async function resolveWorkspaceMutationGrantIdentityTx( tx: Database, input: { accountId: string; humanSubjectId: string | null }, ): Promise<{ membershipId: string | null; authorizationRevision: number | null; }> { if (!input.humanSubjectId) return { membershipId: null, authorizationRevision: null }; // `organization_memberships` has no runtime SELECT (0263). Migration 0277 // installs one narrow tenant-fenced SECURITY DEFINER seam that returns only // this identity/status/revision triple. const rows = await tx.execute<{ membership_id: string; membership_status: string; authorization_revision: number | string; }>(sql` select membership_id, membership_status, authorization_revision from resolve_workspace_writer_grant_identity( ${input.accountId}::uuid, ${input.humanSubjectId}::text ) `); const membership = rows[0]; if (!membership) return { membershipId: null, authorizationRevision: null }; if (membership.membership_status === "revoked" || membership.membership_status === "suspended") { throw new SandboxWorkspaceMutationFencedError( "authority_revoked", `Workspace mutation rejected because its organization grant is ${membership.membership_status}`, ); } if (membership.membership_status !== "active") { return { membershipId: null, authorizationRevision: null }; } return { membershipId: membership.membership_id, authorizationRevision: Number(membership.authorization_revision), }; } /** The initiator half, copied verbatim from the accepted turn. A turn frozen * before migration 0096 carries the subject sentinel with the default * `service` kind; that is honestly "no causal initiator", so it is normalized * to the explicit sentinel instead of being promoted to a real one. Turn work * is never refused for this - the attempt fence remains its authority - but * anything the turn retains inherits the honest absence. */ function frozenTurnInitiator( turn: typeof schema.sessionTurns.$inferSelect, ): Pick< AdmittedWorkspaceMutationAuthority, "initiatorKind" | "initiatorSubjectId" | "initiatingHumanSubjectId" > { const kind = turn.initiatorKind === "subject" ? "subject" : "service"; if (turn.initiatorSubjectId === "unattributed-legacy") { return { initiatorKind: "legacy_unattributed", initiatorSubjectId: "unattributed-legacy", initiatingHumanSubjectId: null, }; } return { initiatorKind: kind, initiatorSubjectId: turn.initiatorSubjectId, initiatingHumanSubjectId: turn.initiatingHumanSubjectId, }; } /** The tenancy half of the tuple, read from the exact locked session row. A * direct writer has no frozen snapshot, so the live session IS its authority - * which is also why the private-session owner check below runs here, inside the * same transaction that advances the generation. */ function directSessionAuthorityTx( session: typeof schema.sessions.$inferSelect, initiatorSubjectId: string, grant: { membershipId: string | null }, ): Pick< AdmittedWorkspaceMutationAuthority, "authorityEpoch" | "authorityVisibility" | "authorityOwnerOrganizationMembershipId" > { const visibility = session.visibility === "user_private" ? "user_private" : "workspace_shared"; if (visibility === "user_private") { const ownedBySubject = session.ownerSubjectId === initiatorSubjectId; const ownedByMembership = grant.membershipId !== null && session.ownerOrganizationMembershipId === grant.membershipId; if (!ownedBySubject && !ownedByMembership) { throw new SandboxWorkspaceMutationFencedError( "authority_revoked", "Direct workspace mutation rejected because the request no longer owns this private session", ); } if (!session.ownerOrganizationMembershipId) { throw new SandboxWorkspaceMutationFencedError( "authority_revoked", "Direct workspace mutation rejected because the private session has no owning membership", ); } } return { authorityEpoch: session.authorityEpoch, authorityVisibility: visibility, authorityOwnerOrganizationMembershipId: session.ownerOrganizationMembershipId, }; } async function lockWorkspaceMutationAuthorityTx( tx: Database, authority: WorkspaceMutationAuthority, ): Promise { if (authority.kind === "turn") { const fence = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: authority.workspaceId, sessionId: authority.sessionId, turnId: authority.turnId, executionGeneration: authority.executionGeneration, attemptId: authority.attemptId, }); if (!fence.allowed) { throw new SandboxWorkspaceMutationFencedError( "attempt_fenced", `Workspace mutation rejected by turn-attempt fence (${fence.reason})`, ); } if ( fence.session.accountId !== authority.accountId || fence.session.sandboxGroupId !== authority.sandboxGroupId ) { throw new SandboxWorkspaceMutationFencedError( "attempt_fenced", "Workspace mutation rejected because the turn session does not own the sandbox group", ); } const routeEpoch = authority.routeEpoch ?? fence.session.activeEpoch; if ( authority.routeKind === "active" && (fence.session.activeSandboxId !== authority.routeTargetId || fence.session.activeEpoch !== routeEpoch) ) { throw new SandboxWorkspaceMutationFencedError( "route_fenced", "Workspace mutation rejected because its active route moved before admission", ); } // The accepted turn already froze its causal initiator and tenancy tuple; // copy them verbatim so recovery, retry and continuation all record the // same authority. The grant identity below is the one live resolution: it // can fence a frozen human whose membership was since revoked or // suspended, matching the 0263 teardown that cancels work initiated by a // suspended subject. const turnInitiator = frozenTurnInitiator(fence.turn); const turnGrant = await resolveWorkspaceMutationGrantIdentityTx(tx, { accountId: authority.accountId, humanSubjectId: turnInitiator.initiatingHumanSubjectId, }); return { accountId: authority.accountId, workspaceId: authority.workspaceId, sessionId: authority.sessionId, sandboxGroupId: authority.sandboxGroupId, actorKind: "turn", actorId: authority.attemptId, turnId: authority.turnId, attemptId: authority.attemptId, executionGeneration: authority.executionGeneration, holderKind: "turn", holderId: authority.holderId, expectedLeaseId: null, expectedEpoch: authority.expectedEpoch, expectedBackend: null, expectedInstanceId: authority.expectedInstanceId, routeKind: authority.routeKind, routeTargetId: authority.routeKind === "home" ? null : authority.routeTargetId, routeEpoch, authority: { ...turnInitiator, initiatorOrganizationMembershipId: turnGrant.membershipId, initiatorAuthorizationRevision: turnGrant.authorizationRevision, authorityEpoch: fence.attempt.authorityEpoch, authorityVisibility: fence.attempt.authorityVisibility === "user_private" ? "user_private" : "workspace_shared", authorityOwnerOrganizationMembershipId: fence.attempt.authorityOwnerOrganizationMembershipId, }, session: fence.session, retainedProcess: null, }; } const session = await lockWorkspaceMutationSessionTx( tx, authority.workspaceId, authority.sessionId, ); if (session.accountId !== authority.accountId) { throw new SandboxWorkspaceMutationFencedError( "attempt_fenced", "Workspace mutation rejected because its session account changed", ); } if (authority.kind === "direct") { if (session.sandboxGroupId !== authority.sandboxGroupId) { throw new SandboxWorkspaceMutationFencedError( "attempt_fenced", "Direct workspace mutation rejected because the session does not own the sandbox group", ); } if ( session.activeSandboxId !== authority.routeTargetId || session.activeEpoch !== authority.routeEpoch ) { throw new SandboxWorkspaceMutationFencedError( "route_fenced", "Direct workspace mutation rejected because its active route moved before admission", ); } const initiatorSubjectId = authority.initiatorSubjectId.trim(); if (initiatorSubjectId.length === 0 || initiatorSubjectId === "unattributed-legacy") { throw new SandboxWorkspaceMutationFencedError( "authority_unattributed", "Direct workspace mutation rejected because it carries no causal initiator", ); } // A direct writer has no frozen snapshot, so its grant is re-proved here, // in the same transaction that advances the generation: a revocation // committed before this statement fences the operation instead of relying // on stale HTTP authorization. A revocation committing after this // lock-free read still races the admission commit; the recorded grant // identity and observed revision exist so the offboarding teardown and a // later revocation sweep can find and settle exactly those writers. const directGrant = await resolveWorkspaceMutationGrantIdentityTx(tx, { accountId: authority.accountId, humanSubjectId: initiatorSubjectId, }); const directTenancy = directSessionAuthorityTx(session, initiatorSubjectId, directGrant); return { accountId: authority.accountId, workspaceId: authority.workspaceId, sessionId: authority.sessionId, sandboxGroupId: authority.sandboxGroupId, actorKind: "direct", actorId: authority.requestId, turnId: null, attemptId: null, executionGeneration: null, holderKind: "direct", holderId: authority.holderId, expectedLeaseId: null, expectedEpoch: authority.expectedEpoch, expectedBackend: null, expectedInstanceId: authority.expectedInstanceId, routeKind: "active", routeTargetId: authority.routeTargetId, routeEpoch: authority.routeEpoch, authority: { initiatorKind: "subject", initiatorSubjectId, initiatingHumanSubjectId: directGrant.membershipId ? initiatorSubjectId : null, initiatorOrganizationMembershipId: directGrant.membershipId, initiatorAuthorizationRevision: directGrant.authorizationRevision, ...directTenancy, }, session, retainedProcess: null, }; } const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, authority.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, authority.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, authority.sessionId), eq(schema.sandboxRetainedProcesses.id, authority.processId), ), ) .for("update") .limit(1); if (!process) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Workspace mutation rejected because the retained process does not exist", ); } if (process.state !== "active") { throw new SandboxRetainedProcessTerminalError(process.state, process.exitCode); } if (process.cancellationRequestedAt || process.supervisionReceipt) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Workspace mutation rejected because retained command input is closed", ); } if (session.sandboxGroupId !== process.sandboxGroupId) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Workspace mutation rejected because the retained process scope is stale", ); } // A retained process outlives the request or turn that started it, so its // frozen authority is the only thing that can license a further write. It is // never re-derived: an unattributed (pre-0277) process is refused rather than // adopted, and the running provider process is deliberately left alone. const processAuthority = assertRetainedProcessAuthority(process); const processGrant = await resolveWorkspaceMutationGrantIdentityTx(tx, { accountId: authority.accountId, humanSubjectId: processAuthority.initiatingHumanSubjectId, }); if ( processAuthority.authorityEpoch < session.executionAuthorityEpoch || processAuthority.authorityEpoch > session.authorityEpoch || (processAuthority.authorityVisibility !== session.visibility && !( processAuthority.authorityVisibility === "user_private" && session.visibility === "workspace_shared" )) ) { throw new SandboxWorkspaceMutationFencedError( "authority_revoked", "Workspace mutation rejected because the retained process authority no longer matches its session", ); } return { accountId: authority.accountId, workspaceId: authority.workspaceId, sessionId: authority.sessionId, sandboxGroupId: process.sandboxGroupId, actorKind: "process", actorId: process.id, turnId: null, attemptId: null, executionGeneration: null, holderKind: "process", holderId: process.holderId, expectedLeaseId: process.leaseId, expectedEpoch: process.leaseEpoch, expectedBackend: process.providerBackend, expectedInstanceId: process.providerInstanceId, routeKind: process.routeKind as "home" | "active", routeTargetId: process.routeTargetId, routeEpoch: process.routeEpoch, authority: { ...processAuthority, // A frozen grant identity is never replaced. A process admitted before // its human's membership row existed may backfill it from the live // unique (account, subject) row - memberships are never deleted or // recreated, so the id cannot diverge from the frozen human - and the // observed revision refreshes because it is evidence, not a fence. initiatorOrganizationMembershipId: processAuthority.initiatorOrganizationMembershipId ?? processGrant.membershipId, initiatorAuthorizationRevision: processGrant.authorizationRevision ?? processAuthority.initiatorAuthorizationRevision, }, session, retainedProcess: process, }; } /** Read the frozen authority of a retained process, refusing a pre-0277 row. * The refusal is a write fence only: the caller never terminates the process. * * The MISSING TENANCY HALF is what marks a pre-0277 row. A recorded but * `legacy_unattributed` initiator is not the same thing: that process still has * a real session epoch and visibility to be fenced against, and refusing it * would fence ordinary work on sessions whose turns predate migration 0096. */ function assertRetainedProcessAuthority( process: typeof schema.sandboxRetainedProcesses.$inferSelect, ): AdmittedWorkspaceMutationAuthority { if (process.authorityEpoch === null || process.authorityVisibility === null) { throw new SandboxWorkspaceMutationFencedError( "authority_unattributed", "Workspace mutation rejected because the retained process predates recorded authority; " + "start a new command - the running process is untouched", ); } return { initiatorKind: process.initiatorKind, initiatorSubjectId: process.initiatorSubjectId, initiatingHumanSubjectId: process.initiatingHumanSubjectId, initiatorOrganizationMembershipId: process.initiatorOrganizationMembershipId, initiatorAuthorizationRevision: process.initiatorAuthorizationRevision, authorityEpoch: process.authorityEpoch, authorityVisibility: process.authorityVisibility, authorityOwnerOrganizationMembershipId: process.authorityOwnerOrganizationMembershipId, }; } async function advanceWorkspaceGenerationForAuthorityOnce( db: Database, authority: WorkspaceMutationAuthority, operationInput: string, ): Promise { const operation = normalizeWorkspaceMutationOperation(operationInput); return await withRlsContext( db, { accountId: authority.accountId, workspaceId: authority.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const locked = await lockWorkspaceMutationAuthorityTx(tx, authority); // Keep the admission UPDATE and its rejection diagnostic on one lease // state. A concurrent capture release between these READ COMMITTED // statements otherwise turns a recoverable capture wait into a false // lease_fenced error. Take this after the canonical actor/attempt prefix. await tx.execute(sql`select id from sandbox_leases where account_id = ${locked.accountId} and workspace_id = ${locked.workspaceId} and sandbox_group_id = ${locked.sandboxGroupId} for update`); const rows = await tx.execute<{ id: string; lease_id: string; sandbox_group_id: string; session_id: string; actor_kind: string; actor_id: string; holder_kind: string; holder_id: string; lease_epoch: number | string; provider_backend: string; provider_instance_id: string; route_kind: string; route_target_id: string | null; route_epoch: number | string; workspace_generation: number | string; }>(sql` with advanced as ( update sandbox_leases as lease set workspace_generation = lease.workspace_generation + 1, updated_at = now() from sandbox_lease_holders as holder where lease.account_id = ${locked.accountId} and lease.workspace_id = ${locked.workspaceId} and lease.sandbox_group_id = ${locked.sandboxGroupId} and lease.liveness = 'warm' and lease.rotation_requested_at is null and lease.archive_capture_id is null and lease.lease_epoch = ${locked.expectedEpoch} and lease.instance_id = ${locked.expectedInstanceId} and (${locked.expectedLeaseId}::uuid is null or lease.id = ${locked.expectedLeaseId}::uuid) and (${locked.expectedBackend}::text is null or lease.backend = ${locked.expectedBackend}::text) and lease.workspace_generation < 2147483647 and holder.lease_id = lease.id and holder.account_id = ${locked.accountId} and holder.workspace_id = ${locked.workspaceId} and holder.kind = ${locked.holderKind} and holder.holder_id = ${locked.holderId} and holder.subject_id = ${locked.sessionId} returning lease.id, lease.backend, lease.workspace_generation ) insert into sandbox_workspace_mutation_admissions ( account_id, workspace_id, lease_id, sandbox_group_id, session_id, actor_kind, actor_id, turn_id, attempt_id, execution_generation, holder_kind, holder_id, lease_epoch, provider_backend, provider_instance_id, route_kind, route_target_id, route_epoch, workspace_generation, operation, initiator_kind, initiator_subject_id, initiating_human_subject_id, initiator_organization_membership_id, initiator_authorization_revision, authority_epoch, authority_visibility, authority_owner_organization_membership_id ) select ${locked.accountId}, ${locked.workspaceId}, advanced.id, ${locked.sandboxGroupId}, ${locked.sessionId}, ${locked.actorKind}, ${locked.actorId}, ${locked.turnId}, ${locked.attemptId}, ${locked.executionGeneration}, ${locked.holderKind}, ${locked.holderId}, ${locked.expectedEpoch}, advanced.backend, ${locked.expectedInstanceId}, ${locked.routeKind}, ${locked.routeTargetId}, ${locked.routeEpoch}, advanced.workspace_generation, ${operation}, ${locked.authority.initiatorKind}, ${locked.authority.initiatorSubjectId}, ${locked.authority.initiatingHumanSubjectId}, ${locked.authority.initiatorOrganizationMembershipId}, ${locked.authority.initiatorAuthorizationRevision}, ${locked.authority.authorityEpoch}, ${locked.authority.authorityVisibility}, ${locked.authority.authorityOwnerOrganizationMembershipId} from advanced returning id, lease_id, sandbox_group_id, session_id, actor_kind, actor_id, holder_kind, holder_id, lease_epoch, provider_backend, provider_instance_id, route_kind, route_target_id, route_epoch, workspace_generation `); const row = rows[0]; if (!row) { const current = await tx.execute<{ workspace_generation: number | string; lease_current: boolean; rotation_pending: boolean; holder_current: boolean; capture_in_progress: boolean; archive_capture_remaining_ms: number | string | null; }>(sql` select lease.workspace_generation, ( lease.account_id = ${locked.accountId} and lease.liveness = 'warm' and lease.rotation_requested_at is null and lease.lease_epoch = ${locked.expectedEpoch} and lease.instance_id = ${locked.expectedInstanceId} and (${locked.expectedLeaseId}::uuid is null or lease.id = ${locked.expectedLeaseId}::uuid) and (${locked.expectedBackend}::text is null or lease.backend = ${locked.expectedBackend}::text) ) as lease_current, ( lease.account_id = ${locked.accountId} and lease.liveness = 'warm' and lease.rotation_requested_at is not null and lease.lease_epoch = ${locked.expectedEpoch} and lease.instance_id = ${locked.expectedInstanceId} and (${locked.expectedLeaseId}::uuid is null or lease.id = ${locked.expectedLeaseId}::uuid) and (${locked.expectedBackend}::text is null or lease.backend = ${locked.expectedBackend}::text) ) as rotation_pending, (lease.archive_capture_id is not null) as capture_in_progress, case when lease.archive_capture_deadline_at is null then null else greatest( 0, ceil(extract(epoch from ( lease.archive_capture_deadline_at - clock_timestamp() )) * 1000) )::bigint end as archive_capture_remaining_ms, exists ( select 1 from sandbox_lease_holders as holder where holder.lease_id = lease.id and holder.account_id = ${locked.accountId} and holder.workspace_id = ${locked.workspaceId} and holder.kind = ${locked.holderKind} and holder.holder_id = ${locked.holderId} and holder.subject_id = ${locked.sessionId} ) as holder_current from sandbox_leases as lease where lease.account_id = ${locked.accountId} and lease.workspace_id = ${locked.workspaceId} and lease.sandbox_group_id = ${locked.sandboxGroupId} limit 1 `); if (Number(current[0]?.workspace_generation) >= 2147483647) { throw new SandboxWorkspaceMutationFencedError( "generation_exhausted", "Workspace mutation generation is exhausted", ); } if (current[0]?.lease_current && !current[0].holder_current) { throw new SandboxWorkspaceMutationFencedError( "holder_fenced", "Workspace mutation rejected because the exact lease holder is absent", ); } if (current[0]?.lease_current && current[0].capture_in_progress) { const captureRemainingMs = archiveCaptureRemainingMs({ archive_capture_remaining_ms: current[0].archive_capture_remaining_ms, }); throw new SandboxWorkspaceMutationFencedError( "capture_in_progress", "Workspace mutation is waiting for the exact provider archive capture to settle", captureRemainingMs, ); } if (current[0]?.rotation_pending) { // Same epoch/instance/backend, but a rotation was requested: the // box is not lost. Admission reopens on the cold successor once // the current holders checkpoint and release. throw new SandboxWorkspaceMutationFencedError( "rotation_in_progress", "Workspace mutation is waiting for the sandbox rotation to complete", ); } throw new SandboxWorkspaceMutationFencedError( "lease_fenced", "Workspace mutation rejected by lease epoch/provider fence", ); } return mapWorkspaceMutationAdmission(row); }), ); } async function advanceWorkspaceGenerationForAuthority( db: Database, authority: WorkspaceMutationAuthority, operationInput: string, captureWaitMs = 0, waitSignal?: AbortSignal, onCaptureWait?: (observation: { durationMs: number; outcome: "completed" | "failed" }) => void, ): Promise { if (!Number.isSafeInteger(captureWaitMs) || captureWaitMs < 0 || captureWaitMs > 60 * 60_000) { throw new Error("Workspace archive capture wait is invalid"); } const startedAt = performance.now(); const waitBudget = new SandboxTransitionWaitBudget(captureWaitMs, startedAt); let delayMs = 25; let captureWaitStartedAt: number | undefined; let captureWaitOutcome: "completed" | "failed" = "failed"; try { for (;;) { try { const admission = await advanceWorkspaceGenerationForAuthorityOnce( db, authority, operationInput, ); captureWaitOutcome = "completed"; return admission; } catch (error) { const now = performance.now(); if ( captureWaitMs > 0 && error instanceof SandboxWorkspaceMutationFencedError && error.code === "capture_in_progress" ) { waitBudget.observeCapture(error.captureRemainingMs, now); } if ( !(error instanceof SandboxWorkspaceMutationFencedError) || error.code !== "capture_in_progress" || now >= waitBudget.deadline ) { throw error; } captureWaitStartedAt ??= performance.now(); await waitForSandboxTransition( Math.min(delayMs, Math.max(1, waitBudget.deadline - now)), waitSignal, "Sandbox workspace mutation wait cancelled", ); delayMs = Math.min(500, delayMs * 2); } } } finally { if (captureWaitStartedAt !== undefined && onCaptureWait) { try { onCaptureWait({ durationMs: Math.max(0, performance.now() - captureWaitStartedAt), outcome: captureWaitOutcome, }); } catch { // Diagnostics must never alter mutation admission authority. } } } } /** * Advance the live workspace's mutation generation before an acknowledged * filesystem-writing operation reaches the provider. The normal activity write * fence is acquired first (workspace control -> workspace -> session -> turn -> * attempt), then the exact lease row is updated under its epoch + provider-id * predicates. Any failed fence rejects the operation before external effects. */ export async function advanceWorkspaceGeneration( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; holderId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; operation: string; /** Wait before provider admission while an exact archive capture owns this * lease. The attempt/route fences are re-read on every bounded retry. */ captureWaitMs?: number; /** Cancel the bounded transition wait without creating an admission. */ waitSignal?: AbortSignal; /** Observe only time actually spent blocked behind an archive capture. */ onCaptureWait?: (observation: { durationMs: number; outcome: "completed" | "failed" }) => void; /** Active-routed mutations bind to the exact session pointer. Omitted means * an intentional home-provider write outside the routing surface. */ routeKind?: "home" | "active"; routeTargetId?: string | null; routeEpoch?: number; }, ): Promise { const routeKind = input.routeKind ?? "home"; return await advanceWorkspaceGenerationForAuthority( db, { kind: "turn", accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, holderId: input.holderId, sandboxGroupId: input.sandboxGroupId, expectedEpoch: input.expectedEpoch, expectedInstanceId: input.expectedInstanceId, routeKind, routeTargetId: routeKind === "home" ? null : (input.routeTargetId ?? null), ...(input.routeEpoch === undefined ? {} : { routeEpoch: input.routeEpoch }), }, input.operation, input.captureWaitMs, input.waitSignal, input.onCaptureWait, ); } /** Admit an API/direct mutation under an exact request holder and active route. * Direct actors intentionally have no turn identity and can never inherit the * attempt-quiescence archive fallback. `initiatorSubjectId` is the exact * authenticated principal behind the request and is required: it is this * writer's only causal identity, and it is re-proved against the live grant * inside the admission transaction. */ export async function advanceWorkspaceGenerationForDirectRequest( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; requestId: string; holderId: string; initiatorSubjectId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeTargetId: string | null; routeEpoch: number; operation: string; captureWaitMs?: number; waitSignal?: AbortSignal; }, ): Promise { return await advanceWorkspaceGenerationForAuthority( db, { kind: "direct", routeKind: "active", ...input }, input.operation, input.captureWaitMs, input.waitSignal, ); } /** Admit one model/user-visible stdin write for an exact retained process. The * process's original provider and route are authoritative even if the session's * active pointer has since moved. */ export async function advanceWorkspaceGenerationForRetainedProcess( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; operation: string; captureWaitMs?: number; waitSignal?: AbortSignal; }, ): Promise { return await advanceWorkspaceGenerationForAuthority( db, { kind: "process", ...input }, input.operation, input.captureWaitMs, input.waitSignal, ); } type AdmissionIdentityRow = { id: string; lease_id: string; sandbox_group_id: string; session_id: string; actor_kind: "turn" | "direct" | "process"; actor_id: string; turn_id: string | null; attempt_id: string | null; execution_generation: number | string | null; holder_kind: "turn" | "direct" | "process"; holder_id: string; lease_epoch: number | string; provider_backend: string; provider_instance_id: string; route_kind: "home" | "active"; route_target_id: string | null; route_epoch: number | string; workspace_generation: number | string; operation: string; // Migration 0277 attribution. A row admitted by a pre-0277 writer carries the // sentinel and null epochs; it is never upgraded in place. initiator_kind: "subject" | "service" | "legacy_unattributed"; initiator_subject_id: string; initiating_human_subject_id: string | null; initiator_organization_membership_id: string | null; initiator_authorization_revision: number | string | null; authority_epoch: number | string | null; authority_visibility: "user_private" | "workspace_shared" | null; authority_owner_organization_membership_id: string | null; provider_outcome: "resolved" | "rejected" | "retained" | null; settled_at: Date | string | null; } & Record; async function selectExactAdmissionForUpdate( tx: Database, input: { accountId: string; workspaceId: string; admissionId: string; actorKind: "turn" | "direct" | "process"; actorId: string; sessionId: string; admittedWorkspaceGeneration: number; operation: string; }, ): Promise { const rows = await tx.execute(sql` select * from sandbox_workspace_mutation_admissions where id = ${input.admissionId} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and session_id = ${input.sessionId} and actor_kind = ${input.actorKind} and actor_id = ${input.actorId} and workspace_generation = ${input.admittedWorkspaceGeneration} and operation = ${input.operation} for update `); return rows[0] ?? null; } function admissionMatchesAuthority( admission: AdmissionIdentityRow, authority: LockedWorkspaceMutationAuthority, ): boolean { return ( admission.lease_id === (authority.expectedLeaseId ?? admission.lease_id) && admission.sandbox_group_id === authority.sandboxGroupId && admission.session_id === authority.sessionId && admission.actor_kind === authority.actorKind && admission.actor_id === authority.actorId && admission.turn_id === authority.turnId && admission.attempt_id === authority.attemptId && (admission.execution_generation === null ? authority.executionGeneration === null : Number(admission.execution_generation) === authority.executionGeneration) && admission.holder_kind === authority.holderKind && admission.holder_id === authority.holderId && Number(admission.lease_epoch) === authority.expectedEpoch && admission.provider_instance_id === authority.expectedInstanceId && (authority.expectedBackend === null || admission.provider_backend === authority.expectedBackend) && admission.route_kind === authority.routeKind && admission.route_target_id === authority.routeTargetId && Number(admission.route_epoch) === authority.routeEpoch ); } function admissionMatchesSnapshot( admission: AdmissionIdentityRow, snapshot: SandboxWorkspaceMutationAdmission, ): boolean { return ( admission.id === snapshot.id && admission.lease_id === snapshot.leaseId && admission.sandbox_group_id === snapshot.sandboxGroupId && admission.session_id === snapshot.sessionId && admission.actor_kind === snapshot.actorKind && admission.actor_id === snapshot.actorId && admission.holder_kind === snapshot.holderKind && admission.holder_id === snapshot.holderId && Number(admission.lease_epoch) === snapshot.leaseEpoch && admission.provider_backend === snapshot.providerBackend && admission.provider_instance_id === snapshot.providerInstanceId && admission.route_kind === snapshot.routeKind && admission.route_target_id === snapshot.routeTargetId && Number(admission.route_epoch) === snapshot.routeEpoch && Number(admission.workspace_generation) === snapshot.workspaceGeneration ); } function admissionSnapshotMatchesAuthorityInput( admission: SandboxWorkspaceMutationAdmission, authority: WorkspaceMutationAuthority, ): boolean { if (admission.sessionId !== authority.sessionId) return false; if (authority.kind === "process") { return admission.actorKind === "process" && admission.actorId === authority.processId; } if ( admission.sandboxGroupId !== authority.sandboxGroupId || admission.leaseEpoch !== authority.expectedEpoch || admission.providerInstanceId !== authority.expectedInstanceId || admission.holderId !== authority.holderId ) { return false; } if (authority.kind === "direct") { return ( admission.actorKind === "direct" && admission.actorId === authority.requestId && admission.holderKind === "direct" && admission.routeKind === "active" && admission.routeTargetId === authority.routeTargetId && admission.routeEpoch === authority.routeEpoch ); } const routeKind = authority.routeKind; return ( admission.actorKind === "turn" && admission.actorId === authority.attemptId && admission.holderKind === "turn" && admission.routeKind === routeKind && admission.routeTargetId === (routeKind === "home" ? null : authority.routeTargetId) && (authority.routeEpoch === undefined || admission.routeEpoch === authority.routeEpoch) ); } function admissionMatchesAuthorityInput( admission: AdmissionIdentityRow, authority: WorkspaceMutationAuthority, ): boolean { if ( !admissionSnapshotMatchesAuthorityInput(mapWorkspaceMutationAdmission(admission), authority) ) { return false; } if (authority.kind === "turn") { return ( admission.turn_id === authority.turnId && admission.attempt_id === authority.attemptId && Number(admission.execution_generation) === authority.executionGeneration ); } return admission.turn_id === null && admission.attempt_id === null; } function workspaceMutationAuthorityFailure( error: unknown, ): SandboxWorkspaceMutationSettlementResult | null { if (!(error instanceof SandboxWorkspaceMutationFencedError)) return null; if ( error.code !== "admission_fenced" && error.code !== "attempt_fenced" && error.code !== "holder_fenced" && error.code !== "lease_fenced" && error.code !== "route_fenced" && error.code !== "process_fenced" && // A physically yielded provider process must still be promoted durably when // its authority turns out to be unattributed or revoked; the output is // rejected after commit instead of stranding a running process. error.code !== "authority_unattributed" && error.code !== "authority_revoked" ) { return null; } if (error instanceof SandboxRetainedProcessTerminalError) { return { failure: error.code, detail: error.message, retainedProcessTerminal: { state: error.state, exitCode: error.exitCode }, }; } return { failure: error.code, detail: error.message }; } async function verifyResolvedAdmissionAuthority( tx: Database, authority: LockedWorkspaceMutationAuthority, admission: AdmissionIdentityRow, ): Promise { if (!admissionMatchesAuthority(admission, authority)) { return { failure: "admission_fenced", detail: "Workspace mutation settlement did not match its exact durable admission", }; } if ( admission.route_kind === "active" && authority.actorKind !== "process" && (authority.session.activeSandboxId !== admission.route_target_id || authority.session.activeEpoch !== Number(admission.route_epoch)) ) { return { failure: "route_fenced", detail: "Workspace mutation output rejected because its active route moved", }; } const [identity] = await tx.execute<{ lease_current: boolean; holder_current: boolean; }>(sql` select ( lease.account_id = ${authority.accountId} and lease.workspace_id = ${authority.workspaceId} and lease.sandbox_group_id = ${authority.sandboxGroupId} and lease.liveness = 'warm' and lease.lease_epoch = ${authority.expectedEpoch} and lease.backend = ${admission.provider_backend} and lease.instance_id = ${authority.expectedInstanceId} and lease.workspace_generation >= ${Number(admission.workspace_generation)} ) as lease_current, exists ( select 1 from sandbox_lease_holders as holder where holder.lease_id = lease.id and holder.account_id = ${authority.accountId} and holder.workspace_id = ${authority.workspaceId} and holder.kind = ${authority.holderKind} and holder.holder_id = ${authority.holderId} and holder.subject_id = ${authority.sessionId} ) as holder_current from sandbox_leases as lease where lease.id = ${admission.lease_id} for share `); if (!identity?.lease_current) { return { failure: "lease_fenced", detail: "Workspace mutation output rejected by lease epoch/provider fence", }; } if (!identity.holder_current) { return { failure: "holder_fenced", detail: "Workspace mutation output rejected because the exact holder is absent", }; } return { failure: null }; } async function verifyWorkspaceMutationSettlementForAuthority( db: Database, authorityInput: WorkspaceMutationAuthority, input: { admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }, ): Promise { const operation = normalizeWorkspaceMutationOperation(input.operation); const admissionSnapshot = { ...input.admission }; const outcome = input.outcome; // Savepoint release cannot prove an outer caller-owned transaction committed. const ownsCommit = typeof (db as Database & { rollback?: unknown }).rollback !== "function"; const settleOnce = async (): Promise => await withRlsContext( db, { accountId: authorityInput.accountId, workspaceId: authorityInput.workspaceId, }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Admission and settlement must take the same canonical ownership // prefix before either touches the lease. The former order // (admission row -> authority -> lease) deadlocked a completed // parallel exec settlement against retained-process promotion // (admission row -> lease -> authority). PostgreSQL then rolled // back the losing admission settlement and permanently blocked // checkpoint capture. // // Preserve physical-settlement semantics when mutable authority // is stale: retain the typed fence, settle the exact immutable // admission below, commit, and only then reject its output. let authority: LockedWorkspaceMutationAuthority | null = null; let authorityFailure: SandboxWorkspaceMutationSettlementResult | null = null; try { authority = await lockWorkspaceMutationAuthorityTx(tx, authorityInput); } catch (error) { const failure = workspaceMutationAuthorityFailure(error); if (!failure) throw error; authorityFailure = failure; } const actorKind = authorityInput.kind; const actorId = authorityInput.kind === "turn" ? authorityInput.attemptId : authorityInput.kind === "direct" ? authorityInput.requestId : authorityInput.processId; const admission = await selectExactAdmissionForUpdate(tx, { accountId: authorityInput.accountId, workspaceId: authorityInput.workspaceId, admissionId: admissionSnapshot.id, actorKind, actorId, sessionId: authorityInput.sessionId, admittedWorkspaceGeneration: admissionSnapshot.workspaceGeneration, operation, }); if ( !admission || !admissionMatchesSnapshot(admission, admissionSnapshot) || !admissionMatchesAuthorityInput(admission, authorityInput) || admission.provider_outcome === "retained" || (admission.provider_outcome && admission.provider_outcome !== outcome) || (admission.settled_at && admission.provider_outcome !== outcome) ) { return { failure: "admission_fenced" as const, detail: "Workspace mutation settlement did not match its exact durable admission", }; } if (!admission.settled_at) { const pendingAttempt = await nextSessionAttemptAwaitingQuiescence( tx, authorityInput.workspaceId, authorityInput.sessionId, ); const [physical] = await tx.execute<{ provider_outcome: string; settled_at: Date; }>(sql` update sandbox_workspace_mutation_admissions set provider_outcome = ${outcome}, settled_at = now() where id = ${admissionSnapshot.id} and settled_at is null returning provider_outcome, settled_at `); if (physical?.provider_outcome !== outcome || !physical.settled_at) { return { failure: "admission_fenced" as const, detail: "Workspace mutation settlement did not commit its exact provider outcome", }; } if ( pendingAttempt || (authorityInput.kind !== "direct" && (!authority || authority.session.status === "recovering") && (await hasWaitingSandboxSetupForWriterTx( tx, authorityInput.workspaceId, authorityInput.sessionId, actorKind, actorId, ))) ) { const [wakeTarget] = await tx .select({ workflowId: schema.sessions.temporalWorkflowId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, authorityInput.workspaceId), eq(schema.sessions.id, authorityInput.sessionId), ), ) .limit(1); await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: authorityInput.accountId, workspaceId: authorityInput.workspaceId, sessionId: authorityInput.sessionId, temporalWorkflowId: wakeTarget?.workflowId ?? `session-${authorityInput.sessionId}`, reason: "workspace_mutation_settled_quiescence", }); } } if (outcome === "rejected") return { failure: null }; if (authorityFailure) return { ...authorityFailure, physicallySettled: true }; if (!authority) { throw new Error("Workspace mutation settlement lost its locked authority"); } const acceptance = await verifyResolvedAdmissionAuthority(tx, authority, admission); return acceptance.failure === null ? acceptance : { ...acceptance, physicallySettled: true }; }), ); const settlement = await runIdempotentPersistenceTransaction( { stage: "sandbox_workspace_mutation_settlement", maxAttempts: 5, }, settleOnce, ); if (settlement.failure !== null) { if (settlement.physicallySettled && ownsCommit) { // This branch is reached only after the transaction committed a matching // terminal admission. A failed commit or contradictory receipt never // reaches it, even when the provider returned successfully. throw new SandboxWorkspaceMutationOutputRejectedError( settlement.failure, settlement.detail, { accountId: authorityInput.accountId, workspaceId: authorityInput.workspaceId, admission: admissionSnapshot, operation, outcome: "resolved", }, settlement.retainedProcessTerminal ?? null, ); } throw new SandboxWorkspaceMutationFencedError(settlement.failure, settlement.detail); } } /** Physically settle one exact provider mutation admission after its promise * resolves or rejects. Rejections need no output acceptance, but still clear * the in-flight capture blocker. Resolved output is accepted only after the * canonical attempt fence plus the exact live lease-holder/provider identity * are revalidated. A failed acceptance fence is reported only AFTER the * settlement transaction commits, so stale output can be rejected without * resurrecting the physical blocker. */ export async function verifyWorkspaceMutationSettlement( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; holderId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; routeKind?: "home" | "active"; routeTargetId?: string | null; routeEpoch?: number; }, ): Promise { const routeKind = input.routeKind ?? "home"; // Settle the exact admission: without an explicit route epoch, the route // epoch is the one recorded when it was admitted, never the session's // current epoch. A swap during a home-sandbox command moves the session's // active route but changes nothing about where that command ran, so it must // not reject the command's output (an active-route move is still fenced as // route_fenced against the admission's recorded route). const routeEpoch = input.routeEpoch ?? input.admission.routeEpoch; await verifyWorkspaceMutationSettlementForAuthority( db, { kind: "turn", accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.executionGeneration, attemptId: input.attemptId, holderId: input.holderId, sandboxGroupId: input.sandboxGroupId, expectedEpoch: input.expectedEpoch, expectedInstanceId: input.expectedInstanceId, routeKind, routeTargetId: routeKind === "home" ? null : (input.routeTargetId ?? null), routeEpoch, }, input, ); } export async function verifyDirectWorkspaceMutationSettlement( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; requestId: string; holderId: string; initiatorSubjectId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeTargetId: string | null; routeEpoch: number; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }, ): Promise { await verifyWorkspaceMutationSettlementForAuthority( db, { kind: "direct", routeKind: "active", ...input }, input, ); } export async function verifyRetainedProcessMutationSettlement( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }, ): Promise { await verifyWorkspaceMutationSettlementForAuthority(db, { kind: "process", ...input }, input); } /** Promote one yielded provider exec into durable process authority. The parent * admission stays unsettled (`retained`) and a process holder is inserted in the * same transaction, so ordinary request/turn cleanup cannot open archive capture. */ export async function retainWorkspaceMutationProcess( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; providerSessionId: number; admissionId: string; admittedWorkspaceGeneration: number; operation: string; providerBinding: { key: string; binding: ModalCheckpointProviderBinding; } | null; backgroundCommand?: { commandId: string; command: string; }; /** A Docker or local command under the in-sandbox supervisor: any worker * built with that supervisor can reach it, older ones cannot. */ inSandboxSupervisor?: boolean; owner: | { kind: "turn"; turnId: string; executionGeneration: number; attemptId: string; holderId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeKind?: "home" | "active"; routeTargetId?: string | null; routeEpoch?: number; } | { kind: "direct"; requestId: string; holderId: string; initiatorSubjectId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; routeTargetId: string | null; routeEpoch: number; }; }, ): Promise { if (!Number.isSafeInteger(input.providerSessionId) || input.providerSessionId <= 0) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained provider session id must be a positive safe integer", ); } if (input.backgroundCommand && input.backgroundCommand.commandId !== input.processId) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Managed background command id must equal its exact retained process id", ); } const operation = normalizeWorkspaceMutationOperation(input.operation); const providerBinding = input.providerBinding ? canonicalModalCheckpointProviderBinding(input.providerBinding.binding) : null; if (input.providerBinding && providerBinding?.key !== input.providerBinding.key) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process provider binding is not canonical", ); } const authorityInput: TurnWorkspaceMutationAuthority | DirectWorkspaceMutationAuthority = input.owner.kind === "turn" ? { kind: "turn", accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.owner.turnId, executionGeneration: input.owner.executionGeneration, attemptId: input.owner.attemptId, holderId: input.owner.holderId, sandboxGroupId: input.owner.sandboxGroupId, expectedEpoch: input.owner.expectedEpoch, expectedInstanceId: input.owner.expectedInstanceId, routeKind: input.owner.routeKind ?? "home", routeTargetId: (input.owner.routeKind ?? "home") === "home" ? null : (input.owner.routeTargetId ?? null), ...(input.owner.routeEpoch === undefined ? {} : { routeEpoch: input.owner.routeEpoch }), } : { kind: "direct", accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, requestId: input.owner.requestId, holderId: input.owner.holderId, initiatorSubjectId: input.owner.initiatorSubjectId, sandboxGroupId: input.owner.sandboxGroupId, expectedEpoch: input.owner.expectedEpoch, expectedInstanceId: input.owner.expectedInstanceId, routeKind: "active", routeTargetId: input.owner.routeTargetId, routeEpoch: input.owner.routeEpoch, }; const result = await retryRlsPersistence( db, { accountId: input.accountId, workspaceId: input.workspaceId }, { stage: "sandbox_retained_process_promotion", maxAttempts: 5, correlationId: input.processId, }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; if (input.backgroundCommand) { await lockBackgroundCommandWorkspaceLifecycle(tx, [input.workspaceId], "share"); } // Use the same ownership prefix as mutation admission and settlement. // A stale authority still cannot strand a provider process: remember // the fence, durably promote the exact process, then reject its output // after this transaction commits. let authority: LockedWorkspaceMutationAuthority | null = null; let authorityFailure: SandboxWorkspaceMutationSettlementResult | null = null; try { authority = await lockWorkspaceMutationAuthorityTx(tx, authorityInput); } catch (error) { const failure = workspaceMutationAuthorityFailure(error); if (!failure) throw error; authorityFailure = failure; } const actorKind = authorityInput.kind; const actorId = authorityInput.kind === "turn" ? authorityInput.attemptId : authorityInput.requestId; const admission = await selectExactAdmissionForUpdate(tx, { accountId: input.accountId, workspaceId: input.workspaceId, admissionId: input.admissionId, actorKind, actorId, sessionId: input.sessionId, admittedWorkspaceGeneration: input.admittedWorkspaceGeneration, operation, }); if (!admission || !admissionMatchesAuthorityInput(admission, authorityInput)) { throw new SandboxWorkspaceMutationFencedError( "admission_fenced", "Retained process did not match its exact parent admission", ); } if (admission.provider_backend === "modal" && !providerBinding) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Modal retained process requires its exact authenticated provider binding", ); } if (admission.provider_backend !== "modal" && providerBinding) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Only Modal retained processes may carry a Modal provider binding", ); } const [existing] = await tx .select() .from(schema.sandboxRetainedProcesses) .where(eq(schema.sandboxRetainedProcesses.parentAdmissionId, input.admissionId)) .limit(1); if (existing) { if ( existing.id !== input.processId || existing.providerSessionId !== input.providerSessionId || existing.state !== "active" || (existing.providerBindingKey !== null && existing.providerBindingKey !== (providerBinding?.key ?? null)) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Parent admission is already bound to a different retained process", ); } } let process = existing; if (process?.providerBindingKey === null && providerBinding) { const [bound] = await tx .update(schema.sandboxRetainedProcesses) .set({ providerBindingKey: providerBinding.key, providerBinding: providerBinding.binding, }) .where( and( eq(schema.sandboxRetainedProcesses.id, process.id), eq(schema.sandboxRetainedProcesses.state, "active"), isNull(schema.sandboxRetainedProcesses.providerBindingKey), isNull(schema.sandboxRetainedProcesses.providerBinding), ), ) .returning(); if (!bound) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process changed while binding its provider namespace", ); } process = bound; } if (!process) { if (admission.provider_outcome !== null || admission.settled_at !== null) { throw new SandboxWorkspaceMutationFencedError( "admission_fenced", "Settled workspace mutation cannot be promoted to a retained process", ); } // Holder mutations follow the canonical lease -> holder lock order. // The physical provider process already exists, so this lock does not // re-evaluate mutable attempt authority; it only serializes its // durable holder/refcount publication with acquire/release/reaping. const processLeases = await tx.execute<{ id: string }>(sql` select id from sandbox_leases where id = ${admission.lease_id} for update `); if (!processLeases[0]) { throw new SandboxWorkspaceMutationFencedError( "lease_fenced", "Retained process lease vanished before durable promotion", ); } const processHolderId = `process:${input.processId}`; await tx.execute(sql` insert into sandbox_lease_holders (account_id, workspace_id, lease_id, kind, holder_id, subject_id, last_heartbeat_at) values (${input.accountId}, ${input.workspaceId}, ${admission.lease_id}, 'process', ${processHolderId}, ${input.sessionId}, now()) on conflict (lease_id, kind, holder_id) do nothing `); const [created] = await tx .insert(schema.sandboxRetainedProcesses) .values({ id: input.processId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, leaseId: admission.lease_id, sandboxGroupId: admission.sandbox_group_id, parentAdmissionId: admission.id, holderId: processHolderId, ownerActorKind: admission.actor_kind as "turn" | "direct", ownerActorId: admission.actor_id, ownerTurnId: admission.turn_id, ownerAttemptId: admission.attempt_id, ownerExecutionGeneration: admission.execution_generation === null ? null : Number(admission.execution_generation), leaseEpoch: Number(admission.lease_epoch), providerBackend: admission.provider_backend, providerInstanceId: admission.provider_instance_id, providerBindingKey: providerBinding?.key ?? null, providerBinding: providerBinding?.binding ?? null, routeKind: admission.route_kind, routeTargetId: admission.route_target_id, routeEpoch: Number(admission.route_epoch), providerSessionId: input.providerSessionId, reconcilerVersion: input.inSandboxSupervisor ? 2 : 1, // The retained process inherits the EXACT authority admitted with // its parent operation. It is copied, never re-resolved: the // process may outlive the request or turn behind it, and a later // membership or visibility change must fence it rather than // silently re-own it. initiatorKind: admission.initiator_kind, initiatorSubjectId: admission.initiator_subject_id, initiatingHumanSubjectId: admission.initiating_human_subject_id, initiatorOrganizationMembershipId: admission.initiator_organization_membership_id, initiatorAuthorizationRevision: admission.initiator_authorization_revision === null ? null : Number(admission.initiator_authorization_revision), authorityEpoch: admission.authority_epoch === null ? null : Number(admission.authority_epoch), authorityVisibility: admission.authority_visibility, authorityOwnerOrganizationMembershipId: admission.authority_owner_organization_membership_id, state: "active", }) .returning(); await tx.execute(sql` update sandbox_workspace_mutation_admissions set provider_outcome = 'retained' where id = ${admission.id} and provider_outcome is null and settled_at is null `); await tx.execute(sql` update sandbox_leases as lease set refcount = counts.total, turn_holders = counts.turns, viewer_holders = counts.viewers, updated_at = now() from ( select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers from sandbox_lease_holders where lease_id = ${admission.lease_id} ) as counts where lease.id = ${admission.lease_id} `); process = created; } // A yielded provider process is already a physical outcome. Persist its // exact route and non-TTL holder even when the earlier authority check // found a stale route/turn, then report staleness after commit. if (authorityFailure) { return { process: mapRetainedProcess(process!), failure: authorityFailure, }; } if (!authority) { throw new Error("Retained process promotion lost its locked authority"); } const identity = await verifyResolvedAdmissionAuthority(tx, authority, admission); if (identity.failure !== null) { return { process: mapRetainedProcess(process!), failure: identity }; } if (input.backgroundCommand) { if (authorityInput.kind === "direct") { const effectiveControl = await evaluateSessionControl( tx, input.workspaceId, input.sessionId, { lock: "none" }, ); if (effectiveControl.state !== "active") { return { process: mapRetainedProcess(process!), failure: { failure: "attempt_fenced" as const, detail: "Managed background command adoption was preceded by Pause or Cancel", }, }; } } await insertManagedSessionBackgroundCommandInTransaction(tx, { ...input, retainedProcessId: input.processId, ...input.backgroundCommand, }); } return { process: mapRetainedProcess(process!), failure: identity }; }), ); if (result.failure.failure !== null) { throw new SandboxRetainedProcessPromotionFencedError( result.failure.failure, result.failure.detail, result.process, ); } return result.process; } /** Read one retained process by durable UUID. Callers must use the copied route * identity; a numeric provider session id alone is never sufficient authority. */ export async function getRetainedProcess( db: Database, input: { workspaceId: string; sessionId: string; processId: string }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .limit(1); return row ? mapRetainedProcess(row) : null; }); } /** The session background command a later turn of the same session reaches * by the provider handle an earlier turn returned to the model. The handle is * a lookup key here, not authority: the row must be an active process of this * exact session, on the caller's exact home lease epoch and provider instance, * whose lifecycle was transferred to a still-running background command. * Anything else, or more than one match, is null. */ export async function findRunningSessionBackgroundProcess( db: Database, input: { workspaceId: string; sessionId: string; providerSessionId: number; providerBackend: string; /** Omit only when the caller binds the result to an exact live backend * identity itself; more than one match is then null as well. */ providerInstanceId?: string | undefined; leaseEpoch?: number | undefined; }, ): Promise { if (!Number.isSafeInteger(input.providerSessionId) || input.providerSessionId <= 0) return null; return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const process = schema.sandboxRetainedProcesses; const background = schema.sessionBackgroundCommands; const rows = await scopedDb .select() .from(process) .where( and( eq(process.workspaceId, input.workspaceId), eq(process.sessionId, input.sessionId), eq(process.providerSessionId, input.providerSessionId), eq(process.state, "active"), eq(process.providerBackend, input.providerBackend), ...(input.providerInstanceId === undefined ? [] : [eq(process.providerInstanceId, input.providerInstanceId)]), ...(input.leaseEpoch === undefined ? [] : [eq(process.leaseEpoch, input.leaseEpoch)]), eq(process.routeKind, "home"), isNull(process.routeTargetId), exists( scopedDb .select({ id: background.id }) .from(background) .where( and( eq(background.workspaceId, process.workspaceId), eq(background.sessionId, process.sessionId), eq(background.retainedProcessId, process.id), eq(background.state, "running"), ), ), ), ), ) .limit(2); return rows.length === 1 ? mapRetainedProcess(rows[0]!) : null; }); } /** The newest retained-process kind this build's reaper can reach. Version 2 * adds Docker and local commands under the in-sandbox supervisor. The claim * returns only rows at or below the caller's version, so during a rolling * deploy an older worker's reaper leaves newer rows to a newer worker instead * of probing its own memory for them and settling a live command as lost. */ export const RETAINED_PROCESS_RECONCILER_VERSION = 2; /** Claim a bounded, oldest-due batch of active retained processes whose exact * owner attempt is closed, whose direct request returned, or whose lifecycle * was explicitly transferred to a session background command. Claim * expiry only recovers coordination after worker death; it is never provider * exit proof. Rows that settle between the global claim and scoped read are * deliberately omitted. */ export async function claimTerminalRetainedProcesses( db: Database, input: { claimId: string; limit: number; claimTtlMs: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) { throw new Error("Retained process reconciliation limit must be between 1 and 100"); } if ( !Number.isSafeInteger(input.claimTtlMs) || input.claimTtlMs < 0 || input.claimTtlMs > 3_600_000 ) { throw new Error("Retained process reconciliation claim TTL is invalid"); } const rows = await rawRows<{ account_id: string; workspace_id: string; session_id: string; process_id: string; claim_id: string; owner_state: string; owner_attempt_outcome: string | null; }>( db, sql` select account_id, workspace_id, session_id, process_id, claim_id, owner_state, owner_attempt_outcome from opengeni_private.claim_terminal_retained_processes( ${input.claimId}::uuid, ${input.limit}::integer, ${input.claimTtlMs}::bigint, ${RETAINED_PROCESS_RECONCILER_VERSION}::integer ) `, ); const claims: SandboxRetainedProcessReconciliationClaim[] = []; for (const row of rows) { const process = await getRetainedProcess(db, { workspaceId: row.workspace_id, sessionId: row.session_id, processId: row.process_id, }); if ( !process || process.accountId !== row.account_id || process.state !== "active" || process.reconcileClaimId !== row.claim_id ) { continue; } claims.push({ process, claimId: row.claim_id, ownerState: row.owner_state, ownerAttemptOutcome: row.owner_attempt_outcome, }); } return claims; } /** * Adopt the provider namespace for one legacy retained process only after a * positive lookup of its exact historical Modal sandbox. A NotFound response * is deliberately insufficient: without a pre-existing binding it cannot * distinguish deletion from a credential/workspace change. */ export async function bindRetainedProcessProviderIdentity( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; providerBindingKey: string; providerBinding: ModalCheckpointProviderBinding; }, ): Promise { const binding = canonicalModalCheckpointProviderBinding(input.providerBinding); if (!binding || binding.key !== input.providerBindingKey) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process provider binding is not canonical", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if ( !process || process.state !== "active" || process.providerBackend !== "modal" || !retainedProcessMatchesSettlementIdentity(process, input.expected) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process binding did not match an active copied Modal identity", ); } if (process.reconcileClaimId !== input.claimId) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process binding claim was lost or superseded", ); } if (process.providerBindingKey !== null || process.providerBinding !== null) { const existing = canonicalModalCheckpointProviderBinding(process.providerBinding); if (!existing || existing.key !== binding.key) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process already belongs to a different provider namespace", ); } return mapRetainedProcess(process); } const [updated] = await tx .update(schema.sandboxRetainedProcesses) .set({ providerBindingKey: binding.key, providerBinding: binding.binding, lastReconcileOutcome: "provider_binding_adopted", }) .where( and( eq(schema.sandboxRetainedProcesses.id, process.id), eq(schema.sandboxRetainedProcesses.state, "active"), eq(schema.sandboxRetainedProcesses.reconcileClaimId, input.claimId), isNull(schema.sandboxRetainedProcesses.providerBindingKey), isNull(schema.sandboxRetainedProcesses.providerBinding), ), ) .returning(); if (!updated) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process changed while adopting its provider namespace", ); } return mapRetainedProcess(updated); }), ); } /** Durably checkpoint exact provider exit/loss proof before canonical * settlement. This closes the worker-death window between provider observation * and settlement without converting owner state, age, timeout, or claim expiry * into physical proof. */ export async function recordRetainedProcessReconciliationProof( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; proof: RetainedProcessProviderProof; }, ): Promise { if ( input.proof.outcome === "exited" && (!Number.isSafeInteger(input.proof.exitCode) || input.proof.exitCode === null) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process reconciliation exit proof requires a safe integer exit code", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if ( !process || process.state !== "active" || !retainedProcessMatchesSettlementIdentity(process, input.expected) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process proof did not match an active copied durable identity", ); } if (process.reconcileClaimId !== input.claimId) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process proof claim was lost or superseded", ); } const existing = mapRetainedProcess(process); const existingProof = retainedProcessReconciliationProof(existing); if (existingProof) { if ( existingProof.outcome !== input.proof.outcome || existingProof.exitCode !== input.proof.exitCode || existingProof.reason !== input.proof.reason ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process already carries different provider proof", ); } return existing; } const [updated] = await tx .update(schema.sandboxRetainedProcesses) .set({ reconcileProofOutcome: input.proof.outcome, reconcileProofExitCode: input.proof.exitCode, reconcileProofReason: input.proof.reason, reconcileProofObservedAt: new Date(), lastReconcileOutcome: `proof_${input.proof.outcome}`, }) .where( and( eq(schema.sandboxRetainedProcesses.id, process.id), eq(schema.sandboxRetainedProcesses.state, "active"), eq(schema.sandboxRetainedProcesses.reconcileClaimId, input.claimId), ), ) .returning(); if (!updated) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process changed while checkpointing provider proof", ); } return mapRetainedProcess(updated); }), ); } /** Release one exact reconciliation claim after an ambiguous/running provider * observation. This schedules a bounded retry but never changes process, * admission, holder, lease, archive, snapshot, or workspace state. */ export async function deferRetainedProcessReconciliation( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; outcome: string; retryAfterMs: number; }, ): Promise { const outcome = normalizeRetainedProcessReconciliationOutcome(input.outcome); if ( !Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0 || input.retryAfterMs > 86_400_000 ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process reconciliation retry delay is invalid", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if (!process || !retainedProcessMatchesSettlementIdentity(process, input.expected)) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process reconciliation did not match the copied durable identity", ); } if (process.state !== "active") return false; if (process.reconcileClaimId !== input.claimId) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process reconciliation claim was lost or superseded", ); } const [updated] = await tx .update(schema.sandboxRetainedProcesses) .set({ reconcileAfter: new Date(Date.now() + input.retryAfterMs), reconcileClaimId: null, reconcileClaimedAt: null, lastReconcileOutcome: outcome, }) .where( and( eq(schema.sandboxRetainedProcesses.id, process.id), eq(schema.sandboxRetainedProcesses.state, "active"), eq(schema.sandboxRetainedProcesses.reconcileClaimId, input.claimId), ), ) .returning({ id: schema.sandboxRetainedProcesses.id }); return Boolean(updated); }), ); } export async function countActiveRetainedProcessesByOwnerState( db: Database, ): Promise { const rows = await rawRows<{ owner_state: string; active_count: number | string; terminal_owner_count: number | string; }>( db, sql` select owner_state, active_count, terminal_owner_count from opengeni_private.count_active_retained_processes_by_owner_state() `, ); return rows.map((row) => ({ ownerState: row.owner_state, activeCount: Number(row.active_count), terminalOwnerCount: Number(row.terminal_owner_count), })); } export async function countExpiredDrainingSandboxLeases( db: Database, ): Promise { const rows = await rawRows<{ backend: string; age_bucket: ExpiredDrainingSandboxLeaseCount["ageBucket"]; count: number | string; }>( db, sql` select backend, age_bucket, count from opengeni_private.count_expired_draining_sandbox_leases() `, ); return rows.map((row) => ({ backend: row.backend, ageBucket: row.age_bucket, count: Number(row.count), })); } /** Settle an exact retained process only after exit or definitive loss proof. * The process row, parent admission, non-TTL holder, lease count, and any * linked background-command terminal input commit atomically. A duplicate * terminal state + exit code is idempotent and * preserves the first durable evidence reason; contradictory physical truth * fails closed. */ export async function settleRetainedProcess( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; reconciliationClaimId?: string; outcome: "exited" | "lost"; exitCode?: number | null; reason: string; idleGraceMs: number; }, ): Promise<{ settled: boolean; process: SandboxRetainedProcess; backgroundCommandEvents: SessionEvent[]; /** Committed wakes to signal after commit; see `signalBackgroundCommandWakes`. */ backgroundCommandWakes: SessionWorkflowWake[]; }> { return settleRetainedProcessWithAuthority(db, input); } /** Only call for an authenticated, typed provider response proving this exact * retained launch was never started. Ambiguous dispatch is NOT rejection proof. * The command equality and empty launch checks repeat under the settlement lock. */ export async function rejectRetainedSupervisedLaunch( db: Database, scope: { accountId: string; workspaceId: string; sessionId: string; processId: string }, command: ModalRouterProviderCommand, ): Promise { const expectedCommand = ModalRouterProviderCommand.parse(command); if (!expectedCommand.supervision) throw new Error("Launch rejection requires supervision"); const process = await getRetainedProcess(db, scope); if (!process) throw new Error("Retained supervised launch is unavailable"); await settleRetainedProcessWithAuthority( db, { ...scope, expected: process, outcome: "lost", reason: "provider_start_rejected", idleGraceMs: 0, }, expectedCommand, ); } /** Compose the leaf cursor/proof persistence with canonical settlement. The * leaf subpath cannot import this root without reversing the DB boundary. */ export function retainedProviderCommandPersistence( ...[db, scope, publish]: Parameters ) { return { ...retainedProviderCommandState(db, scope, publish), rejectSupervisedLaunch: (command: ModalRouterProviderCommand) => rejectRetainedSupervisedLaunch(db, scope, command), }; } // Never expose the launch-rejection authority on the public generic settlement // input: ordinary lost callbacks must not become never-started evidence. async function settleRetainedProcessWithAuthority( db: Database, input: Parameters[1], rejectedLaunch?: ModalRouterProviderCommand, ): ReturnType { const reason = normalizeRetainedProcessSettlementReason(input.reason); const exitCode = input.outcome === "exited" ? (input.exitCode ?? null) : null; if (exitCode !== null && !Number.isSafeInteger(exitCode)) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process exit code must be a safe integer or null", ); } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const session = await lockWorkspaceMutationSessionTx(tx, input.workspaceId, input.sessionId); const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), eq(schema.sandboxRetainedProcesses.id, input.processId), ), ) .for("update") .limit(1); if (!process) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process settlement did not match a durable process", ); } if (!retainedProcessMatchesSettlementIdentity(process, input.expected)) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process settlement did not match the copied durable identity", ); } if (rejectedLaunch) { if ( input.outcome !== "lost" || reason !== "provider_start_rejected" || !isDeepStrictEqual(process.providerCommand, rejectedLaunch) || process.supervisionReceipt !== null || process.supervisionOutputCaptured || process.reconcileProofOutcome !== null || process.providerCommandInputIndex !== 0 || !Object.values(rejectedLaunch.streams).every( (stream) => stream.byteOffset === 0 && stream.utf8Remainder === "" && !stream.eof && stream.exitCode === null, ) || (process.state !== "active" && (process.state !== "lost" || process.settlementReason !== reason)) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Launch rejection requires the exact pristine retained invocation", ); } const [children] = await tx.execute<{ present: boolean }>(sql` select exists(select 1 from sandbox_workspace_mutation_admissions where account_id=${input.accountId} and workspace_id=${input.workspaceId} and actor_kind='process' and actor_id=${input.processId}) as present `); if (children?.present) throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Launch rejection cannot retire admitted process input", ); } if (process.state !== "active") { if (process.state !== input.outcome || process.exitCode !== exitCode) { throw new SandboxRetainedProcessTerminalError(process.state, process.exitCode); } await tx .update(schema.sandboxPtySessions) .set({ status: "closed", closedAt: new Date() }) .where( and( eq(schema.sandboxPtySessions.retainedProcessId, process.id), eq(schema.sandboxPtySessions.status, "open"), ), ); const terminalProcess = mapRetainedProcess(process); const commandMutation = backgroundCommandTerminalMutation({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, }); await settleSessionBackgroundCommandForRetainedProcessInTransaction( tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, retainedProcessId: input.processId, outcome: input.outcome, exitCode, reason: terminalProcess.settlementReason ?? reason, }, commandMutation, ); return { settled: false, process: terminalProcess, backgroundCommandEvents: [...commandMutation.events], backgroundCommandWakes: [...commandMutation.wakes], }; } if ( input.reconciliationClaimId !== undefined && process.reconcileClaimId !== input.reconciliationClaimId ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process settlement reconciliation claim was lost or superseded", ); } const durableProof = retainedProcessReconciliationProof(mapRetainedProcess(process)); if ( process.providerCommand?.kind === "modal-router-v1" && process.providerCommand.supervision && !rejectedLaunch && (input.outcome !== "exited" || !process.supervisionReceipt || !process.supervisionOutputCaptured || exitCode !== process.supervisionReceipt.leaderExitCode) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Supervised command requires immutable quiescence, provider termination and captured output", ); } if ( durableProof && (durableProof.outcome !== input.outcome || durableProof.exitCode !== exitCode) ) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process settlement conflicts with checkpointed provider proof", ); } const wasAwaitingQuiescence = process.ownerAttemptId !== null && (await hasPendingSessionAttemptQuiescenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, attemptId: process.ownerAttemptId, })); const admissions = await tx.execute(sql` select * from sandbox_workspace_mutation_admissions where id = ${process.parentAdmissionId} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and session_id = ${input.sessionId} and lease_id = ${process.leaseId} and sandbox_group_id = ${process.sandboxGroupId} and lease_epoch = ${process.leaseEpoch} and provider_backend = ${process.providerBackend} and provider_instance_id = ${process.providerInstanceId} and route_kind = ${process.routeKind} and route_target_id is not distinct from ${process.routeTargetId} and route_epoch = ${process.routeEpoch} and provider_outcome = 'retained' and settled_at is null for update `); if (!admissions[0]) { throw new SandboxWorkspaceMutationFencedError( "admission_fenced", "Retained process parent admission is not open", ); } const leases = await tx.execute(sql` select * from sandbox_leases where id = ${process.leaseId} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${process.sandboxGroupId} for update `); const lease = leases[0]; if (!lease) { throw new SandboxWorkspaceMutationFencedError( "lease_fenced", "Retained process settlement lease no longer exists", ); } const processOwnsCurrentLease = Number(lease.lease_epoch) === process.leaseEpoch && lease.backend === process.providerBackend && lease.instance_id === process.providerInstanceId; // A successor lease may inherit stale process-holder rows from the old // provider identity. Removing those rows is necessary, but only a // reconciliation claim carrying durable provider exit/loss proof may // cross that identity boundary. A late owner callback without such a // proof remains fenced. if ( !processOwnsCurrentLease && (input.reconciliationClaimId === undefined || durableProof === null) ) { throw new SandboxWorkspaceMutationFencedError( "lease_fenced", "Superseded retained process settlement requires durable provider proof", ); } await tx .update(schema.sandboxPtySessions) .set({ status: "closed", closedAt: new Date() }) .where( and( eq(schema.sandboxPtySessions.retainedProcessId, process.id), eq(schema.sandboxPtySessions.status, "open"), ), ); const [priorRejectionBinding] = rejectedLaunch ? await tx.execute<{ value: string | null }>(sql` select current_setting('opengeni.supervised_launch_rejection_binding', true) as value `) : []; if (rejectedLaunch) await tx.execute(sql` select set_config('opengeni.supervised_launch_rejection_binding', ${JSON.stringify({ processId: process.id, command: rejectedLaunch })}, true) `); const [updated] = await tx .update(schema.sandboxRetainedProcesses) .set({ state: input.outcome, exitCode, // A checkpointed provider proof is the first durable evidence for // this physical terminal state. A later owner/reaper observation // may classify the same state + exit code differently, but it must // not overwrite that already-durable evidence provenance. settlementReason: durableProof?.reason ?? reason, settledAt: new Date(), reconcileClaimId: null, reconcileClaimedAt: null, lastReconcileOutcome: input.reconciliationClaimId === undefined ? `owner_settled_${input.outcome}` : `reconciled_${input.outcome}`, }) .where( and( eq(schema.sandboxRetainedProcesses.id, process.id), eq(schema.sandboxRetainedProcesses.state, "active"), ), ) .returning(); if (rejectedLaunch) await tx.execute(sql` select set_config('opengeni.supervised_launch_rejection_binding', ${priorRejectionBinding?.value ?? ""}, true) `); if (!updated) { throw new SandboxWorkspaceMutationFencedError( "process_fenced", "Retained process changed while its row was locked", ); } await tx.execute(sql` update sandbox_workspace_mutation_admissions set provider_outcome = ${input.outcome === "exited" ? "resolved" : "rejected"}, settled_at = now() where id = ${process.parentAdmissionId} and provider_outcome = 'retained' and settled_at is null `); await tx.execute(sql` delete from sandbox_lease_holders where lease_id = ${process.leaseId} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and kind = 'process' and holder_id = ${process.holderId} `); const [counts] = await tx.execute<{ total: number; turns: number; viewers: number; }>(sql` select count(*)::int as total, count(*) filter (where kind = 'turn')::int as turns, count(*) filter (where kind = 'viewer')::int as viewers from sandbox_lease_holders where lease_id = ${process.leaseId} `); const enterDraining = processOwnsCurrentLease && (counts?.total ?? 0) === 0; await tx.execute(sql` update sandbox_leases set refcount = ${counts?.total ?? 0}, turn_holders = ${counts?.turns ?? 0}, viewer_holders = ${counts?.viewers ?? 0}, ${ enterDraining ? sql`liveness = case when liveness = 'warm' then 'draining' else liveness end, expires_at = case when liveness = 'warm' then case when rotation_requested_at is not null then now() else now() + (${String(input.idleGraceMs)} || ' milliseconds')::interval end else expires_at end,` : sql`` } updated_at = now() where id = ${process.leaseId} and sandbox_group_id = ${process.sandboxGroupId} `); const settledProcess = mapRetainedProcess(updated); const commandMutation = backgroundCommandTerminalMutation({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, }); await settleSessionBackgroundCommandForRetainedProcessInTransaction( tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, retainedProcessId: input.processId, outcome: input.outcome, exitCode, reason: settledProcess.settlementReason ?? reason, }, commandMutation, ); const setupAwaitingCompletion = process.ownerAttemptId && session.status === "recovering" && (await hasWaitingSandboxSetupForWriterTx( tx, input.workspaceId, input.sessionId, "turn", process.ownerAttemptId, )); if ( process.ownerAttemptId && (setupAwaitingCompletion || wasAwaitingQuiescence || (await hasPendingSessionAttemptQuiescenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, attemptId: process.ownerAttemptId, }))) ) { await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${input.sessionId}`, reason: "retained_process_settled_quiescence", }); } return { settled: true, process: settledProcess, backgroundCommandEvents: [...commandMutation.events], backgroundCommandWakes: [...commandMutation.wakes], }; }, ); } /** Legacy containment never substitutes for native-supervisor terminal proof. * Presence, not successful descriptor parsing, is the fail-closed boundary. * Check the whole lease, including stale/already-enrolled process IDs. A warm * point-in-time capture marked concurrent is the one exception: it never * terminates the box (see `concurrentLeaseProcess`). */ function noActiveSupervisedProcesses(leaseId: SQL): SQL { return sql`not exists ( select 1 from sandbox_retained_processes supervised_process where supervised_process.lease_id = ${leaseId} and supervised_process.state = 'active' and coalesce(supervised_process.provider_command, '{}'::jsonb) ? 'supervision' )`; } /** The exact active background command on one lease epoch and provider * instance. Such a command may keep running across a warm checkpoint: * Modal pauses the whole box while it snapshots, so the command is frozen rather * than racing the read, but a file it was in the middle of writing can be saved * half-written. That is deliberate. A long-running command used to * refuse every checkpoint for the box's whole lifetime, so an uncaptured * provider death lost everything since the last capture. A supervised command * runs through one too: its terminal receipt lives in the supervisor's memory * behind its control socket, never in the snapshot, and a warm concurrent * capture neither terminates the box nor settles the command. Drains, * containment and every other publication still keep the supervised proof * gate (`noActiveSupervisedProcesses`), and the database guard * `supervised_command_capture_guard` admits only the warm concurrent claim * and fold. Every other holder and every in-flight request still blocks the * capture. */ function concurrentLeaseProcess( process: SQL, lease: { id: SQL; epoch: SQL; instanceId: SQL }, ): SQL { return sql`${process}.lease_id = ${lease.id} and ${process}.lease_epoch = ${lease.epoch} and ${process}.provider_instance_id = ${lease.instanceId} and ${process}.state = 'active'`; } /** A process holder owned by a background command that may run through a warm * checkpoint (see `concurrentLeaseProcess`). */ function concurrentCommandHolder( holder: SQL, lease: { id: SQL; epoch: SQL; instanceId: SQL }, ): SQL { return sql`(${holder}.kind = 'process' and exists ( select 1 from sandbox_retained_processes concurrent_process where concurrent_process.holder_id = ${holder}.holder_id and ${concurrentLeaseProcess(sql`concurrent_process`, lease)} ))`; } /** A holder whose writes a warm point-in-time checkpoint may run around: a * background command (see `concurrentCommandHolder`), or a viewer / browser * interaction attach. A viewer's noVNC/PTY tunnel and a browser controller can * change `/workspace` without a generation admission, so their presence marks * the claim concurrent (archive one generation behind) instead of refusing it. * Refusing it starved every checkpoint for as long as a desktop or terminal tab * stayed open. `direct` and other process holders still block. */ function concurrentWriterHolder(holder: SQL, lease: { id: SQL; epoch: SQL; instanceId: SQL }): SQL { return sql`(${holder}.kind in ('viewer', 'interaction') or ${concurrentCommandHolder(holder, lease)})`; } /** The parent admission of a background command that may run through a warm * checkpoint. It stays open for the command's lifetime; it is not an in-flight * request, and treating it as one starved checkpoints for hours. */ function concurrentCommandAdmission( admission: SQL, lease: { id: SQL; epoch: SQL; instanceId: SQL }, ): SQL { return sql`exists ( select 1 from sandbox_retained_processes concurrent_process where concurrent_process.parent_admission_id = ${admission}.id and ${concurrentLeaseProcess(sql`concurrent_process`, lease)} )`; } /** True when this exact capture claim ran around active background commands * (recorded at claim time, see `claimWorkspaceArchiveCapture`). Its snapshot is * a real recovery point but may predate their later writes: the warm * publication records it one generation behind the workspace, so later * periodic captures continue and a loss restore carries the discontinuity * warning; every other publication path must not present it as complete. */ function captureRanAroundCommands(lease: SQL): SQL { return sql`(${lease}.archive_capture_id is not null and ${lease}.archive_capture_concurrent_capture_id is not distinct from ${lease}.archive_capture_id)`; } /** Read the exact generation a verified capture must later fold. This is a * preflight only: persistWarmSnapshot/persistDrainSnapshot repeat the full * epoch, provider, liveness, and generation CAS under the archive-fold lock. */ export async function readWorkspaceArchiveCapturePreflight( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; liveness: "warm" | "draining"; }, ): Promise<{ workspaceGeneration: number; archiveGeneration: number | null; archiveComplete: boolean; } | null> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` select lease.* from sandbox_leases as lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and lease.liveness = ${input.liveness} and ${noActiveSupervisedProcesses(sql`lease.id`)} and lease.lease_epoch = ${input.expectedEpoch} and lease.instance_id = ${input.expectedInstanceId} ${ input.liveness === "draining" ? sql`and (lease.refcount = 0 or lease.unobservable_command_drain_ids is not null) and not exists (select 1 from sandbox_lease_holders holder where holder.lease_id = lease.id and not (holder.kind = 'process' and exists ( select 1 from sandbox_retained_processes process where process.id = any(lease.unobservable_command_drain_ids) and process.lease_id = lease.id and process.holder_id = holder.holder_id and process.lease_epoch = lease.lease_epoch and process.provider_instance_id = lease.instance_id )))` : sql`` } and not exists ( select 1 from sandbox_workspace_mutation_admissions as admission left join session_turn_attempts as attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = lease.id and admission.lease_epoch = lease.lease_epoch and admission.provider_backend = lease.backend and admission.provider_instance_id = lease.instance_id and admission.workspace_generation <= lease.workspace_generation and admission.settled_at is null and not exists(select 1 from sandbox_retained_processes process where process.id = any(lease.unobservable_command_drain_ids) and process.parent_admission_id = admission.id and process.lease_id = lease.id and process.lease_epoch = lease.lease_epoch and process.provider_instance_id = lease.instance_id) and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)} and not (admission.id = any(coalesce(lease.deadline_forced_admission_ids, '{}'::uuid[]))) and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) ) limit 1 `); const row = rows[0]; if (!row) return null; const mapped = mapLeaseRow(row); return { workspaceGeneration: mapped.workspaceGeneration, archiveGeneration: mapped.archiveGeneration, archiveComplete: mapped.archiveComplete, }; }, ); } export const SANDBOX_REAPER_HOLD_MAX_TTL_MS = 24 * 60 * 60_000; /** Read the exact operator-hold target without exposing it across an * account/workspace mismatch. The operator CLI projects only non-secret fields * from this snapshot; resumeState remains an internal DB contract. */ export async function readSandboxLeaseReaperHoldTarget( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` select lease.* from sandbox_leases lease where lease.account_id = ${input.accountId} and lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} limit 1 `); return rows[0] ? mapLeaseRow(rows[0]) : null; }, ); } export type SandboxLeaseReaperHoldResult = | { status: "held"; renewed: boolean; lease: LeaseSnapshot } | { status: | "lease_fenced" | "not_live" | "held_by_other" | "teardown_in_progress" | "rotation_in_progress" | "provider_deadline_conflict" | "reason_conflict"; lease: LeaseSnapshot | null; }; /** * Install or renew a bounded operator preservation gate on one exact physical * lease. The row lock serializes this decision with reaper claim acquisition. * A hold never creates/resumes a provider and never overrides teardown already * issued: callers must receive a positive receipt before relying on it. */ export async function acquireSandboxLeaseReaperHold( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; holdId: string; ttlMs: number; /** Preserve this much configured rotation headroom after the hold expires. * Callers should pass the deployment's sandboxRotationLeadMs. */ providerDeadlineHeadroomMs: number; reason: string; }, ): Promise { if ( !Number.isSafeInteger(input.ttlMs) || input.ttlMs <= 0 || input.ttlMs > SANDBOX_REAPER_HOLD_MAX_TTL_MS ) { throw new Error("Sandbox reaper hold TTL must be between 1ms and 24h"); } if ( !Number.isSafeInteger(input.providerDeadlineHeadroomMs) || input.providerDeadlineHeadroomMs <= 0 || input.providerDeadlineHeadroomMs > SANDBOX_REAPER_HOLD_MAX_TTL_MS ) { throw new Error("Sandbox reaper hold provider-deadline headroom must be between 1ms and 24h"); } const reason = input.reason.trim(); if (reason.length < 1 || reason.length > 500) { throw new Error("Sandbox reaper hold reason must contain 1-500 characters"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute< LeaseRow & { reaper_hold_active: boolean; provider_hold_safe: boolean; } >(sql` select lease.*, (lease.reaper_hold_id is not null and lease.reaper_hold_until > now()) as reaper_hold_active, ( lease.provider_deadline_at is null or lease.provider_deadline_at > now() + (${input.ttlMs + input.providerDeadlineHeadroomMs} * interval '1 millisecond') ) as provider_hold_safe from sandbox_leases lease where lease.account_id = ${input.accountId} and lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || Number(row.lease_epoch) !== input.expectedEpoch || row.instance_id !== input.expectedInstanceId ) { return { status: "lease_fenced" as const, lease: row ? mapLeaseRow(row) : null, }; } if (row.instance_id === null || (row.liveness !== "warm" && row.liveness !== "draining")) { return { status: "not_live" as const, lease: mapLeaseRow(row) }; } const renewing = row.reaper_hold_active && row.reaper_hold_id === input.holdId; if (row.reaper_hold_active && !renewing) { return { status: "held_by_other" as const, lease: mapLeaseRow(row) }; } if (renewing && row.reaper_hold_reason !== reason) { return { status: "reason_conflict" as const, lease: mapLeaseRow(row), }; } if (row.archive_capture_id !== null || row.rotation_reason === "teardown_claim") { return { status: "teardown_in_progress" as const, lease: mapLeaseRow(row), }; } if (row.rotation_requested_at !== null) { return { status: "rotation_in_progress" as const, lease: mapLeaseRow(row), }; } if (!row.provider_hold_safe) { return { status: "provider_deadline_conflict" as const, lease: mapLeaseRow(row), }; } const held = await tx.execute(sql` update sandbox_leases set reaper_hold_id = ${input.holdId}::uuid, reaper_hold_until = now() + (${input.ttlMs} * interval '1 millisecond'), reaper_hold_reason = ${reason}, updated_at = now() where id = ${row.id} and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} returning * `); const lease = held[0]; if (!lease) { return { status: "lease_fenced" as const, lease: mapLeaseRow(row) }; } return { status: "held" as const, renewed: renewing, lease: mapLeaseRow(lease), }; }), ); } /** Release only the exact operator receipt on the exact physical lease. */ export async function releaseSandboxLeaseReaperHold( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; holdId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set reaper_hold_id = null, reaper_hold_until = null, reaper_hold_reason = null, updated_at = now() where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} and reaper_hold_id = ${input.holdId}::uuid returning id `); return rows.length === 1; }, ); } export type WorkspaceArchiveCaptureClaim = { id: string; operationId: string; providerRequestId: string; providerReplaySafe: boolean; takeoverSafe: boolean; attempt: number; leaseId: string; leaseEpoch: number; instanceId: string; workspaceGeneration: number; archiveGeneration: number | null; archiveComplete: boolean; startedAt: Date; deadlineAt: Date; /** Non-null only after a verified drain archive was atomically published * under this exact capture. Such a claim may finish teardown, never recapture * or release/re-arm. */ publishedAt: Date | null; }; /** Read the authoritative takeover clock for one exact unpublished capture. * Provider recovery must never compare a Postgres deadline with an application * wall clock: clock skew could otherwise fence a still-accepted provider * request early. The eventual replacement remains a separate exact CAS. */ export async function workspaceArchiveCaptureDeadlineElapsed( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; captureId: string; expectedEpoch: number; expectedInstanceId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ elapsed: boolean }>(sql` select exists ( select 1 from sandbox_leases lease where lease.account_id = ${input.accountId} and lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and lease.lease_epoch = ${input.expectedEpoch} and lease.instance_id = ${input.expectedInstanceId} and lease.archive_capture_id = ${input.captureId}::uuid and lease.archive_capture_published_at is null and lease.archive_capture_deadline_at <= now() ) as elapsed `); return rows[0]?.elapsed === true; }, ); } export type ClaimWorkspaceArchiveCaptureResult = | { status: "claimed"; claim: WorkspaceArchiveCaptureClaim; lease: LeaseSnapshot; } | { status: | "lease_fenced" | "attempt_fenced" | "reaper_held" | "capture_in_progress" | "holder_in_progress" | "mutation_in_progress" | "throttled" // A warm point-in-time capture found the archive already complete and // no writer that bypasses generation admissions on the box. | "clean"; }; /** * Atomically reserve one live provider for archive capture. Modal pauses a box * during native snapshot creation, so a read-only generation preflight is not * sufficient: every later holder acquisition and mutation admission must see * this durable claim before provider capture begins. */ export async function claimWorkspaceArchiveCapture( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; captureId: string; /** Stable logical request across retries. Old callers default to the exact * capture id and are normalized the same way by migration 0184's trigger. */ operationId?: string; attempt?: number; expectedEpoch: number; expectedInstanceId: string; liveness: "warm" | "draining"; captureTimeoutMs: number; minIntervalMs: number; /** Explicit provider-registry proof. Optional false defaults preserve safe * rolling behavior for pre-policy callers. */ providerReplaySafe?: boolean; takeoverSafe?: boolean; warmAttempt?: { sessionId: string; turnId: string; attemptId: string; holderId: string; }; /** The provider capture is a point-in-time image of a paused box (Modal * native filesystem/directory snapshots). A warm one may run around active * background commands, and any may run around a crashed worker's orphaned * request. Tar-style captures read files one by one from a * running box and keep both as blockers. */ pointInTimeCapture?: boolean; /** Draining only: the caller deletes a compute sandbox whose group ended * without capturing it (`persistDrainSnapshot`'s `groupEndDiscard`). While * this lease's group end still stands and no real rotation claimed it, * nothing will be read from the box, so the claim may be taken around a * crashed owner's orphaned request as a point-in-time capture is: the box * is deleted next and the cold commit settles the request only after * that. A rotation still captures, and keeps waiting for the request. */ groupEndDiscard?: boolean; /** Draining only: inside this window before a requested provider-deadline * rotation's deadline the save is mandatory. Requests still open on the * exact box are recorded in deadline_forced_admission_ids, captured * around, and settled with the box after termination. */ deadlineMandatoryCaptureLeadMs?: number; /** Draining only: unsettled setup requests whose provider Start outcome * is unknown, owned by a turn attempt closed at least this long ago with * no active retained process, are captured around exactly like the * mandatory pre-deadline save instead of pinning the box until then. */ abandonedSetupCaptureAfterMs?: number; /** Warm point-in-time checkpoint of a box no turn holds, kept warm by * viewers, browser/computer interactions or active background commands * (supervised or not) (e.g. while the session waits for one or for input). Requires * `pointInTimeCapture` and no `warmAttempt`: with no turn attempt to fence, * no other holder may be on the box, at least one of those must be (a box * no holder keeps warm belongs to the idle drain), and every other open * request still blocks. */ idleCheckpoint?: boolean; }, ): Promise { if ( !Number.isSafeInteger(input.captureTimeoutMs) || input.captureTimeoutMs <= 0 || input.captureTimeoutMs > 60 * 60_000 ) { throw new Error("Workspace archive capture timeout is invalid"); } const operationId = input.operationId ?? input.captureId; // A fresh admission-fenced capture gets a fresh provider request identity. // After a released failure, writers may re-arm this same lease epoch before // the drain workflow retries. Reusing its operationId could then retrieve an // older provider snapshot as the newer workspace generation. Replacements of // an uninterrupted claim retain this stored identity for late-result adoption. const providerRequestId = randomUUID(); const captureAttempt = input.attempt ?? 1; const providerReplaySafe = input.providerReplaySafe === true; const takeoverSafe = input.takeoverSafe === true; if (providerReplaySafe && !takeoverSafe) { throw new Error("Provider-replay-safe capture must also be takeover-safe"); } if (!Number.isSafeInteger(captureAttempt) || captureAttempt <= 0) { throw new Error("Workspace archive capture attempt is invalid"); } if ( !Number.isSafeInteger(input.minIntervalMs) || input.minIntervalMs < 0 || input.minIntervalMs > 24 * 60 * 60_000 ) { throw new Error("Workspace archive capture interval is invalid"); } const idleCheckpoint = input.idleCheckpoint === true; if ( idleCheckpoint && (input.liveness !== "warm" || input.warmAttempt !== undefined || input.pointInTimeCapture !== true) ) { throw new Error("Idle workspace checkpoint must be a warm point-in-time capture"); } if ((input.liveness === "warm") !== (input.warmAttempt !== undefined || idleCheckpoint)) { throw new Error("Warm workspace archive capture requires its exact turn attempt"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (input.warmAttempt) { await lockWorkspaceInferenceControl(scopedDb, input.workspaceId, "share"); const [turnAttempt] = await scopedDb .select({ accountId: schema.sessionTurnAttempts.accountId, state: schema.sessionTurnAttempts.state, outcome: schema.sessionTurnAttempts.outcome, activeAttemptId: schema.sessionTurns.activeAttemptId, sandboxGroupId: schema.sessions.sandboxGroupId, }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessionTurnAttempts.workspaceId), eq(schema.sessionTurns.sessionId, schema.sessionTurnAttempts.sessionId), eq(schema.sessionTurns.id, schema.sessionTurnAttempts.turnId), eq( schema.sessionTurns.executionGeneration, schema.sessionTurnAttempts.executionGeneration, ), ), ) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.sessionTurnAttempts.workspaceId), eq(schema.sessions.id, schema.sessionTurnAttempts.sessionId), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.warmAttempt.sessionId), eq(schema.sessionTurnAttempts.turnId, input.warmAttempt.turnId), eq(schema.sessionTurnAttempts.id, input.warmAttempt.attemptId), ), ) .limit(1); const [interruption] = turnAttempt ? await scopedDb .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, input.workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, input.warmAttempt.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, input.warmAttempt.attemptId), ), ) .limit(1) : []; if (!turnAttempt) return { status: "attempt_fenced" as const }; const attemptIsCurrent = turnAttempt.activeAttemptId === input.warmAttempt.attemptId; const attemptLive = (turnAttempt.state === "claimed" || turnAttempt.state === "running") && turnAttempt.outcome === null && attemptIsCurrent; const attemptSettledForTurnEnd = turnAttempt.state === "closed" && (turnAttempt.outcome === "completed" || turnAttempt.outcome === "failed" || turnAttempt.outcome === "requires_action") && (turnAttempt.activeAttemptId === null || attemptIsCurrent); const attemptMayCapture = turnAttempt !== undefined && turnAttempt.accountId === input.accountId && turnAttempt.sandboxGroupId === input.sandboxGroupId && !interruption && (attemptLive || attemptSettledForTurnEnd); if (!attemptMayCapture) return { status: "attempt_fenced" as const }; } const rows = await scopedDb.execute< LeaseRow & { reaper_hold_active: boolean; periodic_capture_throttled: boolean } >(sql` select lease.*, coalesce(lease.archive_capture_last_attempt_at > now() - (${input.minIntervalMs}::bigint * interval '1 millisecond'), false) as periodic_capture_throttled, (lease.reaper_hold_id is not null and lease.reaper_hold_until > now()) as reaper_hold_active from sandbox_leases lease where lease.account_id = ${input.accountId} and lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if ( !row || row.liveness !== input.liveness || (input.liveness === "draining" && Number(row.refcount) !== 0 && !row.unobservable_command_drain_ids?.length) || Number(row.lease_epoch) !== input.expectedEpoch || row.instance_id !== input.expectedInstanceId ) { return { status: "lease_fenced" as const }; } if ((input.liveness === "draining" || idleCheckpoint) && row.reaper_hold_active) { return { status: "reaper_held" as const }; } // Decided on the locked row, as the discard itself is re-checked under // this lock before anything is deleted. The claim's own `teardown_claim` // rotation, left by a released claim, is not a rotation of the box. const discardsEndedGroup = input.groupEndDiscard === true && input.liveness === "draining" && row.backend === "compute" && row.group_end_requested_at != null && (row.rotation_requested_at == null || row.rotation_reason === "teardown_claim"); // Inventory is only discovery: a later rotation owns this box's final // checkpoint. Fence the idle child under the same lease lock, without // blocking a turn's mandatory rotation checkpoint. if (idleCheckpoint && row.rotation_requested_at !== null) { return { status: "lease_fenced" as const }; } // A box no holder keeps warm belongs to the idle drain, which captures // it before teardown; an idle checkpoint would duplicate that capture. if (idleCheckpoint && Number(row.refcount) === 0) { return { status: "lease_fenced" as const }; } // Neither a new process nor a new admission can appear while this claim // is held, so "a command was running at claim time" is exactly the // condition under which the snapshot may miss later writes. const aroundCommands = (input.warmAttempt !== undefined || idleCheckpoint) && input.pointInTimeCapture === true; // A supervised command allows only a warm point-in-time capture that // runs around it on its own box: such a claim is always marked // concurrent below (the command is a concurrent process), publishes one // generation behind and never terminates the box. Drains and tar-style // captures keep waiting for its receipt. const [supervision] = await scopedDb.execute<{ safe: boolean }>(sql` select ${noActiveSupervisedProcesses(sql`${row.id}::uuid`)} or (${aroundCommands && input.liveness === "warm"} and not exists ( select 1 from sandbox_retained_processes supervised_process where supervised_process.lease_id = ${row.id} and supervised_process.state = 'active' and coalesce(supervised_process.provider_command, '{}'::jsonb) ? 'supervision' and not (supervised_process.lease_epoch = ${Number(row.lease_epoch)} and supervised_process.provider_instance_id = ${input.expectedInstanceId}) )) as safe `); if (!supervision?.safe) return { status: "mutation_in_progress" as const }; if (row.archive_capture_id !== null) { return { status: "capture_in_progress" as const }; } if (input.minIntervalMs > 0 && row.periodic_capture_throttled) { return { status: "throttled" as const }; } const leaseIdentity = { id: sql`${row.id}::uuid`, epoch: sql`${Number(row.lease_epoch)}`, instanceId: sql`${input.expectedInstanceId}`, }; const holderCounts = input.liveness === "warm" ? await scopedDb.execute<{ total: number; exact: number; }>(sql` select count(*)::integer as total, count(*) filter ( where kind = 'turn' and holder_id = ${input.warmAttempt?.holderId ?? null} )::integer as exact from sandbox_lease_holders where lease_id = ${row.id} ${ aroundCommands ? sql`and not ${concurrentWriterHolder(sql`sandbox_lease_holders`, leaseIdentity)}` : sql`` } `) : await scopedDb.execute<{ total: number; exact: number; }>(sql` select count(*)::integer as total, 0::integer as exact from sandbox_lease_holders where lease_id = ${row.id} and not (kind = 'process' and exists ( select 1 from sandbox_retained_processes process where process.id = any(${`{${(row.unobservable_command_drain_ids ?? []).join(",")}}`}::uuid[]) and process.holder_id = sandbox_lease_holders.holder_id and process.lease_id = ${row.id} )) `); if (input.warmAttempt && holderCounts[0]?.exact !== 1) { return { status: "attempt_fenced" as const }; } // The durable claim blocks new acquisitions. Requiring the warm owner to // be the sole blocking holder means every other worker/session has // relinquished its provider handle before capture can pause the box. // A warm point-in-time capture runs around writers that never release on // their own schedule: an active background command, and a // viewer or browser-interaction attach. A viewer is not passive (its // noVNC/PTY tunnel can mutate the workspace without a generation // admission), so the claim is marked concurrent below and the archive is // published one generation behind; the next capture after the writer // leaves completes it. Waiting for them instead starved checkpoints for as // long as a tab stayed open or a command ran. See // `concurrentLeaseProcess` for the torn-file trade-off. An idle // checkpoint has no owner holder of its own. Tar-style and drain captures // keep requiring every holder gone. const expectedHolderCount = input.warmAttempt ? 1 : 0; if ((holderCounts[0]?.total ?? 0) !== expectedHolderCount) { return { status: "holder_in_progress" as const }; } const forcedAdmissionIds = row.deadline_forced_admission_ids ?? []; const unsettled = await scopedDb.execute<{ id: string }>(sql` select admission.id from sandbox_workspace_mutation_admissions admission left join session_turn_attempts attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = ${row.id} and admission.lease_epoch = ${input.expectedEpoch} and admission.provider_backend = ${row.backend} and admission.provider_instance_id = ${input.expectedInstanceId} and admission.workspace_generation <= ${Number(row.workspace_generation)} and admission.settled_at is null and not exists(select 1 from sandbox_retained_processes process where process.id = any(${`{${(row.unobservable_command_drain_ids ?? []).join(",")}}`}::uuid[]) and process.parent_admission_id = admission.id and process.lease_id = ${row.id}) ${ aroundCommands ? sql`and not ${concurrentCommandAdmission(sql`admission`, leaseIdentity)}` : sql`` } ${ // A crashed worker's request may still be running a command. Only // a point-in-time capture may run around it: a warm one marks the // claim below, a drain terminates the box next. A file-by-file // tar read of the running box could publish torn state as complete. // A drain that deletes an ended group's box reads nothing from it. input.pointInTimeCapture === true || discardsEndedGroup ? sql`and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)}` : sql`` } ${ input.liveness === "draining" ? sql`and not (admission.id = any(${`{${forcedAdmissionIds.join(",")}}`}::uuid[]))` : sql`` } and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) order by admission.id `); if (unsettled.length > 0) { // Close to the provider deadline a drain must save now. Due rotations // are only stamped on warm leases, so a lease that was already // draining (no holder left) never gets one; requiring it let such a // box be killed uncaptured at the deadline. This branch is draining // only, so the deadline alone decides. const lead = input.deadlineMandatoryCaptureLeadMs; const [deadline] = input.liveness === "draining" && lead !== undefined && Number.isSafeInteger(lead) ? await scopedDb.execute<{ mandatory: boolean }>(sql` select ( ${row.provider_deadline_at ?? null}::timestamptz is not null and ${row.provider_deadline_at ?? null}::timestamptz <= now() + (${lead}::bigint * interval '1 millisecond') ) as mandatory `) : []; // A setup request whose provider Start outcome is unknown can never // settle on a live box: no exit can be observed for it, and its turn // waits (recovering) for the box to be gone. Waiting for the deadline // kept a box with no holder running for a day. Once its owner attempt // has been closed for the abandonment window, with no retained process // of that attempt, capture around exactly these setup requests; // termination then settles them and the turn's ended-epoch recovery // resumes it on the saved workspace. Only a point-in-time (Modal // snapshot) capture may run around a request that might still be // writing; a file-by-file tar read keeps waiting for the deadline. const abandonAfterMs = input.abandonedSetupCaptureAfterMs; const [abandoned] = deadline?.mandatory !== true && input.liveness === "draining" && input.pointInTimeCapture === true && abandonAfterMs !== undefined && Number.isSafeInteger(abandonAfterMs) && abandonAfterMs > 0 ? await scopedDb.execute<{ abandoned: boolean }>(sql` select coalesce(bool_and(coalesce( admission.actor_kind = 'turn' and admission.actor_id = attempt.id and admission.operation in ('lazyOwnedSandboxSetup', 'eagerOwnedSandboxSetup') and admission.route_kind = 'home' and admission.route_target_id is null and attempt.state = 'closed' and attempt.closed_at <= now() - (${abandonAfterMs}::bigint * interval '1 millisecond') and turn.status = 'recovering' and turn.active_attempt_id is null and turn.execution_generation = attempt.execution_generation and turn.metadata -> 'sandboxSetupOutcomeUnknown' @> jsonb_build_object( 'version', 1, 'turnId', turn.id::text, 'attemptId', attempt.id::text, 'reason', 'sandbox_command_start_outcome_unknown') and not exists (select 1 from sandbox_retained_processes process where process.workspace_id = attempt.workspace_id and process.session_id = attempt.session_id and process.owner_attempt_id = attempt.id and process.state = 'active'), false)), false) as abandoned from sandbox_workspace_mutation_admissions admission left join session_turn_attempts attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation left join session_turns turn on turn.workspace_id = attempt.workspace_id and turn.session_id = attempt.session_id and turn.id = attempt.turn_id where admission.id = any(${`{${unsettled .map((admission: { id: string }) => admission.id) .join(",")}}`}::uuid[]) `) : []; if (deadline?.mandatory !== true && abandoned?.abandoned !== true) { return { status: "mutation_in_progress" as const }; } // Mandatory save: no holder is left on the box (checked above), so // these requests cannot finish into a capture in time. Record exactly // them; publication excludes them, and the cold commit settles them // only after the box is terminated. await scopedDb.execute(sql` update sandbox_leases set deadline_forced_admission_ids = ${`{${[ ...forcedAdmissionIds, ...unsettled.map((admission: { id: string }) => admission.id), ].join(",")}}`}::uuid[], updated_at = now() where id = ${row.id} `); } const [concurrentCommands] = aroundCommands ? await scopedDb.execute<{ present: boolean }>(sql` select exists ( select 1 from sandbox_retained_processes concurrent_process where ${concurrentLeaseProcess(sql`concurrent_process`, leaseIdentity)} ) or exists ( select 1 from sandbox_lease_holders concurrent_writer where concurrent_writer.lease_id = ${row.id} and concurrent_writer.kind in ('viewer', 'interaction') ) or exists ( select 1 from sandbox_workspace_mutation_admissions orphaned_request where orphaned_request.lease_id = ${row.id} and orphaned_request.lease_epoch = ${input.expectedEpoch} and orphaned_request.provider_instance_id = ${input.expectedInstanceId} and ${crashedWorkerOrphanAdmissionSql(sql`orphaned_request`)} ) as present `) : []; const sessionState = row.resume_state?.sessionState && typeof row.resume_state.sessionState === "object" ? (row.resume_state.sessionState as Record) : null; const priorAtRaw = sessionState?.workspaceArchiveAt; const priorAtMs = typeof priorAtRaw === "string" ? Date.parse(priorAtRaw) : Number.NaN; const archiveGeneration = row.archive_generation === null ? null : Number(row.archive_generation); const archiveComplete = archiveGeneration !== null && archiveGeneration === Number(row.workspace_generation) && recoveryStateFromLeaseRow(row).archive.status === "available"; // Every admitted write advances the generation, and a capture taken // while an untracked writer was attached is published one generation // behind, so a complete archive with no such writer attached now, and // none attached since the last capture taken with none attached, has // nothing new to save. A viewer that attached after that capture keeps // the box dirty even after it detached, though the generation did not // move. if ( aroundCommands && archiveComplete && concurrentCommands?.present !== true && (row.untracked_writer_since ?? null) === null ) { return { status: "clean" as const }; } if ( input.minIntervalMs > 0 && Number.isFinite(priorAtMs) && Date.now() - priorAtMs < input.minIntervalMs ) { return { status: "throttled" as const }; } // The deadline is diagnostic/reconciliation truth, never permission to // clear a possibly still-running provider operation. Normal completion // clears the exact claim; stale recovery must first prove provider safety. // Start it on the authoritative DB clock at the instant the claim commits, // not on an app clock before a potentially blocked row update. const claimed = await scopedDb.execute(sql` update sandbox_leases set archive_capture_id = ${input.captureId}::uuid, archive_capture_operation_id = ${operationId}::uuid, archive_capture_provider_request_id = ${providerRequestId}::uuid, archive_capture_provider_replay_safe = ${providerReplaySafe}, archive_capture_takeover_safe = ${takeoverSafe}, archive_capture_attempt = ${captureAttempt}, archive_capture_generation = workspace_generation, archive_capture_started_at = now(), archive_capture_last_attempt_at = now(), archive_capture_deadline_at = now() + (${input.captureTimeoutMs}::bigint * interval '1 millisecond'), archive_capture_published_at = null, archive_capture_concurrent_capture_id = ${ concurrentCommands?.present === true ? input.captureId : null }::uuid, updated_at = now() where id = ${row.id} and archive_capture_id is null and workspace_generation = ${Number(row.workspace_generation)} returning * `); const lease = claimed[0]; if (!lease) return { status: "capture_in_progress" as const }; const instanceId = lease.instance_id; if (!instanceId) { throw new Error("Workspace archive capture claim returned no provider instance"); } const startedAtRaw = lease.archive_capture_started_at; const deadlineAtRaw = lease.archive_capture_deadline_at; if (!startedAtRaw || !deadlineAtRaw) { throw new Error("Workspace archive capture claim returned no timing receipt"); } const startedAt = startedAtRaw instanceof Date ? startedAtRaw : new Date(startedAtRaw); const deadlineAt = deadlineAtRaw instanceof Date ? deadlineAtRaw : new Date(deadlineAtRaw); return { status: "claimed" as const, claim: { id: input.captureId, operationId, providerRequestId, providerReplaySafe: lease.archive_capture_provider_replay_safe, takeoverSafe: lease.archive_capture_takeover_safe, attempt: captureAttempt, leaseId: lease.id, leaseEpoch: Number(lease.lease_epoch), instanceId, workspaceGeneration: Number(lease.workspace_generation), archiveGeneration, archiveComplete, startedAt, deadlineAt, publishedAt: null, }, lease: mapLeaseRow(lease), }; }, ); } /** Clear only the exact capture owner. A stale callback cannot release a * successor claim or a replacement provider epoch. */ export async function releaseWorkspaceArchiveCapture( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; captureId: string; expectedEpoch: number; expectedInstanceId: string; /** Take over a warm claim whose owner died: release it only when it is * past its database deadline, was recorded takeover-safe (a late provider * result can never publish under a replacement capture id), and no turn * holds the box. A box kept warm by background commands never drains, so * without this a dead checkpoint worker's claim fenced every later turn * and checkpoint until the provider deadline. */ onlyExpiredWarmTakeover?: boolean; /** The released draining capture settled as a failure: count it toward * this lease epoch's consecutive drain snapshot failures, atomically with * the release (a fenced, already replaced claim counts nothing). */ recordDrainCaptureFailure?: boolean; /** Called with the epoch's new consecutive failure count when * `recordDrainCaptureFailure` counted this failure (the lease was still * draining), after the release commits. */ onDrainCaptureFailureCounted?: (consecutiveFailures: number) => void; }, ): Promise { let counted: number | null = null; const released = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; const rows = await tx.execute<{ id: string; rotation_requested_at: Date | null; current_rotation_requested_at: Date | null; drain_capture_failures: number | null; liveness: string; }>(sql` with owned as ( select id, rotation_requested_at as prior_rotation_requested_at, liveness as prior_liveness from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} and archive_capture_id = ${input.captureId}::uuid and archive_capture_published_at is null ${ input.onlyExpiredWarmTakeover === true ? sql`and liveness = 'warm' and archive_capture_deadline_at <= now() and archive_capture_takeover_safe and turn_holders = 0` : sql`` } for update ) update sandbox_leases set archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, ${ input.recordDrainCaptureFailure === true ? sql`drain_capture_failures = case when sandbox_leases.liveness <> 'draining' then sandbox_leases.drain_capture_failures when sandbox_leases.drain_capture_failure_epoch = sandbox_leases.lease_epoch then sandbox_leases.drain_capture_failures + 1 else 1 end, drain_capture_first_failed_at = case when sandbox_leases.liveness <> 'draining' then sandbox_leases.drain_capture_first_failed_at when sandbox_leases.drain_capture_failure_epoch = sandbox_leases.lease_epoch then coalesce(sandbox_leases.drain_capture_first_failed_at, now()) else now() end, drain_capture_last_failed_at = case when sandbox_leases.liveness <> 'draining' then sandbox_leases.drain_capture_last_failed_at else now() end, drain_capture_failure_epoch = case when sandbox_leases.liveness <> 'draining' then sandbox_leases.drain_capture_failure_epoch else sandbox_leases.lease_epoch end,` : sql`` } rotation_requested_at = case when rotation_reason = 'teardown_claim' then null else rotation_requested_at end, rotation_reason = case when rotation_reason = 'teardown_claim' then null else rotation_reason end, updated_at = now() from owned where sandbox_leases.id = owned.id returning sandbox_leases.id, owned.prior_rotation_requested_at as rotation_requested_at, sandbox_leases.rotation_requested_at as current_rotation_requested_at, sandbox_leases.drain_capture_failures, owned.prior_liveness as liveness `); if ( input.recordDrainCaptureFailure === true && rows.length === 1 && rows[0]!.liveness === "draining" ) { counted = Number(rows[0]!.drain_capture_failures); } if ( rows.length === 1 && rows[0]!.rotation_requested_at !== null && rows[0]!.current_rotation_requested_at === null ) { await wakeSandboxLifecycleWaitersTx(tx, input); } return rows.length === 1; }), ); if (counted !== null && Number.isSafeInteger(counted) && counted > 0) { input.onDrainCaptureFailureCounted?.(counted); } return released; } /** * Replace a capture attempt without ever opening the admission gate. A generic * provider remains deadline-gated. A provider registration explicitly recorded * as takeover-safe may retry immediately, using either same-request idempotency * or an independently repeatable read-only capture. * captureId changes to fence teardown ownership; providerRequestId deliberately * does not, so a predecessor success remains adoptable by its successor. */ export async function replaceWorkspaceArchiveCaptureAfterProof( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; priorCaptureId: string; captureId: string; operationId: string; attempt: number; expectedEpoch: number; expectedInstanceId: string; captureTimeoutMs: number; }, ): Promise { if ( !Number.isSafeInteger(input.captureTimeoutMs) || input.captureTimeoutMs <= 0 || input.captureTimeoutMs > 60 * 60_000 ) { throw new Error("Workspace archive capture timeout is invalid"); } if (!Number.isSafeInteger(input.attempt) || input.attempt <= 0) { throw new Error("Workspace archive capture attempt is invalid"); } if (input.captureId === input.priorCaptureId) { throw new Error("Replacement workspace archive capture must use a new capture id"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` update sandbox_leases as lease set archive_capture_id = ${input.captureId}::uuid, archive_capture_operation_id = ${input.operationId}::uuid, archive_capture_attempt = ${input.attempt}, -- A replayed provider request would return the warm-time snapshot of -- a claim that ran around commands; request a fresh one. archive_capture_provider_request_id = case when ${captureRanAroundCommands(sql`lease`)} then ${randomUUID()}::uuid else lease.archive_capture_provider_request_id end, archive_capture_concurrent_capture_id = null, archive_capture_generation = lease.workspace_generation, archive_capture_started_at = now(), archive_capture_deadline_at = now() + (${input.captureTimeoutMs}::bigint * interval '1 millisecond'), archive_capture_published_at = null, updated_at = now() where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and lease.liveness = 'draining' and (lease.refcount = 0 or lease.unobservable_command_drain_ids is not null) and lease.lease_epoch = ${input.expectedEpoch} and lease.instance_id = ${input.expectedInstanceId} and lease.archive_capture_id = ${input.priorCaptureId}::uuid and ${noActiveSupervisedProcesses(sql`lease.id`)} and ( lease.archive_capture_operation_id <> ${input.operationId}::uuid or lease.archive_capture_attempt < ${input.attempt} ) and lease.archive_capture_generation = lease.workspace_generation and lease.archive_capture_published_at is null and (lease.reaper_hold_id is null or lease.reaper_hold_until <= now()) and ( lease.archive_capture_deadline_at <= now() or lease.archive_capture_takeover_safe ) and not exists ( select 1 from sandbox_lease_holders holder where holder.lease_id = lease.id and not (holder.kind = 'process' and exists ( select 1 from sandbox_retained_processes process where process.id = any(lease.unobservable_command_drain_ids) and process.lease_id = lease.id and process.holder_id = holder.holder_id and process.lease_epoch = lease.lease_epoch and process.provider_instance_id = lease.instance_id )) ) and not exists ( select 1 from sandbox_workspace_mutation_admissions admission left join session_turn_attempts attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = lease.id and admission.lease_epoch = lease.lease_epoch and admission.provider_backend = lease.backend and admission.provider_instance_id = lease.instance_id and admission.workspace_generation <= lease.workspace_generation and admission.settled_at is null and not exists(select 1 from sandbox_retained_processes process where process.id = any(lease.unobservable_command_drain_ids) and process.parent_admission_id = admission.id and process.lease_id = lease.id and process.lease_epoch = lease.lease_epoch and process.provider_instance_id = lease.instance_id) and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)} and not (admission.id = any(coalesce(lease.deadline_forced_admission_ids, '{}'::uuid[]))) and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) ) returning lease.* `); const lease = rows[0]; if (!lease) return null; const instanceId = lease.instance_id; if (!instanceId) { throw new Error("Replacement workspace archive capture returned no provider instance"); } const startedAtRaw = lease.archive_capture_started_at; const deadlineAtRaw = lease.archive_capture_deadline_at; if (!startedAtRaw || !deadlineAtRaw) { throw new Error("Replacement workspace archive capture returned no timing receipt"); } const providerRequestId = lease.archive_capture_provider_request_id; if (!providerRequestId) { throw new Error("Replacement workspace archive capture returned no provider request"); } const startedAt = startedAtRaw instanceof Date ? startedAtRaw : new Date(startedAtRaw); const deadlineAt = deadlineAtRaw instanceof Date ? deadlineAtRaw : new Date(deadlineAtRaw); return { id: input.captureId, operationId: input.operationId, providerRequestId, providerReplaySafe: lease.archive_capture_provider_replay_safe, takeoverSafe: lease.archive_capture_takeover_safe, attempt: input.attempt, leaseId: lease.id, leaseEpoch: Number(lease.lease_epoch), instanceId, workspaceGeneration: Number(lease.workspace_generation), archiveGeneration: lease.archive_generation === null ? null : Number(lease.archive_generation), archiveComplete: hasCompleteWorkspaceArchive(lease), startedAt, deadlineAt, publishedAt: null, }; }, ); } export type SandboxCheckpointArtifactState = | "candidate" | "current" | "previous" | "delete_pending" | "deleting" | "delete_failed" | "deleted"; export type SandboxCheckpointArtifactRegistration = { id: string; state: SandboxCheckpointArtifactState; objectId: string; }; export class SandboxCheckpointArtifactRegistrationConflictError extends Error { readonly name = "SandboxCheckpointArtifactRegistrationConflictError"; } function validatedModalCheckpoint(input: { workspaceArchive: string; workspaceArchiveMeta: SandboxArchiveRevision; }): { bytes: Uint8Array; descriptor: SandboxNativeSnapshotRevision; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; } { const descriptor = parseArchiveRevision(input.workspaceArchiveMeta); if ( descriptor?.version !== 2 || (descriptor.provider !== "modal_snapshot_filesystem" && descriptor.provider !== "modal_snapshot_directory") ) { throw new Error("Checkpoint artifact registration requires a verified Modal snapshot"); } const bytes = decodeCanonicalBase64(input.workspaceArchive); if (!bytes) { throw new Error("Checkpoint artifact archive is not canonical base64"); } const native = decodeNativeSnapshotRef(bytes); const sha256 = createHash("sha256").update(bytes).digest("hex"); if ( !native || native.provider !== descriptor.provider || native.snapshotId !== descriptor.snapshotId || native.workspacePersistence !== descriptor.workspacePersistence || descriptor.archiveBytes !== bytes.length || descriptor.archiveSha256 !== sha256 ) { throw new Error("Checkpoint artifact receipt does not match its verified descriptor"); } return { bytes, descriptor, objectKind: descriptor.provider === "modal_snapshot_filesystem" ? "modal_filesystem_snapshot" : "modal_directory_snapshot", }; } /** * Register the provider object immediately after snapshot creation returns, * before trying to publish it onto a lease. A failed/superseded publication can * therefore durably hand the object to GC instead of leaking it. */ export async function registerSandboxCheckpointArtifact( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; sourceLeaseId: string; sourceLeaseEpoch: number; sourceInstanceId: string; sourceWorkspaceGeneration: number; providerBindingKey: string; providerBinding: Record; workspaceArchive: string; workspaceArchiveMeta: SandboxArchiveRevision; /** * Workspace checkpoints are identified by their exact capture source. * Provider-image builds instead use a provider-owned idempotency key: a * retry may run from a successor verifier lease but must converge on the * same exact immutable object. The first source remains immutable * provenance; only a byte-identical object in the same tenant/group may be * reused. */ registrationIdentity?: "capture" | "provider_object"; }, ): Promise { const verified = validatedModalCheckpoint(input); const providerIdentity = canonicalModalCheckpointProviderBinding(input.providerBinding); if (!providerIdentity || providerIdentity.key !== input.providerBindingKey) { throw new Error("Modal checkpoint provider binding key is invalid"); } // The provider object already exists. Retry this idempotent transaction so // an unknown commit outcome is reconciled by reading the immutable row on the // next attempt. A true identity collision is authoritative and never retried. let lastError: unknown; for (let attempt = 0; attempt < 3; attempt += 1) { try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const inserted = await scopedDb.execute<{ id: string; state: SandboxCheckpointArtifactState; object_id: string; }>(sql` insert into sandbox_checkpoint_artifacts ( account_id, workspace_id, sandbox_group_id, source_lease_id, source_lease_epoch, source_instance_id, source_workspace_generation, provenance, provider_backend, provider_binding_key, provider_binding, object_kind, object_id, archive_base64, archive_sha256, archive_bytes, descriptor, descriptor_revision ) values ( ${input.accountId}, ${input.workspaceId}, ${input.sandboxGroupId}, ${input.sourceLeaseId}, ${input.sourceLeaseEpoch}, ${input.sourceInstanceId}, ${input.sourceWorkspaceGeneration}, 'native_capture', 'modal', ${providerIdentity.key}, ${JSON.stringify(providerIdentity.binding)}::jsonb, ${verified.objectKind}, ${verified.descriptor.snapshotId}, ${input.workspaceArchive}, ${verified.descriptor.archiveSha256}, ${verified.bytes.length}, ${JSON.stringify(verified.descriptor)}::jsonb, ${verified.descriptor.revision} ) on conflict (provider_backend, provider_binding_key, object_id) do nothing returning id, state, object_id `); const row = inserted[0] ?? ( await scopedDb.execute<{ id: string; state: SandboxCheckpointArtifactState; object_id: string; account_id: string; workspace_id: string; sandbox_group_id: string; source_lease_id: string; source_lease_epoch: number | string; source_instance_id: string | null; source_workspace_generation: number | string | null; provenance: string; archive_base64: string; archive_sha256: string; descriptor: unknown; descriptor_revision: string; object_kind: string; provider_binding: unknown; }>(sql` select id, state, object_id, account_id, workspace_id, sandbox_group_id, source_lease_id, source_lease_epoch, source_instance_id, source_workspace_generation, provenance, archive_base64, archive_sha256, descriptor, descriptor_revision, object_kind, provider_binding from sandbox_checkpoint_artifacts where provider_backend = 'modal' and provider_binding_key = ${providerIdentity.key} and object_id = ${verified.descriptor.snapshotId} limit 1 for update `) )[0]; const existingProviderObjectMatches = row && "account_id" in row && row.account_id === input.accountId && row.workspace_id === input.workspaceId && row.sandbox_group_id === input.sandboxGroupId && row.provenance === "native_capture" && row.archive_base64 === input.workspaceArchive && row.archive_sha256 === verified.descriptor.archiveSha256 && row.object_kind === verified.objectKind && canonicalModalCheckpointProviderBinding(row.provider_binding)?.key === providerIdentity.key; const existingCaptureObjectMatches = existingProviderObjectMatches && stableJson(row.descriptor) === stableJson(verified.descriptor) && row.descriptor_revision === verified.descriptor.revision; const existingCaptureMatches = existingCaptureObjectMatches && row.source_lease_id === input.sourceLeaseId && Number(row.source_lease_epoch) === input.sourceLeaseEpoch && row.source_instance_id === input.sourceInstanceId && row.source_workspace_generation !== null && Number(row.source_workspace_generation) === input.sourceWorkspaceGeneration; if ( !row || ("account_id" in row && (input.registrationIdentity === "provider_object" ? !existingProviderObjectMatches : !existingCaptureMatches)) ) { throw new SandboxCheckpointArtifactRegistrationConflictError( "Modal checkpoint object identity collision", ); } if (row.state === "deleted") { throw new SandboxCheckpointArtifactRegistrationConflictError( "Modal checkpoint object was already deleted", ); } if ( input.registrationIdentity === "provider_object" && (row.state === "delete_pending" || row.state === "delete_failed") ) { await scopedDb.execute(sql` update sandbox_checkpoint_artifacts set state = 'candidate', delete_after = null, delete_claim_id = null, delete_claimed_at = null, last_delete_error = null, updated_at = now() where id = ${row.id} and state in ('delete_pending', 'delete_failed') `); return { id: row.id, state: "candidate", objectId: row.object_id }; } return { id: row.id, state: row.state, objectId: row.object_id }; }, ); } catch (error) { if (error instanceof SandboxCheckpointArtifactRegistrationConflictError) { throw error; } lastError = error; } } throw lastError; } /** Hand an unpublished candidate to asynchronous GC. Referenced artifacts are * protected both here and by the global claim function. */ export async function markSandboxCheckpointArtifactDeletePending( db: Database, input: { accountId: string; workspaceId: string; artifactId: string; reason?: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_checkpoint_artifacts artifact set state = 'delete_pending', delete_after = now(), last_delete_error = ${input.reason?.slice(0, 4000) ?? null}, updated_at = now() where artifact.id = ${input.artifactId} and artifact.state in ('candidate', 'delete_failed') and not exists ( select 1 from sandbox_leases lease where lease.current_checkpoint_artifact_id = artifact.id or lease.previous_checkpoint_artifact_id = artifact.id ) and not exists ( select 1 from rig_versions version cross join lateral jsonb_each(version.provider_images) provider_image where version.workspace_id = ${input.workspaceId} and provider_image.value ->> 'artifactId' = artifact.id::text and provider_image.value ->> 'status' = 'ready' ) and not exists ( select 1 from rig_changes change join rig_versions base on base.id = change.base_version_id and base.workspace_id = change.workspace_id and base.active = true where change.workspace_id = ${input.workspaceId} and change.status in ('verifying', 'proposed') and change.verification #>> '{providerImage,artifactId}' = artifact.id::text and change.verification #>> '{providerImage,status}' = 'ready' ) returning artifact.id `); return rows.length > 0; }, ); } export type SandboxCheckpointArtifactGcClaim = { id: string; providerBackend: string; providerBindingKey: string; providerBinding: Record; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; objectId: string; deleteAttempts: number; }; export async function claimSandboxCheckpointArtifactsForGc( db: Database, input: { claimId: string; limit: number; claimTtlMs: number }, ): Promise { const rows = await rawRows<{ id: string; provider_backend: string; provider_binding_key: string; provider_binding: Record; object_kind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; object_id: string; delete_attempts: number | string; }>( db, sql`select * from opengeni_private.claim_sandbox_checkpoint_artifacts( ${input.claimId}::uuid, ${input.limit}, ${input.claimTtlMs} )`, ); return rows.map((row) => ({ id: row.id, providerBackend: row.provider_backend, providerBindingKey: row.provider_binding_key, providerBinding: row.provider_binding, objectKind: row.object_kind, objectId: row.object_id, deleteAttempts: Number(row.delete_attempts), })); } export async function settleSandboxCheckpointArtifactGc( db: Database, input: { artifactId: string; claimId: string; deleted: boolean; error?: string | null; retryAfterMs: number; }, ): Promise { const rows = await rawRows<{ settled: boolean }>( db, sql`select opengeni_private.settle_sandbox_checkpoint_artifact( ${input.artifactId}::uuid, ${input.claimId}::uuid, ${input.deleted}, ${input.error?.slice(0, 4000) ?? null}, ${input.retryAfterMs} ) as settled`, ); return rows[0]?.settled === true; } export async function pruneDeletedSandboxCheckpointArtifacts( db: Database, retentionMs: number, limit: number, ): Promise { const rows = await rawRows<{ pruned: number | string }>( db, sql`select opengeni_private.prune_deleted_sandbox_checkpoint_artifacts( ${retentionMs}, ${limit} ) as pruned`, ); return Number(rows[0]?.pruned ?? 0); } export async function requestDueSandboxRotationsGlobal( db: Database, leadMs: number, limit: number, ): Promise { const rows = await rawRows<{ requested: number | string }>( db, sql`select opengeni_private.request_due_sandbox_rotations( ${leadMs}, ${limit} ) as requested`, ); return Number(rows[0]?.requested ?? 0); } export const SANDBOX_CHECKPOINT_ARTIFACT_STATES = [ "candidate", "current", "previous", "delete_pending", "deleting", "delete_failed", "deleted", ] as const satisfies readonly SandboxCheckpointArtifactState[]; export async function countSandboxCheckpointArtifactsByState( db: Database, ): Promise> { const counts = Object.fromEntries( SANDBOX_CHECKPOINT_ARTIFACT_STATES.map((state) => [state, 0]), ) as Record; const rows = await rawRows<{ state: string; count: number | string }>( db, sql`select state, count from opengeni_private.sandbox_checkpoint_artifact_inventory()`, ); for (const row of rows) { if ((SANDBOX_CHECKPOINT_ARTIFACT_STATES as readonly string[]).includes(row.state)) { counts[row.state as SandboxCheckpointArtifactState] = Number(row.count); } } return counts; } export type SandboxRotationBacklog = { requested: number; overdue: number; turnBlocked: number; directBlocked: number; processBlocked: number; interactionBlocked: number; }; export async function readSandboxRotationBacklog(db: Database): Promise { const rows = await rawRows<{ requested: number | string; overdue: number | string; turn_blocked: number | string; direct_blocked: number | string; process_blocked: number | string; interaction_blocked: number | string; }>( db, sql`select backlog.*, opengeni_private.sandbox_rotation_interaction_blocked() as interaction_blocked from opengeni_private.sandbox_rotation_backlog() backlog`, ); const row = rows[0]; return { requested: Number(row?.requested ?? 0), overdue: Number(row?.overdue ?? 0), turnBlocked: Number(row?.turn_blocked ?? 0), directBlocked: Number(row?.direct_blocked ?? 0), processBlocked: Number(row?.process_blocked ?? 0), interactionBlocked: Number(row?.interaction_blocked ?? 0), }; } export type SandboxCheckpointStaleness = { /** Live Modal boxes holding a write their last checkpoint did not capture. */ dirty: number; stale4h: number; stale12h: number; /** Age of the oldest such write (clamped to box creation), seconds. */ maxAgeSeconds: number; }; /** Content-free fleet signal: how long live boxes have held unsaved changes. */ export async function readSandboxCheckpointStaleness( db: Database, ): Promise { const [row] = await rawRows<{ dirty: number | string; stale_4h: number | string; stale_12h: number | string; max_age_seconds: number | string; }>(db, sql`select * from opengeni_private.sandbox_checkpoint_staleness()`); return { dirty: Number(row?.dirty ?? 0), stale4h: Number(row?.stale_4h ?? 0), stale12h: Number(row?.stale_12h ?? 0), maxAgeSeconds: Number(row?.max_age_seconds ?? 0), }; } /** Content-free, cross-workspace operator signal reconstructed from committed * audit receipts. Unlike process-local counters, a worker crash after commit * cannot erase this short-lived warning window. */ export async function readRecentSandboxRecoveryObservations(db: Database): Promise<{ providerLosses: number; fallbackSelections: number; freshWorkspaceSelections: number; }> { const [row] = await rawRows<{ provider_losses: number | string; fallback_selections: number | string; fresh_workspace_selections?: number | string; }>(db, sql`select * from opengeni_private.sandbox_recovery_observations()`); return { providerLosses: Number(row?.provider_losses ?? 0), fallbackSelections: Number(row?.fallback_selections ?? 0), freshWorkspaceSelections: Number(row?.fresh_workspace_selections ?? 0), }; } export type LegacyModalCheckpointSlot = { accountId: string; workspaceId: string; sandboxGroupId: string; leaseId: string; leaseEpoch: number; instanceId: string; workspaceGeneration: number; slot: "current" | "previous"; archiveBase64: string; descriptor: SandboxNativeSnapshotRevision; }; export async function listLegacyModalCheckpointSlots( db: Database, limit = 100, ): Promise { const rows = await rawRows<{ account_id: string; workspace_id: string; sandbox_group_id: string; lease_id: string; lease_epoch: number | string; instance_id: string; workspace_generation: number | string; slot: "current" | "previous"; archive_base64: string; descriptor: unknown; }>(db, sql`select * from opengeni_private.list_legacy_modal_checkpoint_slots(${limit})`); return rows.flatMap((row) => { const descriptor = parseArchiveRevision(row.descriptor); return descriptor?.version === 2 ? [ { accountId: row.account_id, workspaceId: row.workspace_id, sandboxGroupId: row.sandbox_group_id, leaseId: row.lease_id, leaseEpoch: Number(row.lease_epoch), instanceId: row.instance_id, workspaceGeneration: Number(row.workspace_generation), slot: row.slot, archiveBase64: row.archive_base64, descriptor, }, ] : []; }); } export type LegacyModalCheckpointAdoptionTarget = Omit & { providerBindingKey: string; providerBinding: Record; /** A cold restore may adopt only while this exact rematerialization still * owns the warming lease. Live-lease migration leaves this unset. */ rematerializationId?: string; }; /** Atomically register and attach an exact historical Modal archive slot. * * Legacy receipts have no trustworthy capture-instance or capture-generation * metadata, so their immutable row records typed unknown provenance instead of * inventing those values. The lease lock, object insert, slot reference, and * artifact state transition commit together: a fenced adoption can never leave * an unreferenced candidate that GC might delete while the legacy slot still * depends on that provider object. */ export async function adoptLegacyModalCheckpointArtifact( db: Database, input: LegacyModalCheckpointAdoptionTarget, ): Promise { const verified = validatedModalCheckpoint({ workspaceArchive: input.archiveBase64, workspaceArchiveMeta: input.descriptor, }); const providerIdentity = canonicalModalCheckpointProviderBinding(input.providerBinding); if (!providerIdentity || providerIdentity.key !== input.providerBindingKey) { throw new Error("Modal checkpoint provider binding key is invalid"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const leaseRows = await scopedDb.execute<{ id: string; current_checkpoint_artifact_id: string | null; previous_checkpoint_artifact_id: string | null; }>(sql` select lease.id, lease.current_checkpoint_artifact_id, lease.previous_checkpoint_artifact_id from sandbox_leases lease where lease.id = ${input.leaseId}::uuid and lease.account_id = ${input.accountId}::uuid and lease.workspace_id = ${input.workspaceId}::uuid and lease.sandbox_group_id = ${input.sandboxGroupId}::uuid and lease.lease_epoch = ${input.leaseEpoch} and lease.workspace_generation = ${input.workspaceGeneration} and lease.backend = 'modal' and lease.liveness in ('warming', 'warm', 'draining') ${ input.rematerializationId ? sql`and lease.liveness = 'warming' and lease.resume_state #>> '{opengeniRecovery,restore,rematerializationId}' = ${input.rematerializationId} and lease.resume_state #>> '{opengeniRecovery,restore,status}' in ('restoring', 'verifying')` : sql`` } and ${ input.slot === "current" ? sql`lease.archive_generation = lease.workspace_generation and lease.resume_state #>> '{sessionState,workspaceArchive}' = ${input.archiveBase64} and lease.resume_state #> '{sessionState,workspaceArchiveMeta}' = ${JSON.stringify(input.descriptor)}::jsonb` : sql`lease.resume_state #>> '{sessionState,workspaceArchivePrev}' = ${input.archiveBase64} and lease.resume_state #> '{sessionState,workspaceArchivePrevMeta}' = ${JSON.stringify(input.descriptor)}::jsonb` } for update `); const lease = leaseRows[0]; if (!lease) return false; const existingReference = input.slot === "current" ? lease.current_checkpoint_artifact_id : lease.previous_checkpoint_artifact_id; if (existingReference !== null) { const exact = await scopedDb.execute<{ id: string }>(sql` select artifact.id from sandbox_checkpoint_artifacts artifact where artifact.id = ${existingReference}::uuid and artifact.account_id = ${input.accountId}::uuid and artifact.workspace_id = ${input.workspaceId}::uuid and artifact.sandbox_group_id = ${input.sandboxGroupId}::uuid and artifact.source_lease_id = ${input.leaseId}::uuid and artifact.source_lease_epoch = ${input.leaseEpoch} and artifact.source_instance_id is null and artifact.source_workspace_generation is null and artifact.provenance = 'legacy_provider_adopted' and artifact.provider_backend = 'modal' and artifact.provider_binding_key = ${providerIdentity.key} and artifact.object_kind = ${verified.objectKind} and artifact.object_id = ${verified.descriptor.snapshotId} and artifact.archive_base64 = ${input.archiveBase64} and artifact.archive_sha256 = ${verified.descriptor.archiveSha256} and artifact.descriptor = ${JSON.stringify(verified.descriptor)}::jsonb and artifact.descriptor_revision = ${verified.descriptor.revision} and artifact.state = ${input.slot} `); return exact.length === 1; } const inserted = await scopedDb.execute<{ id: string; state: SandboxCheckpointArtifactState; }>(sql` insert into sandbox_checkpoint_artifacts ( account_id, workspace_id, sandbox_group_id, source_lease_id, source_lease_epoch, source_instance_id, source_workspace_generation, provenance, provider_backend, provider_binding_key, provider_binding, object_kind, object_id, archive_base64, archive_sha256, archive_bytes, descriptor, descriptor_revision ) values ( ${input.accountId}, ${input.workspaceId}, ${input.sandboxGroupId}, ${input.leaseId}, ${input.leaseEpoch}, null, null, 'legacy_provider_adopted', 'modal', ${providerIdentity.key}, ${JSON.stringify(providerIdentity.binding)}::jsonb, ${verified.objectKind}, ${verified.descriptor.snapshotId}, ${input.archiveBase64}, ${verified.descriptor.archiveSha256}, ${verified.bytes.length}, ${JSON.stringify(verified.descriptor)}::jsonb, ${verified.descriptor.revision} ) on conflict (provider_backend, provider_binding_key, object_id) do nothing returning id, state `); const artifact = inserted[0] ?? ( await scopedDb.execute<{ id: string; state: SandboxCheckpointArtifactState; account_id: string; workspace_id: string; sandbox_group_id: string; source_lease_id: string; source_lease_epoch: number | string; source_instance_id: string | null; source_workspace_generation: number | string | null; provenance: string; archive_base64: string; archive_sha256: string; descriptor: unknown; descriptor_revision: string; object_kind: string; }>(sql` select id, state, account_id, workspace_id, sandbox_group_id, source_lease_id, source_lease_epoch, source_instance_id, source_workspace_generation, provenance, archive_base64, archive_sha256, descriptor, descriptor_revision, object_kind from sandbox_checkpoint_artifacts where provider_backend = 'modal' and provider_binding_key = ${providerIdentity.key} and object_id = ${verified.descriptor.snapshotId} limit 1 for update `) )[0]; const exactExisting = artifact !== undefined && (!("account_id" in artifact) || (artifact.account_id === input.accountId && artifact.workspace_id === input.workspaceId && artifact.sandbox_group_id === input.sandboxGroupId && artifact.source_lease_id === input.leaseId && Number(artifact.source_lease_epoch) === input.leaseEpoch && artifact.source_instance_id === null && artifact.source_workspace_generation === null && artifact.provenance === "legacy_provider_adopted" && artifact.archive_base64 === input.archiveBase64 && artifact.archive_sha256 === verified.descriptor.archiveSha256 && stableJson(artifact.descriptor) === stableJson(verified.descriptor) && artifact.descriptor_revision === verified.descriptor.revision && artifact.object_kind === verified.objectKind)); if (!artifact || !exactExisting || artifact.state === "deleted") { throw new SandboxCheckpointArtifactRegistrationConflictError( "Modal checkpoint object identity collision", ); } if (artifact.state !== "candidate") { throw new SandboxCheckpointArtifactRegistrationConflictError( "Legacy Modal checkpoint is already owned by another archive slot", ); } const published = await scopedDb.execute<{ id: string }>(sql` update sandbox_checkpoint_artifacts set state = ${input.slot}, published_at = coalesce(published_at, now()), delete_after = null, last_delete_error = null, updated_at = now() where id = ${artifact.id}::uuid and state = 'candidate' returning id `); if (published.length !== 1) { throw new Error("Legacy Modal checkpoint adoption lost its locked provider object"); } const attached = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases lease set ${ input.slot === "current" ? sql`current_checkpoint_artifact_id = ${artifact.id}::uuid` : sql`previous_checkpoint_artifact_id = ${artifact.id}::uuid` }, updated_at = now() where lease.id = ${input.leaseId}::uuid and ${ input.slot === "current" ? sql`lease.current_checkpoint_artifact_id is null` : sql`lease.previous_checkpoint_artifact_id is null` } returning lease.id `); if (attached.length !== 1) { throw new Error("Legacy Modal checkpoint adoption lost its locked archive slot"); } return true; }, ); } function publishedWorkspaceArchiveFields(input: { accountId: string; workspaceId: string; sandboxGroupId: string; workspaceArchiveMeta: SandboxArchiveRevision; workspaceArchive?: string | null; workspaceArchiveRef?: WorkspaceArchiveObjectRef | null; }): { workspaceArchive?: string; workspaceArchiveRef?: WorkspaceArchiveObjectRef; } { const ref = input.workspaceArchiveRef == null ? undefined : (validateWorkspaceArchiveObjectRef(input.workspaceArchiveRef, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, descriptor: input.workspaceArchiveMeta, }) ?? undefined); if (input.workspaceArchiveRef != null && !ref) { throw new Error( "Invalid workspace archive object ref: publication scope or descriptor mismatch", ); } const inline = typeof input.workspaceArchive === "string" && input.workspaceArchive.length > 0 ? input.workspaceArchive : undefined; if (!ref && !inline) { throw new Error("workspace archive publication requires inline bytes or an object ref"); } if (inline && ref) { const bytes = decodeCanonicalBase64(inline); if (!bytes || sha256String(bytes) !== ref.sha256 || bytes.length !== ref.bytes) { throw new Error("inline workspace archive and object-storage ref disagree"); } } if (ref) return { workspaceArchiveRef: ref }; if (!inline) { throw new Error("workspace archive publication requires inline bytes or an object ref"); } return { workspaceArchive: inline }; } /** Object-candidate outcome from the publication transaction, independent of * lifecycle `wrote`. Absent for inline/provider receipts and pure CAS checks. * `unused` is NOT a retirement receipt: only the owner of a fresh candidate with * no other publication in flight may use it for immediate cleanup. Exceptions * give no disposition (commit may have happened). Legacy/shared keys and evicted * refs need durable no-reattachment evidence before deletion. */ export type WorkspaceArchiveCandidateDisposition = "adopted" | "already_referenced" | "unused"; function workspaceArchiveCandidateFields( candidate: WorkspaceArchiveObjectRef | undefined, lockedResumeState: Record | null | undefined, ): { candidateDisposition?: WorkspaceArchiveCandidateDisposition } { if (!candidate) return {}; const sessionState = lockedResumeState?.sessionState as Record | undefined; const referenced = [ sessionState?.workspaceArchiveRef, sessionState?.workspaceArchivePrevRef, ].some((value) => { const ref = parseWorkspaceArchiveObjectRef(value); return ref?.key === candidate.key && ref.backend === candidate.backend; }); return { candidateDisposition: referenced ? "already_referenced" : "unused" }; } export async function persistDrainSnapshot( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; /** Exact source lease identity. Required for cold late-result adoption. */ expectedLeaseId?: string; expectedEpoch: number; expectedInstanceId: string; expectedWorkspaceGeneration: number; captureId: string; /** Stable provider-operation lineage across atomic claim replacements. */ providerRequestId?: string; } & ( | { /** Null performs only the epoch/instance/generation CAS check. */ workspaceArchive: null; workspaceArchiveMeta?: never; checkpointArtifactId?: never; /** A group-end delete without a capture. The CAS additionally requires, * under the same row lock, a compute lease whose group end is still * requested and that no rotation has claimed since; otherwise the * result carries `discardIneligible` and the caller must capture. */ groupEndDiscard?: true; } | { /** Base64 provider receipt or tar archive from the verified runtime capture. * Omit when `workspaceArchiveRef` locates object-storage bytes. */ workspaceArchive?: string; /** Exact descriptor is mandatory for every new publication. */ workspaceArchiveMeta: SandboxArchiveRevision; /** Object-storage locator for tar bytes. When set, inline bytes are omitted. */ workspaceArchiveRef?: WorkspaceArchiveObjectRef | null; /** Required for Modal-native descriptors; absent for actual tar archives. */ checkpointArtifactId?: string | null; } ), ): Promise<{ wrote: boolean; archiveRevision: string | null; candidateDisposition?: WorkspaceArchiveCandidateDisposition; /** Set only for `groupEndDiscard`: the exact capture still owns the lease, * but it is no longer eligible for a delete without a capture. */ discardIneligible?: true; }> { const workspaceArchiveMeta = input.workspaceArchive === null ? null : parseArchiveRevision(input.workspaceArchiveMeta); if (input.workspaceArchive !== null && !workspaceArchiveMeta) { throw new Error("Invalid verified workspace archive descriptor"); } const published = input.workspaceArchive === null ? null : publishedWorkspaceArchiveFields(input); if ( workspaceArchiveMeta?.version === 2 && (workspaceArchiveMeta.provider === "modal_snapshot_filesystem" || workspaceArchiveMeta.provider === "modal_snapshot_directory") && !input.checkpointArtifactId ) { throw new Error("Modal native checkpoint publication requires a registered artifact"); } // withRlsContext already runs `fn` inside ONE transaction with the RLS GUCs set, // so the SELECT...FOR UPDATE + UPDATE below are atomic (one snapshot, one lock) // WITHOUT an extra nested savepoint — nesting a second transaction here under // the RLS-scoped connection wedges the postgres-js client ("Failed query"). return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { // Serialize every publication, successor replacement, cold commit and late // repair on the one lease row. The mode is decided only after the lock: // 1. current draining owner (exact capture or continuous lineage), or // 2. exact cold provider-loss receipt left by confirmDrainCold. const guard = await scopedDb.execute< LeaseRow & { prior_archive: string | null; prior_archive_prev: string | null; current_checkpoint_artifact_id: string | null; previous_checkpoint_artifact_id: string | null; unsettled_mutation: boolean; supervision_safe: boolean; } >(sql` select lease.*, ${noActiveSupervisedProcesses(sql`lease.id`)} as supervision_safe, resume_state #>> '{sessionState,workspaceArchive}' as prior_archive, resume_state #>> '{sessionState,workspaceArchivePrev}' as prior_archive_prev, exists ( select 1 from sandbox_workspace_mutation_admissions as admission left join session_turn_attempts as attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = lease.id -- Only requests on this exact box can race its capture; an open -- request left on an older epoch or instance must not refuse -- every later publication. and admission.lease_epoch = lease.lease_epoch and admission.provider_instance_id = lease.instance_id and admission.workspace_generation <= ${input.expectedWorkspaceGeneration} and admission.settled_at is null and not exists(select 1 from sandbox_retained_processes process where process.id = any(lease.unobservable_command_drain_ids) and process.parent_admission_id = admission.id and process.lease_id = lease.id) and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)} and not (admission.id = any(coalesce(lease.deadline_forced_admission_ids, '{}'::uuid[]))) and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) ) as unsettled_mutation from sandbox_leases as lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} for update `); const row = guard[0]; const candidateFields = workspaceArchiveCandidateFields( published?.workspaceArchiveRef, row?.resume_state, ); if (!row || !row.supervision_safe) { return { wrote: false, archiveRevision: null, ...candidateFields, }; } const sourceLeaseMatches = input.expectedLeaseId === undefined || row.id === input.expectedLeaseId; const activeLineageMatches = row.archive_capture_id === input.captureId || (input.providerRequestId !== undefined && row.archive_capture_provider_request_id === input.providerRequestId); const activePublication = sourceLeaseMatches && row.liveness === "draining" && (Number(row.refcount) === 0 || Boolean(row.unobservable_command_drain_ids?.length)) && Number(row.lease_epoch) === input.expectedEpoch && row.instance_id === input.expectedInstanceId && Number(row.workspace_generation) === input.expectedWorkspaceGeneration && Number(row.archive_capture_generation) === input.expectedWorkspaceGeneration && row.archive_capture_id !== null && activeLineageMatches && !row.unsettled_mutation; const recovery = recoveryStateFromLeaseRow(row); const lateReceipt = recovery.lateArchiveCapture; const coldLatePublication = input.workspaceArchive !== null && input.expectedLeaseId !== undefined && input.providerRequestId !== undefined && row.id === input.expectedLeaseId && row.liveness === "cold" && Number(row.refcount) === 0 && Number(row.lease_epoch) === input.expectedEpoch + 1 && row.instance_id === null && Number(row.workspace_generation) === input.expectedWorkspaceGeneration && row.archive_capture_id === null && recovery.provider.status === "missing" && recovery.provider.instanceId === input.expectedInstanceId && recovery.restore.rematerializationId === null && (recovery.restore.status === "unrecoverable" || recovery.restore.status === "degraded" || recovery.restore.status === "pending") && lateReceipt?.sourceLeaseId === input.expectedLeaseId && lateReceipt.sourceLeaseEpoch === input.expectedEpoch && lateReceipt.sourceInstanceId === input.expectedInstanceId && lateReceipt.sourceWorkspaceGeneration === input.expectedWorkspaceGeneration && lateReceipt.providerRequestId === input.providerRequestId && // Durable publication deadline: automatic recovery decisions wait out // this window, so an archive can never land behind one. (await transactionNow(scopedDb)).getTime() < Date.parse(lateReceipt.recordedAt) + LATE_CAPTURE_PUBLICATION_WINDOW_MS && !pendingFreshWorkspaceRecovery(row.resume_state) && automaticCheckpointMarker(row.resume_state)?.status !== "accepted" && !row.unsettled_mutation; if (!activePublication && !coldLatePublication) { return { wrote: false, archiveRevision: null, ...candidateFields }; } const priorArchive = row.prior_archive ?? null; const priorArchivePrev = row.prior_archive_prev ?? null; const priorSessionState = row.resume_state?.sessionState && typeof row.resume_state.sessionState === "object" ? (row.resume_state.sessionState as Record) : null; const priorRef = parseWorkspaceArchiveObjectRef(priorSessionState?.workspaceArchiveRef); // null workspaceArchive = pure CAS-check. Keep the drain's exact capture // claim intact: it is also the durable teardown claim and must fence new // holders until provider termination commits cold or recovery replaces it. if (input.workspaceArchive === null) { // Discard eligibility is decided here, under the lock that also fences // the capture: a rotation or re-arm that committed after the reaper read // the lease turns a group-end delete back into a capture. if ( input.groupEndDiscard && !( activePublication && row.backend === "compute" && Boolean(row.group_end_requested_at) && // The capture claim stamps its own `teardown_claim` rotation; only // an earlier, real rotation needs the capture. (!row.rotation_requested_at || row.rotation_reason === "teardown_claim") ) ) { return { wrote: false, archiveRevision: null, discardIneligible: true }; } return { wrote: true, archiveRevision: null, }; } if (!published) throw new Error("Missing workspace archive publication fields"); const priorMeta = parseArchiveRevision(priorSessionState?.workspaceArchiveMeta); if (activePublication && row.archive_capture_published_at !== null) { // A predecessor and its successor may receive the same provider result. // Publication is already durable; treat this as an idempotent ownership // gate and hand any distinct unused Modal candidate to GC. if ((priorArchive === null && priorRef === null) || priorMeta === null) { throw new Error("Published workspace capture has no durable verified archive"); } if ( input.checkpointArtifactId && input.checkpointArtifactId !== row.current_checkpoint_artifact_id ) { await scopedDb.execute(sql` update sandbox_checkpoint_artifacts artifact set state = 'delete_pending', delete_after = now(), last_delete_error = 'duplicate_drain_snapshot_result', updated_at = now() where artifact.id = ${input.checkpointArtifactId}::uuid and artifact.state in ('candidate', 'delete_failed') and not exists ( select 1 from sandbox_leases lease where lease.current_checkpoint_artifact_id = artifact.id or lease.previous_checkpoint_artifact_id = artifact.id ) `); } return { wrote: true, archiveRevision: priorMeta.revision, ...candidateFields }; } const rotation = rotateWorkspaceArchives({ resumeState: row.resume_state, priorCurrentArchive: priorArchive, priorPreviousArchive: priorArchivePrev, }); const previousCheckpointArtifactId = previousCheckpointArtifactIdForRotation({ previousArchive: rotation.previousArchive, priorArchive, priorArchivePrev, currentCheckpointArtifactId: row.current_checkpoint_artifact_id, previousCheckpointArtifactId: row.previous_checkpoint_artifact_id, }); const resumeState = coldLatePublication ? archiveOnlyResumeState(row, { provider: recovery.provider, archive: recovery.archive, restore: { status: "pending", rematerializationId: null, selectedRevision: workspaceArchiveMeta?.revision ?? null, startedAt: null, completedAt: null, }, workspace: { status: "not_ready", verifiedRevision: null, verifiedAt: null, }, }) : row.resume_state; const folded = await foldWorkspaceArchiveOntoLease(scopedDb, { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, expectedEpoch: input.expectedEpoch, expectedInstanceId: input.expectedInstanceId, expectedWorkspaceGeneration: input.expectedWorkspaceGeneration, captureId: activePublication ? row.archive_capture_id : null, ...(coldLatePublication && input.providerRequestId !== undefined ? { providerRequestId: input.providerRequestId } : {}), ...(published.workspaceArchive ? { workspaceArchive: published.workspaceArchive } : {}), workspaceArchiveMeta, ...(published.workspaceArchiveRef ? { workspaceArchiveRef: published.workspaceArchiveRef } : {}), resumeState, livenessGuard: coldLatePublication ? "cold_late" : "draining", previousArchive: rotation.previousArchive, previousArchiveMeta: rotation.previousArchiveMeta, previousArchiveRef: rotation.previousArchiveRef, checkpointArtifactId: input.checkpointArtifactId ?? null, previousCheckpointArtifactId, priorCurrentCheckpointArtifactId: row.current_checkpoint_artifact_id, priorPreviousCheckpointArtifactId: row.previous_checkpoint_artifact_id, }); if (!folded) { return { wrote: false, archiveRevision: null, ...candidateFields, }; } return { wrote: true, archiveRevision: workspaceArchiveMeta?.revision ?? null, ...(published.workspaceArchiveRef ? { candidateDisposition: "adopted" as const } : {}), }; }, ); } /** * The ONE archive-fold write, shared by the drain seam (persistDrainSnapshot) * and the mid-session seam (persistWarmSnapshot) — the two differ only in * their CAS guard (draining@refcount0 vs warm) and their read-side semantics. * * Merges the NEW archive (+ its workspaceArchiveAt timestamp, the throttle * baseline for mid-session snapshots) into resume_state.sessionState. * jsonb_set's create_missing does NOT create intermediate objects, so a direct * set of '{sessionState,workspaceArchive}' is a silent no-op when * `sessionState` is absent (a null resume_state, or a legacy flat envelope). * Instead: rebuild `sessionState` as (existing sessionState OR '{}') merged * (||) with the fold — this CREATES sessionState if absent AND preserves its * existing siblings (providerState/manifest/exposedPorts). The archive is * bound as a jsonb string scalar (to_jsonb(text)). Re-asserting the caller's * CAS guard keeps the write atomic with its FOR UPDATE lock. Archive-slot * rotation is computed by rotateWorkspaceArchives before this writer is called, * so the warm and drain seams use exactly the same retention policy. */ export function rotateWorkspaceArchives(input: { resumeState: Record | null; priorCurrentArchive: string | null; priorPreviousArchive: string | null; }): { previousArchive: string | null; previousArchiveMeta: SandboxArchiveRevision | null; previousArchiveRef: WorkspaceArchiveObjectRef | null; } { const sessionState = input.resumeState?.sessionState && typeof input.resumeState.sessionState === "object" ? (input.resumeState.sessionState as Record) : {}; const previousMeta = parseArchiveRevision(sessionState.workspaceArchivePrevMeta); const previousRef = parseWorkspaceArchiveObjectRef(sessionState.workspaceArchivePrevRef); const currentRef = parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef); const recovery = input.resumeState?.opengeniRecovery && typeof input.resumeState.opengeniRecovery === "object" ? (input.resumeState.opengeniRecovery as Record) : {}; const workspace = recovery.workspace && typeof recovery.workspace === "object" ? (recovery.workspace as Record) : {}; const verifiedRevision = typeof workspace.verifiedRevision === "string" ? workspace.verifiedRevision : null; const preserveVerifiedPrevious = (input.priorPreviousArchive !== null || previousRef !== null) && previousMeta !== null && previousMeta.revision === verifiedRevision; return preserveVerifiedPrevious ? { previousArchive: previousRef ? null : input.priorPreviousArchive, previousArchiveMeta: previousMeta, previousArchiveRef: previousRef, } : { previousArchive: currentRef ? null : input.priorCurrentArchive, previousArchiveMeta: parseArchiveRevision(sessionState.workspaceArchiveMeta), previousArchiveRef: currentRef, }; } function previousCheckpointArtifactIdForRotation(input: { previousArchive: string | null; priorArchive: string | null; priorArchivePrev: string | null; currentCheckpointArtifactId: string | null; previousCheckpointArtifactId: string | null; }): string | null { // Object-storage rotation nulls inline bytes when a ref exists. `null === null` // must not promote the current Modal checkpoint into the previous slot. if (input.previousArchive === null) return null; if (input.previousArchive === input.priorArchive) return input.currentCheckpointArtifactId; if (input.previousArchive === input.priorArchivePrev) { return input.previousCheckpointArtifactId; } return null; } async function foldWorkspaceArchiveOntoLease( scopedDb: Database, input: { workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; expectedWorkspaceGeneration: number; captureId: string | null; providerRequestId?: string | null; workspaceArchive?: string; workspaceArchiveMeta: SandboxArchiveRevision | null; workspaceArchiveRef?: WorkspaceArchiveObjectRef | null; resumeState: Record | null; livenessGuard: "draining" | "warm" | "cold_late"; previousArchive: string | null; previousArchiveMeta: SandboxArchiveRevision | null; previousArchiveRef?: WorkspaceArchiveObjectRef | null; checkpointArtifactId: string | null; previousCheckpointArtifactId: string | null; priorCurrentCheckpointArtifactId: string | null; priorPreviousCheckpointArtifactId: string | null; /** The wall-clock (ISO) this archive's capture STARTED. Stamped as * workspaceArchiveAt so warm-snapshot ordering is by capture-initiation, not * land time — a late, older capture is superseded (persistWarmSnapshot's * monotonic guard). Absent (drain) → now(). */ archiveAtIso?: string; }, ): Promise { const currentLeaseEpoch = input.livenessGuard === "cold_late" ? input.expectedEpoch + 1 : input.expectedEpoch; const currentInstanceId = input.livenessGuard === "cold_late" ? null : input.expectedInstanceId; const livenessGuard = input.livenessGuard === "draining" ? // A warm claim that ran around commands may predate their last writes; // it can never publish the final drain archive. Its release // lets the drain recapture the now-quiet box. sql`lease.liveness = 'draining' and (lease.refcount = 0 or lease.unobservable_command_drain_ids is not null) and not ${captureRanAroundCommands(sql`lease`)}` : input.livenessGuard === "warm" ? sql`lease.liveness = 'warm'` : sql`lease.liveness = 'cold' and lease.refcount = 0 and lease.archive_capture_id is null`; const captureGuard = input.livenessGuard === "cold_late" ? sql` lease.resume_state #>> '{opengeniRecovery,lateArchiveCapture,providerRequestId}' = ${input.providerRequestId ?? null} and lease.resume_state #>> '{opengeniRecovery,lateArchiveCapture,sourceLeaseEpoch}' = ${String(input.expectedEpoch)} and lease.resume_state #>> '{opengeniRecovery,lateArchiveCapture,sourceInstanceId}' = ${input.expectedInstanceId} and lease.resume_state #>> '{opengeniRecovery,lateArchiveCapture,sourceWorkspaceGeneration}' = ${String(input.expectedWorkspaceGeneration)} ` : sql` lease.archive_capture_id = ${input.captureId}::uuid and lease.archive_capture_generation = ${input.expectedWorkspaceGeneration} `; const archiveAtIso = input.workspaceArchiveMeta?.capturedAt ?? input.archiveAtIso ?? new Date().toISOString(); const base = input.resumeState && typeof input.resumeState === "object" ? input.resumeState : {}; const currentSession = base.sessionState && typeof base.sessionState === "object" ? (base.sessionState as Record) : {}; const sessionState: Record = { ...currentSession, workspaceArchiveAt: archiveAtIso, }; if (input.workspaceArchiveRef) { sessionState.workspaceArchiveRef = input.workspaceArchiveRef; delete sessionState.workspaceArchive; } else if (typeof input.workspaceArchive === "string" && input.workspaceArchive.length > 0) { sessionState.workspaceArchive = input.workspaceArchive; delete sessionState.workspaceArchiveRef; } else { throw new Error("workspace archive publication requires inline bytes or an object ref"); } if (input.workspaceArchiveMeta) { sessionState.workspaceArchiveMeta = input.workspaceArchiveMeta; } else { delete sessionState.workspaceArchiveMeta; } if (input.previousArchive !== null) { sessionState.workspaceArchivePrev = input.previousArchive; } else { delete sessionState.workspaceArchivePrev; } if (input.previousArchiveMeta !== null) { sessionState.workspaceArchivePrevMeta = input.previousArchiveMeta; } else { delete sessionState.workspaceArchivePrevMeta; } if (input.previousArchiveRef) { sessionState.workspaceArchivePrevRef = input.previousArchiveRef; } else { delete sessionState.workspaceArchivePrevRef; } const folded: Record = { ...base, sessionState }; const explicitRecovery = folded.opengeniRecovery && typeof folded.opengeniRecovery === "object" ? (folded.opengeniRecovery as Record) : {}; folded.opengeniRecovery = { ...explicitRecovery, archive: archiveProjectionFromResumeState(folded), }; const foldedJson = JSON.stringify(folded); const inlineWorkspaceArchive = input.workspaceArchive ?? null; // Publication and GC must serialize on the provider-object receipt itself. // Merely checking its state in a lease UPDATE subquery permits a write-skew: // a concurrent failed callback can mark the object delete_pending after the // subquery snapshot but before we promote it. Locking the artifact first makes // lease reference + receipt->current one atomic ownership handoff. A provider // replay may return the same object to a successor after the predecessor // pessimistically handed it to GC; delete_pending/delete_failed are safe to // reclaim here because the exact active capture keeps this source receipt out // of the GC claim query. `deleting` is never reclaimable. if (input.checkpointArtifactId) { const candidate = await scopedDb.execute<{ id: string }>(sql` select artifact.id from sandbox_checkpoint_artifacts artifact join sandbox_leases lease on lease.id = artifact.source_lease_id where artifact.id = ${input.checkpointArtifactId}::uuid and lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and lease.lease_epoch = ${currentLeaseEpoch} and lease.instance_id is not distinct from ${currentInstanceId} and lease.workspace_generation = ${input.expectedWorkspaceGeneration} and artifact.account_id = lease.account_id and artifact.workspace_id = lease.workspace_id and artifact.sandbox_group_id = lease.sandbox_group_id and artifact.source_lease_epoch = ${input.expectedEpoch} and artifact.source_instance_id = ${input.expectedInstanceId} and artifact.source_workspace_generation = lease.workspace_generation and artifact.provenance = 'native_capture' and artifact.provider_backend = lease.backend and artifact.archive_base64 = ${inlineWorkspaceArchive} and artifact.descriptor_revision = coalesce(${input.workspaceArchiveMeta?.revision ?? null}, '') and artifact.state in ('candidate', 'delete_pending', 'delete_failed') for update of artifact `); if (candidate.length !== 1) return false; } const warmLeaseIdentity = { id: sql`lease.id`, epoch: sql`lease.lease_epoch`, instanceId: sql`lease.instance_id`, }; const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases as lease set resume_state = ${foldedJson}::jsonb, archive_generation = ${input.expectedWorkspaceGeneration}, current_checkpoint_artifact_id = ${input.checkpointArtifactId}::uuid, previous_checkpoint_artifact_id = ${input.previousCheckpointArtifactId}::uuid, -- A published save ends any run of drain snapshot failures: the count -- means failures of this drain since this box's last successful save -- (a re-arm to warm resets it too). drain_capture_failures = 0, drain_capture_failure_epoch = null, drain_capture_first_failed_at = null, drain_capture_last_failed_at = null, ${ input.livenessGuard === "warm" ? sql` workspace_generation = case when ${captureRanAroundCommands(sql`lease`)} then lease.workspace_generation + 1 else lease.workspace_generation end, -- A capture claimed with no viewer or interaction attached (none -- can attach while the claim is held) covers every write they -- made before it. untracked_writer_since = case when ${captureRanAroundCommands(sql`lease`)} then lease.untracked_writer_since else null end, archive_capture_concurrent_capture_id = null, archive_capture_id = null, archive_capture_operation_id = null, archive_capture_provider_request_id = null, archive_capture_provider_replay_safe = false, archive_capture_takeover_safe = false, archive_capture_attempt = null, archive_capture_generation = null, archive_capture_started_at = null, archive_capture_deadline_at = null, archive_capture_published_at = null, ` : input.livenessGuard === "draining" ? // A drain claims with no holder at all, so it covers every // earlier viewer or interaction write. sql`archive_capture_published_at = now(), untracked_writer_since = null,` : sql`` } updated_at = now() where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and ${livenessGuard} and (${noActiveSupervisedProcesses(sql`lease.id`)}${ // A warm claim that ran around a supervised command publishes one // generation behind and leaves the box and command running. input.livenessGuard === "warm" ? sql` or ${captureRanAroundCommands(sql`lease`)}` : sql`` }) and lease.lease_epoch = ${currentLeaseEpoch} and lease.instance_id is not distinct from ${currentInstanceId} and lease.workspace_generation = ${input.expectedWorkspaceGeneration} and ${captureGuard} and ( ${input.checkpointArtifactId}::uuid is null or exists ( select 1 from sandbox_checkpoint_artifacts artifact where artifact.id = ${input.checkpointArtifactId}::uuid and artifact.account_id = lease.account_id and artifact.workspace_id = lease.workspace_id and artifact.sandbox_group_id = lease.sandbox_group_id and artifact.source_lease_id = lease.id and artifact.source_lease_epoch = ${input.expectedEpoch} and artifact.source_instance_id = ${input.expectedInstanceId} and artifact.source_workspace_generation = lease.workspace_generation and artifact.provenance = 'native_capture' and artifact.archive_base64 = ${inlineWorkspaceArchive} and artifact.descriptor_revision = coalesce(${input.workspaceArchiveMeta?.revision ?? null}, '') and artifact.state in ('candidate', 'delete_pending', 'delete_failed') ) ) and not exists ( select 1 from sandbox_workspace_mutation_admissions as admission left join session_turn_attempts as attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = lease.id and admission.lease_epoch = ${input.expectedEpoch} and admission.provider_backend = lease.backend and admission.provider_instance_id = ${input.expectedInstanceId} and admission.workspace_generation <= ${input.expectedWorkspaceGeneration} and admission.settled_at is null and not exists(select 1 from sandbox_retained_processes process where lease.liveness = 'draining' and process.id = any(lease.unobservable_command_drain_ids) and process.parent_admission_id = admission.id and process.lease_id = lease.id and process.lease_epoch = lease.lease_epoch and process.provider_instance_id = lease.instance_id) ${ input.livenessGuard === "warm" ? sql`and not ${concurrentCommandAdmission(sql`admission`, warmLeaseIdentity)}` : sql`` } and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)} and not (admission.id = any(coalesce(lease.deadline_forced_admission_ids, '{}'::uuid[]))) and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) ) returning lease.id `); if (rows.length === 0) return false; if (input.checkpointArtifactId) { const published = await scopedDb.execute<{ id: string }>(sql` update sandbox_checkpoint_artifacts set state = 'current', published_at = coalesce(published_at, now()), delete_after = null, last_delete_error = null, updated_at = now() where id = ${input.checkpointArtifactId}::uuid and state in ('candidate', 'delete_pending', 'delete_failed') returning id `); if (published.length !== 1) { throw new Error("Checkpoint artifact publication lost its locked candidate"); } } if ( input.previousCheckpointArtifactId && input.previousCheckpointArtifactId !== input.checkpointArtifactId ) { await scopedDb.execute(sql` update sandbox_checkpoint_artifacts set state = 'previous', delete_after = null, last_delete_error = null, updated_at = now() where id = ${input.previousCheckpointArtifactId}::uuid and state in ('current', 'previous') `); } const evictedArtifactIds = [ input.priorCurrentCheckpointArtifactId, input.priorPreviousCheckpointArtifactId, ].filter( (id): id is string => id !== null && id !== input.checkpointArtifactId && id !== input.previousCheckpointArtifactId, ); if (evictedArtifactIds.length > 0) { await scopedDb.execute(sql` update sandbox_checkpoint_artifacts set state = 'delete_pending', delete_after = now(), updated_at = now() where id in (${sql.join( evictedArtifactIds.map((id) => sql`${id}::uuid`), sql`, `, )}) and state in ('current', 'previous', 'candidate', 'delete_failed') `); } return true; } /** * MID-SESSION /workspace snapshot fold (sandbox-file-persistence). The WARM * sibling of persistDrainSnapshot: a turn that HOLDS the live box folds a fresh * snapshot onto its own lease without draining anything. Guarded by * `liveness='warm' AND lease_epoch=expected` — a drain/re-create that raced in * (different liveness or newer epoch) writes ZERO rows → wrote:false, and the * caller simply skips (the snapshot belonged to a box the lease no longer * tracks). `workspaceArchiveAt` rides the same sessionState merge so the * throttle re-check here is ATOMIC with the write — two concurrent holders * cannot double-snapshot inside one interval. */ export async function persistWarmSnapshot( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; expectedWorkspaceGeneration: number; captureId: string; /** base64 of the provider snapshot-ref / tar archive from persistWorkspace(). * Omit when `workspaceArchiveRef` locates object-storage bytes. */ workspaceArchive?: string; /** Exact verified archive/tree descriptor produced by the runtime capture. */ workspaceArchiveMeta: SandboxArchiveRevision; /** Object-storage locator for tar bytes. When set, inline bytes are omitted. */ workspaceArchiveRef?: WorkspaceArchiveObjectRef | null; checkpointArtifactId?: string | null; /** Snapshots newer than this many ms are kept (throttle); 0 = always write. */ minIntervalMs: number; /** Wall-clock (ms) this capture STARTED. Ordering is by capture-initiation, * NOT land time: a capture that started at or before the archive already on * the lease is SUPERSEDED (a stale heartbeat capture that timed out its wait * and landed late must never overwrite a fresher turn-end snapshot or refresh * the throttle clock). Defaults to Date.now() for legacy callers/tests. */ capturedAtMs?: number; } & ( | { sessionId: string; turnId: string; attemptId: string; idleCheckpoint?: never } | { /** The capture was claimed with `idleCheckpoint`: no turn attempt * owns it, and the exact capture claim is the only owner fence. */ idleCheckpoint: true; sessionId?: never; turnId?: never; attemptId?: never; } ), ): Promise<{ wrote: boolean; throttled: boolean; superseded: boolean; archiveRevision: string | null; candidateDisposition?: WorkspaceArchiveCandidateDisposition; }> { const capturedAtMs = input.capturedAtMs ?? Date.now(); const workspaceArchiveMeta = parseArchiveRevision(input.workspaceArchiveMeta); if (!workspaceArchiveMeta) { throw new Error("Invalid verified workspace archive descriptor"); } const published = publishedWorkspaceArchiveFields(input); if ( workspaceArchiveMeta?.version === 2 && (workspaceArchiveMeta.provider === "modal_snapshot_filesystem" || workspaceArchiveMeta.provider === "modal_snapshot_directory") && !input.checkpointArtifactId ) { throw new Error("Modal native checkpoint publication requires a registered artifact"); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { // Serialize with control acceptance before touching resume state. Either // this exact attempt snapshot commits first, or Pause/Steer commits its // interruption first and the late snapshot becomes a no-op. An in-process // AbortSignal cannot close this database race. await lockWorkspaceInferenceControl(scopedDb, input.workspaceId, "share"); const turnOwner = input.idleCheckpoint === true ? null : input; const [attempt] = !turnOwner ? [] : await scopedDb .select({ accountId: schema.sessionTurnAttempts.accountId, state: schema.sessionTurnAttempts.state, outcome: schema.sessionTurnAttempts.outcome, sandboxGroupId: schema.sessions.sandboxGroupId, }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessions, and( eq(schema.sessions.id, schema.sessionTurnAttempts.sessionId), eq(schema.sessions.workspaceId, schema.sessionTurnAttempts.workspaceId), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, turnOwner.sessionId), eq(schema.sessionTurnAttempts.turnId, turnOwner.turnId), eq(schema.sessionTurnAttempts.id, turnOwner.attemptId), ), ) .limit(1); const [interruption] = attempt && turnOwner ? await scopedDb .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, input.workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, turnOwner.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, turnOwner.attemptId), ), ) .limit(1) : []; const attemptMayPersistWorkspace = attempt !== undefined && (attempt.state === "claimed" || attempt.state === "running" ? attempt.outcome === null : attempt.state === "closed" && (attempt.outcome === "completed" || attempt.outcome === "failed" || attempt.outcome === "requires_action")); // Even a replay rejected by the attempt/epoch/capture guards may name // a committed current or previous object. Inspect those slots under the // same lease lock as publication, after the canonical workspace lock. // This conveys no retirement or no-future-reattachment authority. const candidateLease = published.workspaceArchiveRef ? await scopedDb.execute<{ resume_state: Record | null }>(sql` select jsonb_build_object('sessionState', jsonb_build_object( 'workspaceArchiveRef', resume_state #> '{sessionState,workspaceArchiveRef}', 'workspaceArchivePrevRef', resume_state #> '{sessionState,workspaceArchivePrevRef}' )) as resume_state from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `) : []; const candidateFields = workspaceArchiveCandidateFields( published.workspaceArchiveRef, candidateLease[0]?.resume_state, ); if ( turnOwner && (!attempt || attempt.accountId !== input.accountId || attempt.sandboxGroupId !== input.sandboxGroupId || interruption || !attemptMayPersistWorkspace) ) { return { wrote: false, throttled: false, superseded: true, archiveRevision: null, ...candidateFields, }; } const guard = await scopedDb.execute<{ prior_archive: string | null; prior_archive_prev: string | null; prior_archive_at: string | null; current_checkpoint_artifact_id: string | null; previous_checkpoint_artifact_id: string | null; archive_generation: number | string | null; resume_state: Record | null; liveness: "warm" | "draining" | "cold" | "warming"; }>(sql` select resume_state #>> '{sessionState,workspaceArchive}' as prior_archive, resume_state #>> '{sessionState,workspaceArchivePrev}' as prior_archive_prev, resume_state #>> '{sessionState,workspaceArchiveAt}' as prior_archive_at, current_checkpoint_artifact_id, previous_checkpoint_artifact_id, archive_generation, resume_state, liveness from sandbox_leases as lease where lease.workspace_id = ${input.workspaceId} and lease.sandbox_group_id = ${input.sandboxGroupId} and lease.liveness in ('warm', 'draining') and lease.lease_epoch = ${input.expectedEpoch} and lease.instance_id = ${input.expectedInstanceId} and lease.workspace_generation = ${input.expectedWorkspaceGeneration} and lease.archive_capture_id = ${input.captureId}::uuid and lease.archive_capture_generation = ${input.expectedWorkspaceGeneration} and not exists ( select 1 from sandbox_workspace_mutation_admissions as admission left join session_turn_attempts as attempt on attempt.account_id = admission.account_id and attempt.workspace_id = admission.workspace_id and attempt.session_id = admission.session_id and attempt.turn_id = admission.turn_id and attempt.id = admission.attempt_id and attempt.execution_generation = admission.execution_generation and admission.actor_kind = 'turn' where admission.lease_id = lease.id and admission.lease_epoch = lease.lease_epoch and admission.provider_backend = lease.backend and admission.provider_instance_id = lease.instance_id and admission.workspace_generation <= ${input.expectedWorkspaceGeneration} and admission.settled_at is null and not ( lease.liveness = 'warm' and ${concurrentCommandAdmission(sql`admission`, { id: sql`lease.id`, epoch: sql`lease.lease_epoch`, instanceId: sql`lease.instance_id`, })} ) and not ${crashedWorkerOrphanAdmissionSql(sql`admission`)} and (admission.actor_kind <> 'turn' or attempt.quiesced_at is null) ) for update `); if (guard.length === 0) { return { wrote: false, throttled: false, superseded: false, archiveRevision: null, ...candidateFields, }; } const priorArchive = guard[0]!.prior_archive ?? null; const priorArchivePrev = guard[0]!.prior_archive_prev ?? null; const priorAtMs = guard[0]!.prior_archive_at ? Date.parse(guard[0]!.prior_archive_at) : Number.NaN; const priorArchiveGeneration = guard[0]!.archive_generation === null ? null : Number(guard[0]!.archive_generation); const priorArchiveComplete = priorArchiveGeneration === input.expectedWorkspaceGeneration; // MONOTONIC guard: a capture whose start is at/before the stored archive's // capture is stale (a slower-but-earlier heartbeat capture landing after a // fresher turn-end one). No-op — do NOT overwrite and do NOT advance the // throttle clock. This is what makes the bounded snapshot wait safe. if (priorArchiveComplete && Number.isFinite(priorAtMs) && capturedAtMs <= priorAtMs) { return { wrote: false, throttled: false, superseded: true, archiveRevision: null, ...candidateFields, }; } if ( input.minIntervalMs > 0 && Number.isFinite(priorAtMs) && capturedAtMs - priorAtMs < input.minIntervalMs ) { return { wrote: false, throttled: true, superseded: false, archiveRevision: null, ...candidateFields, }; } const rotation = rotateWorkspaceArchives({ resumeState: guard[0]!.resume_state, priorCurrentArchive: priorArchive, priorPreviousArchive: priorArchivePrev, }); const previousCheckpointArtifactId = previousCheckpointArtifactIdForRotation({ previousArchive: rotation.previousArchive, priorArchive, priorArchivePrev, currentCheckpointArtifactId: guard[0]!.current_checkpoint_artifact_id, previousCheckpointArtifactId: guard[0]!.previous_checkpoint_artifact_id, }); const rowLiveness = guard[0]!.liveness; if (rowLiveness !== "warm" && rowLiveness !== "draining") { return { wrote: false, throttled: false, superseded: false, archiveRevision: null, ...candidateFields, }; } const livenessGuard: "warm" | "draining" = rowLiveness; const folded = await foldWorkspaceArchiveOntoLease(scopedDb, { workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, expectedEpoch: input.expectedEpoch, expectedInstanceId: input.expectedInstanceId, expectedWorkspaceGeneration: input.expectedWorkspaceGeneration, captureId: input.captureId, ...(published.workspaceArchive ? { workspaceArchive: published.workspaceArchive } : {}), workspaceArchiveMeta, ...(published.workspaceArchiveRef ? { workspaceArchiveRef: published.workspaceArchiveRef } : {}), resumeState: guard[0]!.resume_state, livenessGuard, previousArchive: rotation.previousArchive, previousArchiveMeta: rotation.previousArchiveMeta, previousArchiveRef: rotation.previousArchiveRef, checkpointArtifactId: input.checkpointArtifactId ?? null, previousCheckpointArtifactId, priorCurrentCheckpointArtifactId: guard[0]!.current_checkpoint_artifact_id, priorPreviousCheckpointArtifactId: guard[0]!.previous_checkpoint_artifact_id, archiveAtIso: workspaceArchiveMeta.capturedAt, }); if (!folded) { return { wrote: false, throttled: false, superseded: false, archiveRevision: null, ...candidateFields, }; } return { wrote: true, throttled: false, superseded: false, archiveRevision: workspaceArchiveMeta.revision, ...(published.workspaceArchiveRef ? { candidateDisposition: "adopted" as const } : {}), }; }, ); } export async function getMaterializedSandboxFileResources( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; instanceId: string; }, ): Promise> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ file_ids: unknown }>(sql` select coalesce( jsonb_path_query_array( resume_state, '$.opengeniFileMaterialization[*] ? (@.instanceId == $instanceId).fileIds[*]', jsonb_build_object('instanceId', to_jsonb(${input.instanceId}::text)) ), '[]'::jsonb ) as file_ids from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'warm' and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.instanceId} limit 1 `); const raw = rows[0]?.file_ids; const values = Array.isArray(raw) ? raw : []; return new Set(values.filter((value): value is string => typeof value === "string")); }, ); } export async function markSandboxFileResourcesMaterialized( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; instanceId: string; fileIds: string[]; }, ): Promise<{ wrote: boolean }> { const fileIds = [...new Set(input.fileIds.filter((fileId) => fileId.length > 0))]; if (fileIds.length === 0) { return { wrote: false }; } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string }>(sql` update sandbox_leases set resume_state = jsonb_set( case when jsonb_typeof(resume_state) = 'object' then resume_state else '{}'::jsonb end, '{opengeniFileMaterialization}', ( select jsonb_agg(entry order by entry ->> 'instanceId') from ( select jsonb_build_object( 'instanceId', ${input.instanceId}::text, 'fileIds', ( select jsonb_agg(distinct value order by value) from jsonb_array_elements_text( coalesce( ( select existing -> 'fileIds' from jsonb_array_elements(coalesce(resume_state -> 'opengeniFileMaterialization', '[]'::jsonb)) existing where existing ->> 'instanceId' = ${input.instanceId} limit 1 ), '[]'::jsonb ) || ${JSON.stringify(fileIds)}::jsonb ) as merged(value) ) ) as entry union all select existing as entry from jsonb_array_elements(coalesce(resume_state -> 'opengeniFileMaterialization', '[]'::jsonb)) existing where existing ->> 'instanceId' <> ${input.instanceId} ) entries ), true ), updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and liveness = 'warm' and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.instanceId} returning id `); return { wrote: rows.length > 0 }; }, ); } // ═══════════════ Workbench v2 turn-end workspace capture ═══════ // The durable index for turn-end workspace captures. `insertWorkspaceCapture` // mirrors persistWarmSnapshot's epoch-CAS discipline and also requires the exact // closed, uninterrupted turn attempt. A cancelled attempt or superseded lease // writes ZERO rows. `revision` is explicit and unique on (session_id, revision). export type WorkspaceCaptureRow = { id: string; sessionId: string; turnId: string | null; revision: number; leaseEpoch: number; state: string; manifestKey: string | null; treeIndexKey: string | null; blobKeys: string[]; sizeBytes: number | null; stats: Record; capturedAt: string; }; export type WorkspaceCaptureCommitResult = { revision: number; events: SessionEvent[]; }; const WORKSPACE_CAPTURE_COLUMNS = sql` id, session_id, turn_id, revision, lease_epoch, state, manifest_key, tree_index_key, blob_keys, size_bytes, stats, captured_at `; function mapWorkspaceCaptureRow(row: { id: string; session_id: string; turn_id: string | null; revision: number | string; lease_epoch: number | string; state: string; manifest_key: string | null; tree_index_key: string | null; blob_keys: unknown; size_bytes: number | string | null; stats: unknown; captured_at: string | Date; }): WorkspaceCaptureRow { return { id: row.id, sessionId: row.session_id, turnId: row.turn_id, revision: Number(row.revision), leaseEpoch: Number(row.lease_epoch), state: row.state, manifestKey: row.manifest_key, treeIndexKey: row.tree_index_key, blobKeys: Array.isArray(row.blob_keys) ? (row.blob_keys as string[]) : [], sizeBytes: row.size_bytes === null ? null : Number(row.size_bytes), stats: (row.stats && typeof row.stats === "object" ? row.stats : {}) as Record, // postgres-js decodes `timestamptz` as a Date. Keep the public DB contract // canonical and driver-independent: capture manifests embed ISO strings and // the API compares this identity before it serves any blob. capturedAt: row.captured_at instanceof Date ? row.captured_at.toISOString() : new Date(row.captured_at).toISOString(), }; } type CommitWorkspaceCaptureRevisionInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; sandboxGroupId: string; expectedEpoch: number; revision: number; state: "available" | "failed"; manifestKey: string | null; treeIndexKey: string | null; blobKeys: string[]; sizeBytes: number; stats: Record; capturedAt?: Date; }; /** * Commit the attempt/control/epoch-fenced capture index and its session-scoped * announcement as one durable transition. The announcement is metadata rather * than model output, so it has no current-turn association, but it still carries * the exact attempt/generation that produced the filesystem state. */ async function commitWorkspaceCaptureRevision( db: Database, input: CommitWorkspaceCaptureRevisionInput, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); const session = locks.sessions[0]; if (!session) throw new Error(`Session not found: ${input.sessionId}`); const turn = locks.turns.find((row) => row.id === input.turnId); const attempt = locks.attempts.find((row) => row.id === input.attemptId); const [interruption] = attempt ? await tx .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, input.workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, input.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, input.attemptId), ), ) .limit(1) : []; if ( !turn || !attempt || turn.sessionId !== input.sessionId || attempt.sessionId !== input.sessionId || attempt.turnId !== input.turnId || turn.accountId !== input.accountId || attempt.accountId !== input.accountId || attempt.executionGeneration !== turn.executionGeneration || attempt.state !== "closed" || (attempt.outcome !== "completed" && attempt.outcome !== "failed" && attempt.outcome !== "requires_action") || interruption || (turn.status !== "completed" && turn.status !== "failed" && turn.status !== "requires_action") ) { return null; } // Capture yields when new work is accepted. Its last database call can // still be in flight when that cancellation arrives, so serialize this // fence with enqueue/claim on the session row and refuse older reviews. // Position is priority order, not chronology. const successor = await tx.execute<{ id: string }>(sql` select id from session_turns where workspace_id = ${input.workspaceId} and session_id = ${input.sessionId} and id <> ${input.turnId} and (created_at >= (select created_at from session_turns where id = ${input.turnId}) or status in ('queued', 'running')) limit 1 `); if (successor.length > 0) return null; const capturedAt = input.capturedAt ?? new Date(); const rows = await tx.execute<{ revision: number | string }>(sql` insert into workspace_captures (account_id, workspace_id, session_id, turn_id, revision, lease_epoch, state, manifest_key, tree_index_key, blob_keys, size_bytes, stats, captured_at) select ${input.accountId}, ${input.workspaceId}, ${input.sessionId}, ${input.turnId}, ${input.revision}, ${input.expectedEpoch}, ${input.state}, ${input.manifestKey}, ${input.treeIndexKey}, ${JSON.stringify(input.blobKeys)}::jsonb, ${input.sizeBytes}, ${JSON.stringify(input.stats)}::jsonb, ${capturedAt.toISOString()}::timestamptz where exists ( select 1 from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} ) returning revision `); const [capture] = rows; if (!capture) return null; const revision = Number(capture.revision); const type: SessionEventType = input.state === "available" ? "workspace.revision.captured" : "workspace.revision.degraded"; const payload = input.state === "available" ? { revision, turnId: input.turnId, capturedAt: capturedAt.toISOString(), leaseEpoch: input.expectedEpoch, stats: input.stats, } : { revision, turnId: input.turnId, capturedAt: capturedAt.toISOString(), leaseEpoch: input.expectedEpoch, reason: typeof input.stats.degradedReason === "string" ? input.stats.degradedReason : "repository_discovery_command_failed", }; const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type, payload: payload, clientEventId: `opengeni:workspace-capture:${revision}`, turnId: input.turnId, turnGeneration: attempt.executionGeneration, turnAttemptId: attempt.id, turnAssociation: null, duplicateOfEventId: null, duplicateReason: null, producerId: "workspace-capture", producerSeq: revision, occurredAt: capturedAt, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Workspace capture announcement was not inserted"); await tx .update(schema.sessions) .set({ lastSequence: event.sequence, updatedAt: new Date() }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { revision, events: [mapEvent(event)] }; }), ); } /** * Fenced insert of a capture revision at an EXPLICIT revision (the caller * assigns it as prevRevision+1 so the manifest blob — written before this insert * — can embed the same number). Writes ONLY when a warm lease with the expected * epoch still exists for the sandbox group (the same supersession guard * persistWarmSnapshot uses, expressed as an EXISTS on sandbox_leases). Returns * the assigned revision, or null when the fence rejected the write (interrupted * attempt, cancelled/superseded turn, or released/superseded lease). Captures for * one session are serialized (one turn at a time), so the explicit revision never * races the unique (session_id, revision) index. */ export async function insertWorkspaceCapture( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; sandboxGroupId: string; expectedEpoch: number; revision: number; manifestKey: string; treeIndexKey: string; blobKeys: string[]; sizeBytes: number; stats: Record; capturedAt?: Date; }, ): Promise { return await commitWorkspaceCaptureRevision(db, { ...input, state: "available", }); } /** * Persist an epoch-fenced degraded capture marker. * * Repository discovery is part of the capture's authority boundary: if the * platform cannot prove discovery completed, it must not publish an * authoritative-looking `available` capture with zero repositories. The * marker deliberately has no manifest/blob keys, so readers fall back to the * live box while still receiving an explicit degraded reason. */ export async function insertFailedWorkspaceCapture( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; sandboxGroupId: string; expectedEpoch: number; revision: number; stats: Record; capturedAt?: Date; }, ): Promise { return await commitWorkspaceCaptureRevision(db, { ...input, state: "failed", manifestKey: null, treeIndexKey: null, blobKeys: [], sizeBytes: 0, }); } /** The newest capture for a session (highest revision), or null if none. */ export async function latestWorkspaceCapture( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute[0]>(sql` select ${WORKSPACE_CAPTURE_COLUMNS} from workspace_captures where session_id = ${sessionId} order by revision desc limit 1 `); return rows.length ? mapWorkspaceCaptureRow(rows[0]!) : null; }); } export type SessionWorkspaceCaptureLookup = { sessionExists: boolean; capture: WorkspaceCaptureRow | null; }; /** * Resolve session existence and its newest capture in one RLS-scoped query. * * The capture metadata endpoint only needs existence for its 404 contract. Using * `getSession` there mapped the complete session, MCP metadata, and control * projection before issuing a second transaction for the capture. A lateral * lookup preserves the exact absent-session / absent-capture distinction without * loading unrelated session state or adding another database round trip. */ export async function sessionLatestWorkspaceCapture( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute<{ found_session_id: string; capture_id: string | null; capture_session_id: string | null; capture_turn_id: string | null; capture_revision: number | string | null; capture_lease_epoch: number | string | null; capture_state: string | null; capture_manifest_key: string | null; capture_tree_index_key: string | null; capture_blob_keys: unknown; capture_size_bytes: number | string | null; capture_stats: unknown; capture_captured_at: string | Date | null; }>(sql` select sessions.id as found_session_id, capture.id as capture_id, capture.session_id as capture_session_id, capture.turn_id as capture_turn_id, capture.revision as capture_revision, capture.lease_epoch as capture_lease_epoch, capture.state as capture_state, capture.manifest_key as capture_manifest_key, capture.tree_index_key as capture_tree_index_key, capture.blob_keys as capture_blob_keys, capture.size_bytes as capture_size_bytes, capture.stats as capture_stats, capture.captured_at as capture_captured_at from sessions left join lateral ( select ${WORKSPACE_CAPTURE_COLUMNS} from workspace_captures where workspace_captures.session_id = sessions.id order by workspace_captures.revision desc limit 1 ) capture on true where sessions.workspace_id = ${workspaceId} and sessions.id = ${sessionId} limit 1 `); const row = rows[0]; if (!row) return { sessionExists: false, capture: null }; if (!row.capture_id) return { sessionExists: true, capture: null }; return { sessionExists: true, capture: mapWorkspaceCaptureRow({ id: row.capture_id, session_id: row.capture_session_id!, turn_id: row.capture_turn_id, revision: row.capture_revision!, lease_epoch: row.capture_lease_epoch!, state: row.capture_state!, manifest_key: row.capture_manifest_key, tree_index_key: row.capture_tree_index_key, blob_keys: row.capture_blob_keys, size_bytes: row.capture_size_bytes, stats: row.capture_stats, captured_at: row.capture_captured_at!, }), }; }); } /** A specific capture revision for a session (the M2 file route with an explicit * `?revision=`), or null if that revision was never captured / already GC'd. */ export async function workspaceCaptureAtRevision( db: Database, workspaceId: string, sessionId: string, revision: number, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute[0]>(sql` select ${WORKSPACE_CAPTURE_COLUMNS} from workspace_captures where session_id = ${sessionId} and revision = ${revision} limit 1 `); return rows.length ? mapWorkspaceCaptureRow(rows[0]!) : null; }); } /** * Plan the keep-latest-N GC for a session. Pure read + set-difference (no * mutation): returns the evicted rows' ids, the per-revision manifest/tree blob * keys (unshared — always deletable), and the after-image blob keys owned ONLY * by evicted revisions (union(evicted) minus union(surviving) — a content- * addressed blob shared with a surviving revision is NEVER deleted). The caller * deletes storage first (idempotent), then deletes the rows (F9 ordering — the * new revision is already committed by the time GC runs). */ export type WorkspaceCaptureGcRow = { id: string; manifestKey: string | null; treeIndexKey: string | null; blobKeys: string[]; }; export type WorkspaceCaptureGcPlan = { evictedRowIds: string[]; deleteBlobKeys: string[]; deletePerRevisionKeys: string[]; }; /** * Pure keep-latest-N set-difference (extracted for direct unit testing). `rows` * MUST be ordered newest-revision-first. The first keepN survive; the rest are * evicted. A content-addressed after-image blob key owned by an evicted revision * is deleted ONLY when NO surviving revision also references it (shared blobs are * never deleted); per-revision manifest/tree keys are unshared → always deleted. */ export function computeWorkspaceCaptureGcPlan( rows: WorkspaceCaptureGcRow[], keepN: number, ): WorkspaceCaptureGcPlan { const survivors = rows.slice(0, Math.max(0, keepN)); const evicted = rows.slice(Math.max(0, keepN)); const survivingBlobKeys = new Set(); for (const r of survivors) for (const k of r.blobKeys) survivingBlobKeys.add(k); const deleteBlobKeys = new Set(); const deletePerRevisionKeys: string[] = []; const evictedRowIds: string[] = []; for (const r of evicted) { evictedRowIds.push(r.id); if (r.manifestKey) deletePerRevisionKeys.push(r.manifestKey); if (r.treeIndexKey) deletePerRevisionKeys.push(r.treeIndexKey); for (const k of r.blobKeys) if (!survivingBlobKeys.has(k)) deleteBlobKeys.add(k); } return { evictedRowIds, deleteBlobKeys: [...deleteBlobKeys], deletePerRevisionKeys, }; } export async function planWorkspaceCaptureGc( db: Database, input: { workspaceId: string; sessionId: string; keepN: number }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await scopedDb.execute<{ id: string; revision: number | string; manifest_key: string | null; tree_index_key: string | null; blob_keys: unknown; }>(sql` select id, revision, manifest_key, tree_index_key, blob_keys from workspace_captures where session_id = ${input.sessionId} order by revision desc `); return computeWorkspaceCaptureGcPlan( rows.map( (r: { id: string; manifest_key: string | null; tree_index_key: string | null; blob_keys: unknown; }) => ({ id: r.id, manifestKey: r.manifest_key, treeIndexKey: r.tree_index_key, blobKeys: Array.isArray(r.blob_keys) ? (r.blob_keys as string[]) : [], }), ), input.keepN, ); }); } /** Delete evicted capture rows by id (call AFTER their storage blobs are gone). */ export async function deleteWorkspaceCaptureRows( db: Database, input: { workspaceId: string; rowIds: string[] }, ): Promise { if (input.rowIds.length === 0) return 0; return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const result = await scopedDb.execute<{ id: string }>(sql` delete from workspace_captures where id in (${sql.join( input.rowIds.map((id) => sql`${id}`), sql`, `, )}) returning id `); return result.length; }); } // §4.9 — non-locking snapshot for the API handshake & health. export async function readLease( db: Database, workspaceId: string, sandboxGroupId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute(sql` select * from sandbox_leases where workspace_id = ${workspaceId} and sandbox_group_id = ${sandboxGroupId} limit 1 `); return rows[0] ? mapLeaseRow(rows[0]) : null; }); } /** The session's sandbox group's latest save when it deliberately left * rebuildable folders out (a drain's reduced save, DC-G3), else null. A later * complete save replaces it, so the answer is current on every turn. */ export async function readSandboxReducedSave( db: Database, workspaceId: string, sessionId: string, ): Promise<{ capturedAt: string; omittedPaths: string[] } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb.execute(sql` select lease.* from sandbox_leases lease join sessions session on session.workspace_id = lease.workspace_id and session.sandbox_group_id = lease.sandbox_group_id where session.workspace_id = ${workspaceId} and session.id = ${sessionId} limit 1 `); const current = rows[0] ? recoveryStateFromLeaseRow(rows[0]).archive.current : null; if (current?.version !== 1 || !Array.isArray(current.omittedPaths)) return null; const omittedPaths = current.omittedPaths.filter( (path): path is string => typeof path === "string" && path.length > 0, ); return omittedPaths.length ? { capturedAt: current.capturedAt, omittedPaths } : null; }); } /** * Waits while a sandbox group's lease is warming, the spawner that won * cold->warming still bringing its box up, reading it every `pollMs`. Returns * the first read that is no longer warming (warm once the spawner commits, * cold or draining if its attempt ended, null if the lease is gone), or the * last read, still warming, once `timeoutMs` has passed. An abort of `signal` * ends the wait with its reason. */ export async function waitWhileLeaseWarming( db: Database, workspaceId: string, sandboxGroupId: string, options: { timeoutMs: number; pollMs: number; signal?: AbortSignal | undefined }, ): Promise { const deadline = Date.now() + options.timeoutMs; let lease: LeaseSnapshot | null = null; do { await waitForSandboxTransition( Math.max(0, Math.min(options.pollMs, deadline - Date.now())), options.signal, "sandbox warming wait cancelled", ); lease = await readLease(db, workspaceId, sandboxGroupId); if (lease?.liveness !== "warming") return lease; } while (Date.now() < deadline); return lease; } // P4.2 — record the (re-)resolved desktop data-plane URL on an ALREADY-WARM // lease, EPOCH-FENCED. commitWarmingToWarm records the URL at cold→warming→warm // (the spawn path); this is the WARM-path counterpart used when a viewer mints // the URL against a box that some other holder already brought up, and on // rollover-rotation (re-resolve under the current epoch). The fence is the // split-brain guard: a stale-epoch writer (a box re-established under a newer // epoch) updates ZERO rows and the caller backs off. Returns the updated // snapshot, or null on a fence miss (epoch advanced / lease vanished). export async function recordLeaseDataPlaneUrl( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; dataPlaneUrl: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` update sandbox_leases set data_plane_url = ${input.dataPlaneUrl ?? null}, updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} and liveness in ('warm', 'draining') returning * `); return rows[0] ? mapLeaseRow(rows[0]) : null; }, ); } // P5.t — record the (re-)resolved ttyd terminal data-plane URL (7681) on an // ALREADY-WARM lease, EPOCH-FENCED. The exact terminal twin of // recordLeaseDataPlaneUrl: the REAL PTY rides a SEPARATE provider tunnel from the // desktop noVNC, so its URL is cached in its own column. mintTerminalStream calls // this after resolving the 7681 tunnel; the fast-path then re-mints only a fresh // token against the cached URL. The fence is the split-brain guard (a stale-epoch // writer updates ZERO rows). Returns the updated snapshot, or null on a fence // miss (epoch advanced / lease vanished). export async function recordLeaseTerminalDataPlaneUrl( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; terminalDataPlaneUrl: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` update sandbox_leases set terminal_data_plane_url = ${input.terminalDataPlaneUrl ?? null}, updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} and liveness in ('warm', 'draining') returning * `); return rows[0] ? mapLeaseRow(rows[0]) : null; }, ); } /** Record the browserd controller tunnel for one exact warm provider instance. * Unlike desktop/terminal viewer URLs, this endpoint is an internal transport * cache: controller bearer tokens still enforce per-resource authority. */ export async function recordLeaseControllerDataPlaneUrl( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; controllerDataPlaneUrl: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute(sql` update sandbox_leases set controller_data_plane_url = ${input.controllerDataPlaneUrl ?? null}, updated_at = now() where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.expectedEpoch} and instance_id = ${input.expectedInstanceId} and liveness in ('warm', 'draining') returning * `); return rows[0] ? mapLeaseRow(rows[0]) : null; }, ); } // ============================================================================ // Bring-your-own-compute (M2): first-class swappable sandboxes + enrollment + // per-machine metrics + the per-session epoch-fenced active-sandbox pointer // (migration 0024). All workspace-scoped behind // the same RLS the lease DAOs use. // ============================================================================ export type SandboxKind = (typeof schema.sandboxKindValues)[number]; export type EnrollmentExposure = (typeof schema.enrollmentExposureValues)[number]; export type EnrollmentStatus = (typeof schema.enrollmentStatusValues)[number]; export type EnrollmentOs = (typeof schema.enrollmentOsValues)[number]; export type AgentUpdateStatus = (typeof schema.agentUpdateStatusValues)[number]; export type EnrollmentAgentUpdateRecord = { operationId: string; status: AgentUpdateStatus; targetVersion: string; expectedBinarySha256: string | null; errorCode: string | null; blockers?: Array<{ kind: string; count: number }>; retryable: boolean; rolledBack: boolean; connectionInstanceId: string; connectionGeneration: number; requestedAt: string; updatedAt: string; completedAt: string | null; }; export type EnrollmentRecord = { id: string; accountId: string; workspaceId: string; scope: "organization" | "workspace" | "user"; generation: number; /** "sandbox" is the agent inside one Opengeni compute sandbox, bound to * `sandboxGroupId`; such enrollments are never machines. Absent in rows * read through the scoped machine listing, which returns machines only. */ kind?: "machine" | "sandbox"; sandboxGroupId?: string | null; sandboxId?: string | null; sandboxName?: string | null; /** Null exactly for sandbox enrollments, which hold no credential. */ pubkey: string | null; exposure: EnrollmentExposure; hasDisplay: boolean; opStream: boolean; /** Set when a display exists but capture is not permitted (macOS Screen Recording * not granted); null when capture is permitted or the machine is headless. */ desktopUnavailableReason: string | null; allowScreenControl: boolean; operationPolicy: { memoryMaxBytes: number | null; memoryHighBytes: number | null; cpuMaxMillicores: number | null; revision: number; updatedAt: string | null; }; status: EnrollmentStatus; credentialGeneration: number; /** Exact live runner instance receiving this machine's control traffic. */ connectionInstanceId: string | null; /** Monotonic authority generation, advanced only when a different runner claims. */ connectionGeneration: number; /** Server-clock expiry for the live runner claim. */ connectionLeaseExpiresAt: string | null; /** Valid competing processes denied while another runner held authority. */ connectionDuplicateDeniedCount: number; connectionDuplicateDeniedAt: string | null; os: EnrollmentOs; arch: string; /** Exact absolute launch root last reported by an authoritative runner Hello. */ workspaceRoot: string | null; lastSeenAt: string | null; /** When the machine announced a clean GoingOffline; the liveness derivation reads * an un-cleared marker as offline immediately. NULL ⇒ no goodbye pending. */ wentOfflineAt: string | null; /** The typed reason string of the pending clean going-offline (e.g. * GOING_OFFLINE_REASON_UPDATE); NULL when there is no un-cleared marker. */ wentOfflineReason: string | null; agentVersion: string | null; agentBinarySha256: string | null; agentUpdateChannel: "stable" | "beta" | null; agentCapabilities: Record; agentUpdate: EnrollmentAgentUpdateRecord | null; /** When the current run of unsuccessful update attempts first postponed * the update for managed browsers in use, or null. A run continues while * the latest attempt failed retryably or was postponed. */ agentUpdateBrowsersWaitSince: string | null; /** Attempts of the current run for the current target that failed for a * reason other than a busy machine (`update_busy_*`), before the current * operation. */ agentUpdateFailedAttempts: number; /** The announced time at which an automatic update closes an older * agent's managed browsers, or null. */ agentUpdateBrowsersCloseAt: string | null; createdAt: string; revokedAt: string | null; updatedAt: string; /** Where an organization machine works (migration 1190); null for workspace * and personal machines. */ reach?: OrganizationComputeReach | null; }; function mapEnrollment(row: typeof schema.enrollments.$inferSelect): EnrollmentRecord { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, scope: row.authorityScope as EnrollmentRecord["scope"], generation: Number(row.generation), kind: row.kind === "sandbox" ? "sandbox" : "machine", sandboxGroupId: row.sandboxGroupId ?? null, sandboxId: null, sandboxName: null, pubkey: row.pubkey, exposure: row.exposure as EnrollmentExposure, hasDisplay: row.hasDisplay, opStream: row.opStream, desktopUnavailableReason: row.desktopUnavailableReason ?? null, allowScreenControl: row.allowScreenControl, operationPolicy: { memoryMaxBytes: row.operationMemoryMaxBytes ?? null, memoryHighBytes: row.operationMemoryHighBytes ?? null, cpuMaxMillicores: row.operationCpuMaxMillicores ?? null, revision: Number(row.operationPolicyRevision), updatedAt: row.operationPolicyUpdatedAt?.toISOString() ?? null, }, status: row.status as EnrollmentStatus, credentialGeneration: Number(row.credentialGeneration), connectionInstanceId: row.connectionInstanceId ?? null, connectionGeneration: Number(row.connectionGeneration), connectionLeaseExpiresAt: row.connectionLeaseExpiresAt?.toISOString() ?? null, connectionDuplicateDeniedCount: Number(row.connectionDuplicateDeniedCount), connectionDuplicateDeniedAt: row.connectionDuplicateDeniedAt?.toISOString() ?? null, os: row.os as EnrollmentOs, arch: row.arch, workspaceRoot: row.workspaceRoot ?? null, lastSeenAt: row.lastSeenAt ? row.lastSeenAt.toISOString() : null, wentOfflineAt: row.wentOfflineAt ? row.wentOfflineAt.toISOString() : null, wentOfflineReason: row.wentOfflineReason ?? null, agentVersion: row.agentVersion ?? null, agentBinarySha256: row.agentBinarySha256 ?? null, agentUpdateChannel: row.agentUpdateChannel === "stable" || row.agentUpdateChannel === "beta" ? row.agentUpdateChannel : null, agentCapabilities: row.agentCapabilities ?? {}, agentUpdate: row.agentUpdateOperationId && row.agentUpdateStatus && row.agentUpdateTargetVersion && row.agentUpdateConnectionInstanceId && row.agentUpdateConnectionGeneration !== null && row.agentUpdateRequestedAt && row.agentUpdateUpdatedAt ? { operationId: row.agentUpdateOperationId, status: row.agentUpdateStatus as AgentUpdateStatus, targetVersion: row.agentUpdateTargetVersion, expectedBinarySha256: row.agentUpdateExpectedBinarySha256 ?? null, errorCode: row.agentUpdateErrorCode ?? null, blockers: row.agentUpdateBlockers, retryable: row.agentUpdateRetryable, rolledBack: row.agentUpdateRolledBack, connectionInstanceId: row.agentUpdateConnectionInstanceId, connectionGeneration: row.agentUpdateConnectionGeneration, requestedAt: row.agentUpdateRequestedAt.toISOString(), updatedAt: row.agentUpdateUpdatedAt.toISOString(), completedAt: row.agentUpdateCompletedAt?.toISOString() ?? null, } : null, agentUpdateBrowsersWaitSince: row.agentUpdateBrowsersWaitSince?.toISOString() ?? null, agentUpdateFailedAttempts: row.agentUpdateFailedAttempts ?? 0, agentUpdateBrowsersCloseAt: row.agentUpdateBrowsersCloseAt?.toISOString() ?? null, createdAt: row.createdAt.toISOString(), revokedAt: row.revokedAt ? row.revokedAt.toISOString() : null, updatedAt: row.updatedAt.toISOString(), reach: organizationComputeReach(row), }; } export type SandboxRecord = { id: string; accountId: string; workspaceId: string; kind: SandboxKind; name: string; enrollmentId: string | null; scope?: "organization" | "workspace" | "user"; generation?: number; createdAt: string; updatedAt: string; }; function mapSandbox(row: typeof schema.sandboxes.$inferSelect): SandboxRecord { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, kind: row.kind as SandboxKind, name: row.name, enrollmentId: row.enrollmentId ?? null, scope: "workspace", generation: 1, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } // ---- enrollments ---------------------------------------------------------- // Register (or idempotently re-register) a machine. A re-enroll of the SAME // (workspace, pubkey) is an UPSERT — it refreshes the consent/OS fields and, if // the machine was previously revoked, re-activates it (status->active, revoked_at // cleared) — never a duplicate machine row. Every conflict is a fresh // re-enrollment and atomically advances credential_generation, invalidating every // older bearer. The agent's ed25519 pubkey is the machine identity; the unique // (workspace, pubkey) index is the conflict target. export async function createEnrollment( db: Database, input: { accountId: string; workspaceId: string; pubkey: string; exposure?: EnrollmentExposure; hasDisplay?: boolean; allowScreenControl?: boolean; os?: EnrollmentOs; arch?: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.enrollments) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pubkey: input.pubkey, exposure: input.exposure ?? "whole-machine", hasDisplay: input.hasDisplay ?? false, allowScreenControl: input.allowScreenControl ?? false, os: input.os ?? "linux", arch: input.arch ?? "x86_64", status: "active", }) .onConflictDoUpdate({ target: [schema.enrollments.workspaceId, schema.enrollments.pubkey], targetWhere: sql`authority_scope = 'workspace'`, set: { exposure: input.exposure ?? "whole-machine", hasDisplay: input.hasDisplay ?? false, allowScreenControl: input.allowScreenControl ?? false, os: input.os ?? "linux", arch: input.arch ?? "x86_64", // A re-enroll re-activates a previously revoked machine. status: "active", revokedAt: null, credentialGeneration: sql`${schema.enrollments.credentialGeneration} + 1`, // A fresh enrollment credential is a new authority family. The old // process must not retain its live data-plane address. connectionInstanceId: null, connectionLeaseExpiresAt: null, updatedAt: new Date(), }, }) .returning(); if (!row) { throw new Error("Failed to create enrollment"); } return mapEnrollment(row); }, ); } export async function getEnrollment( db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string }, enrollmentId: string, ): Promise { if (typeof access !== "string") { return ( (await listEnrollments(db, access)).find((enrollment) => enrollment.id === enrollmentId) ?? null ); } const workspaceId = access; try { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, workspaceId), eq(schema.enrollments.id, enrollmentId), ), ) .limit(1); return row ? mapEnrollment(row) : null; }); } catch (error) { // A signed credential can outlive its workspace. Treat that as an absent // enrollment, not an outage, without swallowing database/RLS failures. if (error instanceof WorkspaceNotFoundError && error.workspaceId === workspaceId) return null; throw error; } } /** Read an enrollment only while its exact runner claim is live according to * PostgreSQL's clock. Callers receive capability + process identity from one * snapshot and never reinterpret lease time using an API host's wall clock. */ export async function getLiveEnrollmentConnection( db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string }, enrollmentId: string, ): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: EnrollmentRecord }>( scopedDb, sql`select value from list_scoped_enrollments( ${access.accountId}::uuid, ${access.workspaceId}::uuid, null, 'active' ) value where value->>'id' = ${enrollmentId} and nullif(value->>'connectionInstanceId', '') is not null and nullif(value->>'connectionLeaseExpiresAt', '')::timestamptz > clock_timestamp() limit 1`, ); return row?.value ?? null; }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, workspaceId), eq(schema.enrollments.id, enrollmentId), eq(schema.enrollments.status, "active"), isNotNull(schema.enrollments.connectionInstanceId), isNotNull(schema.enrollments.connectionLeaseExpiresAt), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), ), ) .limit(1); return row ? mapEnrollment(row) : null; }); } export async function assertPersonalMachineForAttempt( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; enrollmentId: string; requireActiveSandbox?: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { await setMachineAttemptSubject(scopedDb, input.subjectId); const [row] = await rawRows<{ authorized: boolean }>( scopedDb, sql`select assert_session_attempt_personal_machine( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer, ${input.enrollmentId}::uuid, ${input.requireActiveSandbox !== false} ) as authorized`, ); return row?.authorized === true; }); } /** Resolve one personal Connected Machine's live runner only after the exact * accepted attempt and its immutable snapshot/current grant pass pre-use in the * same transaction and PostgreSQL snapshot. This is the last DB boundary used * immediately before a worker or one-off provider dispatch. */ export async function resolvePersonalMachineConnectionForAttempt( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; enrollmentId: string; requireActiveSandbox?: boolean; }, ): Promise { return (await resolvePersonalMachineRouteForAttempt(db, input))?.liveConnection ?? null; } /** Preserve authorized machine metadata while its runner is offline. Admission * and liveness are separate: startup may bind the normal offline transport. */ export async function resolvePersonalMachineRouteForAttempt( db: Database, input: Parameters[1], ): Promise<{ enrollment: EnrollmentRecord; liveConnection: EnrollmentRecord | null } | null> { return await withRlsContext(db, input, async (scopedDb) => { await setMachineAttemptSubject(scopedDb, input.subjectId); const [row] = await rawRows<{ value: EnrollmentRecord | null; live: boolean | null }>( scopedDb, sql`select machine.value->'enrollment' as value, nullif(machine.value->'enrollment'->>'connectionInstanceId', '') is not null and nullif(machine.value->'enrollment'->>'connectionLeaseExpiresAt', '')::timestamptz > clock_timestamp() as live from get_session_attempt_machine( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer, null, ${input.enrollmentId}::uuid, ${input.requireActiveSandbox !== false}, false ) machine(value) limit 1`, ); if (!row?.value) return null; return { enrollment: row.value, liveConnection: row.live ? row.value : null }; }); } export async function authorizePersonalMachineForAttempt( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; enrollmentId: string; requireActiveSandbox?: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); await scopedDb.execute(sql`select set_config( 'opengeni.initiating_human_subject_id', ${input.subjectId}, true )`); const [row] = await rawRows<{ authorized: boolean }>( scopedDb, sql`select authorize_session_attempt_personal_machine( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer, ${input.enrollmentId}::uuid ) and assert_session_attempt_personal_machine( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer, ${input.enrollmentId}::uuid, ${input.requireActiveSandbox !== false} ) as authorized`, ); return row?.authorized === true; }); } /** Revision-fenced workspace-operator update of one Connected Machine's optional * command resource policy. NULL remains unrestricted. The active-enrollment check, * CAS, mutation, and audit receipt share one RLS transaction. */ export async function updateEnrollmentOperationPolicy( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; subjectId?: string; expectedRevision: number; memoryMaxBytes: number | null; memoryHighBytes: number | null; cpuMaxMillicores?: number | null; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); const [row] = await scopedDb .update(schema.enrollments) .set({ operationMemoryMaxBytes: input.memoryMaxBytes, operationMemoryHighBytes: input.memoryHighBytes, ...(input.cpuMaxMillicores !== undefined ? { operationCpuMaxMillicores: input.cpuMaxMillicores } : {}), operationPolicyRevision: sql`${schema.enrollments.operationPolicyRevision} + 1`, operationPolicyUpdatedAt: now, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.operationPolicyRevision, input.expectedRevision), ), ) .returning(); if (!row) return null; await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.operation_policy.updated", targetType: "enrollment", targetId: input.enrollmentId, metadata: { revision: Number(row.operationPolicyRevision), memoryMaxBytes: row.operationMemoryMaxBytes, memoryHighBytes: row.operationMemoryHighBytes, cpuMaxMillicores: row.operationCpuMaxMillicores, }, }); return mapEnrollment(row); }, ); } /** Change where an organization machine works. The workspace it was connected * from always has it; chats and schedules in a workspace it no longer works * in fail at their next attach or attempt instead of using it. */ export async function updateOrganizationMachineReach( db: Database, enrollmentId: string, input: OrganizationComputeReachInput, ): Promise { const normalized = await normalizeOrganizationComputeReach(db, input); if (!normalized.ok) return { status: "unknown_workspaces", workspaceIds: normalized.workspaceIds }; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.homeWorkspaceId }, async (scopedDb) => { const where = and( eq(schema.enrollments.accountId, input.accountId), eq(schema.enrollments.workspaceId, input.homeWorkspaceId), eq(schema.enrollments.id, enrollmentId), eq(schema.enrollments.kind, "machine"), eq(schema.enrollments.authorityScope, "organization"), eq(schema.enrollments.status, "active"), ); const [before] = await scopedDb .select({ allowedWorkspaceIds: schema.enrollments.allowedWorkspaceIds, allowPersonalWorkspaces: schema.enrollments.allowPersonalWorkspaces, allowManagedWorkspaces: schema.enrollments.allowManagedWorkspaces, }) .from(schema.enrollments) .where(where) .for("update") .limit(1); if (!before) return { status: "not_found" }; const [row] = await scopedDb .update(schema.enrollments) .set({ allowedWorkspaceIds: normalized.allowedWorkspaceIds, allowPersonalWorkspaces: input.allowPersonalWorkspaces, ...(input.allowManagedWorkspaces !== undefined ? { allowManagedWorkspaces: input.allowManagedWorkspaces } : {}), updatedAt: new Date(), }) .where(where) .returning(); if (!row) return { status: "not_found" }; await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.homeWorkspaceId, subjectId: input.subjectId, action: "connected_machine.reach.changed", targetType: "enrollment", targetId: enrollmentId, metadata: { from: before, to: { allowedWorkspaceIds: row.allowedWorkspaceIds, allowPersonalWorkspaces: row.allowPersonalWorkspaces, allowManagedWorkspaces: row.allowManagedWorkspaces, }, }, }); return { status: "updated", reach: { homeWorkspaceId: row.workspaceId, allowedWorkspaceIds: row.allowedWorkspaceIds ?? null, allowPersonalWorkspaces: row.allowPersonalWorkspaces, allowManagedWorkspaces: row.allowManagedWorkspaces, }, }; }, ); } export type EnrollmentConnectionClaim = { claimed: boolean; connectionInstanceId: string | null; connectionGeneration: number; connectionLeaseExpiresAt: string | null; }; async function enrollmentConnectionClock(scopedDb: Database): Promise { const [row] = await rawRows<{ now: Date | string }>( scopedDb, sql`select clock_timestamp() as now`, ); const now = row?.now instanceof Date ? row.now : row?.now ? new Date(row.now) : null; if (!now || !Number.isFinite(now.getTime())) { throw new Error("Failed to read the database clock for enrollment connection authority"); } return now; } /** * Claims or renews one enrollment's exact live runner instance under the * enrollment-row lock. A second process holding the same valid bearer is denied * while the current runner heartbeats. Once the lease expires, a successor * advances the generation and receives a different NATS address; the old socket * can no longer receive operations even if its short-lived user JWT has not yet * expired. */ export async function claimEnrollmentConnection( db: Database, input: { workspaceId: string; enrollmentId: string; credentialGeneration: number; connectionInstanceId: string; leaseMs: number; }, ): Promise { if (!input.connectionInstanceId || input.connectionInstanceId.length > 128) { throw new Error("connection instance id must be 1-128 characters"); } if (!Number.isSafeInteger(input.leaseMs) || input.leaseMs < 1_000) { throw new Error("connection lease must be at least one second"); } return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), ), ) .for("update") .limit(1); if ( !row || row.status !== "active" || Number(row.credentialGeneration) !== input.credentialGeneration ) { return { claimed: false, connectionInstanceId: row?.connectionInstanceId ?? null, connectionGeneration: Number(row?.connectionGeneration ?? 0), connectionLeaseExpiresAt: row?.connectionLeaseExpiresAt?.toISOString() ?? null, }; } // The database clock is the sole authority for connection leases. Different // API replicas may have slightly different wall clocks, but they all claim // and expire the enrollment row under this transaction's database time. const now = await enrollmentConnectionClock(scopedDb); const sameInstance = row.connectionInstanceId === input.connectionInstanceId; const existingLease = row.connectionLeaseExpiresAt; const claimAvailable = sameInstance || row.connectionInstanceId === null || existingLease === null || existingLease.getTime() <= now.getTime(); if (!claimAvailable) { const incumbentInstanceId = row.connectionInstanceId; if (!incumbentInstanceId) { throw new Error("Unavailable connection claim had no incumbent runner"); } await scopedDb .update(schema.enrollments) .set({ connectionDuplicateDeniedCount: sql`${schema.enrollments.connectionDuplicateDeniedCount} + 1`, connectionDuplicateDeniedAt: now, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.credentialGeneration, input.credentialGeneration), eq(schema.enrollments.connectionInstanceId, incumbentInstanceId), ), ); return { claimed: false, connectionInstanceId: row.connectionInstanceId, connectionGeneration: Number(row.connectionGeneration), connectionLeaseExpiresAt: existingLease?.toISOString() ?? null, }; } const leaseExpiresAt = new Date(now.getTime() + input.leaseMs); const connectionGeneration = Number(row.connectionGeneration) + (sameInstance ? 0 : 1); const [updated] = await scopedDb .update(schema.enrollments) .set({ connectionInstanceId: input.connectionInstanceId, connectionGeneration, connectionLeaseExpiresAt: leaseExpiresAt, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.credentialGeneration, input.credentialGeneration), ), ) .returning({ id: schema.enrollments.id }); if (updated?.id !== input.enrollmentId) { throw new Error("Enrollment authority changed while row lock was held"); } return { claimed: true, connectionInstanceId: input.connectionInstanceId, connectionGeneration, connectionLeaseExpiresAt: leaseExpiresAt.toISOString(), }; }); } /** Renew only the exact active runner. Stale heartbeats never extend or steal a * successor's lease. */ export async function renewEnrollmentConnection( db: Database, input: { accountId?: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; leaseMs: number; }, ): Promise<{ renewed: boolean; enrollment: EnrollmentRecord | null }> { const renew = async (scopedDb: Database) => { // Resolve the database clock once in the UPDATE, rather than a separate // network exchange. Return the exact runner's accepted metadata so the // heartbeat does not need an enrollment read before or after renewal. const heartbeatClock = scopedDb .$with("heartbeat_clock", { now: sql`clock_timestamp()`.as("now") }) .as(sql`select clock_timestamp() as now`); const heartbeatNow = sql`${heartbeatClock.now}`; const [row] = await scopedDb .with(heartbeatClock) .update(schema.enrollments) .set({ connectionLeaseExpiresAt: sql`${heartbeatNow} + ${input.leaseMs} * interval '1 millisecond'`, lastSeenAt: heartbeatNow, wentOfflineAt: null, wentOfflineReason: null, updatedAt: heartbeatNow, }) .from(heartbeatClock) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), ), ) .returning(getTableColumns(schema.enrollments)); return { renewed: row !== undefined, enrollment: row ? mapEnrollment(row) : null }; }; return input.accountId !== undefined ? await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, renew, ) : await withWorkspaceRls(db, input.workspaceId, renew); } /** Release only the exact active runner. A late goodbye from a fenced process is * ignored and cannot mark its successor offline. */ export async function releaseEnrollmentConnection( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; reason: string; }, ): Promise<{ released: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = await enrollmentConnectionClock(scopedDb); const rows = await scopedDb .update(schema.enrollments) .set({ connectionInstanceId: null, connectionLeaseExpiresAt: null, wentOfflineAt: now, wentOfflineReason: input.reason, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), ), ) .returning({ id: schema.enrollments.id }); return { released: rows.length === 1 }; }, ); } // List a workspace's enrollments, newest first. `status` filters the lifecycle // (omit for all; 'active' for the Machines dashboard's live list). export async function listEnrollments( db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string }, options: { status?: EnrollmentStatus } = {}, ): Promise { if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const rows = await rawRows<{ value: EnrollmentRecord }>( scopedDb, sql`select value from list_scoped_enrollments( ${access.accountId}::uuid, ${access.workspaceId}::uuid, null, ${options.status ?? "active"} ) value`, ); return rows.map((row) => row.value); }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { // Machines only: a compute sandbox's enrollment is never a machine. const where = and( eq(schema.enrollments.workspaceId, workspaceId), eq(schema.enrollments.kind, "machine"), ...(options.status ? [eq(schema.enrollments.status, options.status)] : []), ); const rows = await scopedDb .select() .from(schema.enrollments) .where(where) .orderBy(desc(schema.enrollments.createdAt)); return rows.map(mapEnrollment); }); } export type MachineRemovalOutcome = (typeof schema.machineRemovalOperationOutcomeValues)[number]; export type MachineRemovalBlockCode = | "active_route" | "active_commands" | "machine_home" | "active_lease" | "recovery_pending" | "not_selfhosted"; export type MachineRemovalResult = { enrollmentId: string; outcome: MachineRemovalOutcome; removed: boolean; machineName: string | null; lastSeenAt: string | null; revokedAt: string | null; code: MachineRemovalBlockCode | null; message: string; action: string; dependentSessions: Array<{ id: string; title: string | null }>; }; export class MachineRemovalIdempotencyError extends Error { override readonly name = "MachineRemovalIdempotencyError"; } export class MachineRemovalRevisionConflictError extends Error { override readonly name = "MachineRemovalRevisionConflictError"; constructor( message: string, readonly currentUpdatedAt: string, ) { super(message); } } function machineRemovalFingerprint(enrollmentId: string, expectedUpdatedAt?: string): string { return createHash("sha256") .update( JSON.stringify({ enrollmentId, expectedUpdatedAt: expectedUpdatedAt ?? null, }), ) .digest("hex"); } function machineRemovalResultFromStored(value: unknown): MachineRemovalResult { if (!value || typeof value !== "object") { throw new Error("Invalid stored machine removal result"); } const result = value as Partial; const dependentSessions = result.dependentSessions ?? []; if ( typeof result.enrollmentId !== "string" || (result.outcome !== "removed" && result.outcome !== "already_removed" && result.outcome !== "blocked") || typeof result.removed !== "boolean" || (result.machineName !== null && typeof result.machineName !== "string") || (result.lastSeenAt !== null && typeof result.lastSeenAt !== "string") || (result.revokedAt !== null && typeof result.revokedAt !== "string") || (result.code !== null && result.code !== "active_route" && result.code !== "active_commands" && result.code !== "machine_home" && result.code !== "active_lease" && result.code !== "recovery_pending" && result.code !== "not_selfhosted") || typeof result.message !== "string" || typeof result.action !== "string" || !Array.isArray(dependentSessions) || dependentSessions.some( (session) => !session || typeof session !== "object" || typeof session.id !== "string" || (session.title !== null && typeof session.title !== "string"), ) ) { throw new Error("Invalid stored machine removal result"); } return { ...(result as MachineRemovalResult), dependentSessions }; } /** * Remove one connected-machine enrollment without deleting durable identity, * conversation, or audit evidence. Idle sessions using the machine are detached * to `none`; active work and recovery fences still block removal. The enrollment * row is the lifecycle truth: status -> revoked rejects future auth-callout/ * heartbeat/reconnect attempts, while a fresh device-flow re-enrollment can * reactivate the same public-key identity with a new credential family. * * The operation key is scoped to the workspace and is receipt-backed. A retry * with the same key and request fingerprint replays the exact committed result; * a different fingerprint is rejected rather than risking an accidental replay * against a changed control-plane revision. */ export async function removeEnrollment( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; operationKey: string; expectedUpdatedAt?: string; subjectId?: string | null; }, ): Promise { const operationKey = input.operationKey.trim(); if (operationKey.length === 0 || operationKey.length > 200) { throw new Error("machine removal operation key must be 1-200 characters"); } const requestFingerprint = machineRemovalFingerprint(input.enrollmentId, input.expectedUpdatedAt); return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { // Serialize retries for one workspace/key before inspecting or inserting // the receipt. The enrollment lock below independently serializes removal // against re-enrollment, heartbeat auth, and route admission. await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`machine-removal:${input.workspaceId}:${operationKey}`}, 0))`, ); const [existingOperation] = await scopedDb .select({ fingerprint: schema.machineRemovalOperations.requestFingerprint, result: schema.machineRemovalOperations.result, }) .from(schema.machineRemovalOperations) .where( and( eq(schema.machineRemovalOperations.workspaceId, input.workspaceId), eq(schema.machineRemovalOperations.operationKey, operationKey), ), ) .for("update") .limit(1); if (existingOperation) { if (existingOperation.fingerprint !== requestFingerprint) { throw new MachineRemovalIdempotencyError( "machine removal idempotency key was already used with a different request", ); } return machineRemovalResultFromStored(existingOperation.result); } const [enrollment] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), ), ) .for("update") .limit(1); if (!enrollment) { return null; } if ( input.expectedUpdatedAt !== undefined && !Number.isFinite(Date.parse(input.expectedUpdatedAt)) ) { throw new Error("expectedUpdatedAt must be a valid timestamp"); } if ( input.expectedUpdatedAt !== undefined && Date.parse(input.expectedUpdatedAt) !== enrollment.updatedAt.getTime() ) { throw new MachineRemovalRevisionConflictError( "machine changed since it was loaded; refresh the machine and retry", enrollment.updatedAt.toISOString(), ); } const sandboxes = await scopedDb .select({ id: schema.sandboxes.id, kind: schema.sandboxes.kind, name: schema.sandboxes.name, }) .from(schema.sandboxes) .where( and( eq(schema.sandboxes.workspaceId, input.workspaceId), eq(schema.sandboxes.enrollmentId, input.enrollmentId), ), ) .orderBy(asc(schema.sandboxes.createdAt)) .for("share"); const nonSelfhosted = sandboxes.find((sandbox) => sandbox.kind !== "selfhosted"); const machine = sandboxes.find((sandbox) => sandbox.kind === "selfhosted") ?? null; const dependentSessions: Array<{ id: string; title: string | null }> = []; const baseResult = { enrollmentId: enrollment.id, machineName: machine?.name ?? null, lastSeenAt: enrollment.lastSeenAt?.toISOString() ?? null, revokedAt: enrollment.revokedAt?.toISOString() ?? null, dependentSessions, }; if (nonSelfhosted) { const result: MachineRemovalResult = { ...baseResult, outcome: "blocked", removed: false, code: "not_selfhosted", message: "This enrollment is not a self-hosted machine and cannot be removed here.", action: "Use the sandbox's own lifecycle controls instead.", }; await scopedDb.insert(schema.machineRemovalOperations).values({ accountId: input.accountId, workspaceId: input.workspaceId, enrollmentId: enrollment.id, operationKey, requestFingerprint, outcome: result.outcome, result, }); await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.removal_blocked", targetType: "enrollment", targetId: enrollment.id, metadata: { code: result.code, message: result.message }, }); return result; } if (enrollment.status === "revoked") { const result: MachineRemovalResult = { ...baseResult, outcome: "already_removed", removed: false, code: null, message: "This machine was already removed. Its history remains available for audit.", action: "Enroll it again through a fresh human-approved device flow if it should reconnect.", }; await scopedDb.insert(schema.machineRemovalOperations).values({ accountId: input.accountId, workspaceId: input.workspaceId, enrollmentId: enrollment.id, operationKey, requestFingerprint, outcome: result.outcome, result, }); await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.removal_replayed", targetType: "enrollment", targetId: enrollment.id, metadata: { outcome: result.outcome }, }); return result; } if (machine) { const activePointers = await rawRows<{ sessionId: string; title: string | null; activeTurnId: string | null; sandboxBackend: string; }>( scopedDb, sql` select session_id as "sessionId", title, active_turn_id as "activeTurnId", sandbox_backend as "sandboxBackend" from list_scoped_machine_dependent_sessions( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${machine.id}::uuid ) `, ); dependentSessions.push( ...activePointers.map((pointer) => ({ id: pointer.sessionId, title: pointer.title?.trim() || null, })), ); // A conversation with a queued, paused or recovering turn is not work // running on the machine; only the machine's lease below proves that. // Such conversations are detached like idle ones: their next attempt // finds no machine route and uses their managed sandbox instead. // ("active_commands" remains a valid code in stored older results.) const waitingTurns = activePointers.filter((pointer) => pointer.activeTurnId !== null); const [lease] = await scopedDb .select({ liveness: schema.sandboxLeases.liveness, refcount: schema.sandboxLeases.refcount, turnHolders: schema.sandboxLeases.turnHolders, viewerHolders: schema.sandboxLeases.viewerHolders, archiveCaptureId: schema.sandboxLeases.archiveCaptureId, rotationRequestedAt: schema.sandboxLeases.rotationRequestedAt, }) .from(schema.sandboxLeases) .where( and( eq(schema.sandboxLeases.workspaceId, input.workspaceId), eq(schema.sandboxLeases.sandboxGroupId, machine.id), ), ) .for("update") .limit(1); if ( lease && (lease.liveness !== "cold" || lease.refcount > 0 || lease.turnHolders > 0 || lease.viewerHolders > 0 || lease.archiveCaptureId !== null || lease.rotationRequestedAt !== null) ) { const code: MachineRemovalBlockCode = lease.turnHolders > 0 || lease.refcount > 0 || lease.viewerHolders > 0 ? "active_lease" : lease.liveness === "warming" || lease.liveness === "draining" || lease.archiveCaptureId !== null || lease.rotationRequestedAt !== null ? "recovery_pending" : "active_lease"; const result: MachineRemovalResult = { ...baseResult, outcome: "blocked", removed: false, code, message: code === "recovery_pending" ? "Machine has unreconciled recovery or archive work in progress." : "Machine still owns a live lease or active holder.", action: code === "recovery_pending" ? "Wait for recovery to settle, then refresh and retry." : "Stop or detach the active work, then retry removal.", }; await scopedDb.insert(schema.machineRemovalOperations).values({ accountId: input.accountId, workspaceId: input.workspaceId, enrollmentId: enrollment.id, operationKey, requestFingerprint, outcome: result.outcome, result, }); await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.removal_blocked", targetType: "enrollment", targetId: enrollment.id, metadata: { code: result.code, message: result.message }, }); return result; } // An idle conversation is not data living on the machine. Detach it // atomically and make a machine-primary session explicitly compute-less; // its durable messages/history remain intact. A managed sandbox can be // selected later without inventing a fake migration of machine files. const detached = await rawRows<{ sessionId: string; title: string | null; }>( scopedDb, sql` select session_id as "sessionId", title from detach_scoped_machine_dependent_sessions( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${machine.id}::uuid ) `, ); const dependentIds = new Set(dependentSessions.map((session) => session.id)); for (const session of detached) { if (dependentIds.has(session.sessionId)) continue; dependentIds.add(session.sessionId); dependentSessions.push({ id: session.sessionId, title: session.title?.trim() || null, }); } if (detached.length > 0) { await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.sessions_detached", targetType: "enrollment", targetId: enrollment.id, metadata: { sessionIds: detached.map((session) => session.sessionId), // Turns that were waiting (queued, paused or recovering) when // the machine was detached from their conversations. waitingTurnIds: waitingTurns.map((pointer) => pointer.activeTurnId), replacementBackend: "none", }, }); } } const now = new Date(); const [updated] = await scopedDb .update(schema.enrollments) .set({ status: "revoked", revokedAt: now, generation: sql`${schema.enrollments.generation} + 1`, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, enrollment.id), eq(schema.enrollments.status, "active"), ), ) .returning(); if (!updated) { throw new Error("machine enrollment changed while removal lock was held"); } const result: MachineRemovalResult = { ...baseResult, outcome: "removed", removed: true, revokedAt: now.toISOString(), code: null, message: "Machine access was revoked. History was retained for audit.", action: "A fresh human-approved device-flow enrollment is required to reconnect.", }; await scopedDb.insert(schema.machineRemovalOperations).values({ accountId: input.accountId, workspaceId: input.workspaceId, enrollmentId: enrollment.id, operationKey, requestFingerprint, outcome: result.outcome, result, }); await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId ?? null, action: "connected_machine.removed", targetType: "enrollment", targetId: enrollment.id, metadata: { machineName: result.machineName, lastSeenAt: result.lastSeenAt, credentialGeneration: Number(updated.credentialGeneration), }, }); return result; }, ); } // Legacy revoke wrapper retained for uninstall callers and older API clients. // The new admin/API surface calls removeEnrollment directly so it can expose // blockers, idempotent receipts, and stale-revision diagnostics. export async function revokeEnrollment( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; }, ): Promise<{ revoked: boolean }> { const result = await removeEnrollment(db, { ...input, operationKey: `legacy-revoke:${randomUUID()}`, }); return { revoked: result?.removed === true }; } // Self-revoke is credential-family scoped, unlike the administrator revoke above. // The row is locked before checking generation/status so a concurrent re-enroll // cannot slip between validation and mutation. A revoked row is an idempotent // success only for the SAME generation (lost-response retry); an old bearer after // re-enrollment returns matched:false and cannot revoke the new credential family. export async function revokeEnrollmentByGeneration( db: Database, input: { workspaceId: string; enrollmentId: string; credentialGeneration: number; }, ): Promise<{ matched: boolean; revoked: boolean }> { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ status: schema.enrollments.status, credentialGeneration: schema.enrollments.credentialGeneration, }) .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), ), ) .for("update") .limit(1); if (!row || Number(row.credentialGeneration) !== input.credentialGeneration) { return { matched: false, revoked: false }; } if (row.status === "revoked") { return { matched: true, revoked: false }; } if (row.status !== "active") { return { matched: false, revoked: false }; } const updated = await scopedDb .update(schema.enrollments) .set({ status: "revoked", revokedAt: new Date(), generation: sql`${schema.enrollments.generation} + 1`, updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.credentialGeneration, input.credentialGeneration), ), ) .returning({ id: schema.enrollments.id }); if (updated.length !== 1) { throw new Error("Enrollment generation changed while row lock was held"); } return { matched: true, revoked: true }; }); } // Heartbeat liveness cursor: the agent reports it is alive. last_seen_at is read // by the online/reconnecting/offline derivation in the Machines surface. // // A fresh heartbeat is also the definitive "the machine is alive NOW" signal, so // it CLEARS any pending clean going-offline marker in the SAME update: a machine // that said goodbye but is heartbeating again is not offline. went_offline_at / // went_offline_reason go back to NULL alongside the last_seen bump (unconditional — // this update always fires on a heartbeat, so a set marker never outlives the next // heartbeat). export async function touchEnrollmentLastSeen( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .update(schema.enrollments) .set({ lastSeenAt: new Date(), wentOfflineAt: null, wentOfflineReason: null, updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), ), ); }, ); } // Record a CLEAN going-offline: the machine announced a typed GoingOffline // (user-stop / self-update / host-shutdown). Stamps went_offline_at = now() + // the typed reason so the liveness derivation reads the machine OFFLINE // immediately (an un-cleared marker beats last_seen aging), for the dashboard AND // for anything deciding whether to route work at it. Deliberately does NOT touch // last_seen — a shutdown must not look "more recently alive". An unknown enrollment // is a no-op (no row → no write). export async function setEnrollmentWentOffline( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; reason: string; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .update(schema.enrollments) .set({ wentOfflineAt: new Date(), wentOfflineReason: input.reason, updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), ), ); }, ); } /** An authenticated but expired bearer is diagnostic evidence, not live runner * authority. Never let an old credential or racing denial mark a healthy/newly * enrolled machine offline. Repeated denials do not repeatedly write the row. */ export async function recordEnrollmentExpiredCredentials( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; credentialGeneration: number; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .update(schema.enrollments) .set({ wentOfflineAt: new Date(), wentOfflineReason: "credentials_expired", updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.credentialGeneration, input.credentialGeneration), sql`(${schema.enrollments.connectionLeaseExpiresAt} IS NULL OR ${schema.enrollments.connectionLeaseExpiresAt} <= now())`, sql`(${schema.enrollments.lastSeenAt} IS NULL OR ${schema.enrollments.lastSeenAt} < now() - interval '20 seconds')`, sql`${schema.enrollments.wentOfflineReason} IS DISTINCT FROM 'credentials_expired'`, ), ); }, ); } // Clear a pending clean going-offline marker: a reconnect Hello re-announced the // machine, so the goodbye no longer holds. CHANGE-GUARDED (`went_offline_at IS NOT // NULL`) so a steady-state Hello — the overwhelmingly common case — issues NO // write and never churns; `cleared` reports whether a marker was actually present, // which the ingestion path uses to decide whether a link.restored is warranted (a // restored only pairs a prior lost). export async function clearEnrollmentWentOffline( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; /** When present, only the exact still-live runner may clear the marker. */ connectionInstanceId?: string; }, ): Promise<{ cleared: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.enrollments) .set({ wentOfflineAt: null, wentOfflineReason: null, updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), isNotNull(schema.enrollments.wentOfflineAt), ...(input.connectionInstanceId ? [ eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), ] : []), ), ) .returning({ id: schema.enrollments.id }); return { cleared: rows.length > 0 }; }, ); } // Live display cursor: the agent's connect Hello reports whether a display is // present RIGHT NOW (a desktop framebuffer probes). Unlike `has_display` set once // machine's life — a Mac that later grants Screen Recording, or a Linux box whose // Xvfb starts after enrollment, flips false→true on its next Hello (and a display // that goes away flips true→false). // // `desktopUnavailableReason` rides alongside: a machine can have a display it // cannot CAPTURE (macOS Screen Recording / TCC not granted). In that case // has_display is false BUT the reason is a human, actionable string, so the // Machines dashboard can show "display: capture not granted" instead of a bare // "headless". null means capture is permitted OR the machine is genuinely headless. // // CHANGE-GUARDED at the SQL layer: the write fires only when EITHER field differs // from what the row already holds (`hasDisplay` via `ne`, the nullable reason via // `IS DISTINCT FROM`), so a steady-state Hello updates zero rows and never churns. // Returns whether a row was actually changed. Best-effort — the caller swallows // failures so a display refresh never breaks the agent's connect. export async function setEnrollmentDisplayState( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; hasDisplay: boolean; desktopUnavailableReason: string | null; /** Live snapshots update the desktop bit without rewriting release/update metadata. */ runtimeDesktop?: boolean; /** Live macOS permission snapshot, merged into the runtime capabilities. */ macPermissions?: EnrollmentMacPermissions; /** When present, fence the update to the exact still-live runner. */ connectionInstanceId?: string; }, ): Promise<{ updated: boolean }> { const runtime: Record = { ...(input.runtimeDesktop !== undefined ? { desktop: input.runtimeDesktop } : {}), ...(input.macPermissions ? enrollmentMacPermissionCapabilities(input.macPermissions) : {}), }; const runtimeJson = JSON.stringify(runtime); const mergeRuntime = Object.keys(runtime).length > 0; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.enrollments) .set({ hasDisplay: input.hasDisplay, desktopUnavailableReason: input.desktopUnavailableReason, ...(mergeRuntime ? { agentCapabilities: sql`coalesce(${schema.enrollments.agentCapabilities}, '{}'::jsonb) || ${runtimeJson}::jsonb`, } : {}), updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), ...(input.connectionInstanceId ? [ eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), ] : []), // Only write on a CHANGE to EITHER field — an unchanged display state must // not churn a write on every reconnect Hello. `IS DISTINCT FROM` is the // null-safe inequality (a plain `ne` skips NULL rows). or( ne(schema.enrollments.hasDisplay, input.hasDisplay), sql`${schema.enrollments.desktopUnavailableReason} IS DISTINCT FROM ${input.desktopUnavailableReason}`, ...(mergeRuntime ? [ sql`not (coalesce(${schema.enrollments.agentCapabilities}, '{}'::jsonb) @> ${runtimeJson}::jsonb)`, ] : []), ), ), ) .returning({ id: schema.enrollments.id }); return { updated: rows.length > 0 }; }, ); } /** The three macOS desktop permissions a Mac agent reports. */ export type EnrollmentMacPermissions = { screenRecording: boolean; accessibility: boolean; inputMonitoring: boolean; }; const MAC_PERMISSION_CAPABILITY_KEYS = { screenRecording: "macScreenRecording", accessibility: "macAccessibility", inputMonitoring: "macInputMonitoring", } as const; /** Runtime-capability keys under which a Mac's permission snapshot is stored. */ export function enrollmentMacPermissionCapabilities( permissions: EnrollmentMacPermissions, ): Record { return { [MAC_PERMISSION_CAPABILITY_KEYS.screenRecording]: permissions.screenRecording, [MAC_PERMISSION_CAPABILITY_KEYS.accessibility]: permissions.accessibility, [MAC_PERMISSION_CAPABILITY_KEYS.inputMonitoring]: permissions.inputMonitoring, }; } /** The stored Mac permission snapshot, or null when the agent never reported one. */ export function enrollmentMacPermissions( capabilities: Record | null | undefined, ): EnrollmentMacPermissions | null { const read = (key: string) => capabilities?.[key]; const screenRecording = read(MAC_PERMISSION_CAPABILITY_KEYS.screenRecording); const accessibility = read(MAC_PERMISSION_CAPABILITY_KEYS.accessibility); const inputMonitoring = read(MAC_PERMISSION_CAPABILITY_KEYS.inputMonitoring); if ( typeof screenRecording !== "boolean" || typeof accessibility !== "boolean" || typeof inputMonitoring !== "boolean" ) { return null; } return { screenRecording, accessibility, inputMonitoring }; } /** * Allow screen control on one active enrollment, in place: same id, scope, * owner and credential generation. The machine's next credential renewal (the * control plane requests one immediately when it is online) carries the * consent. Only the screen-control bit changes, and the change is audited with * the actor (a person or an agent attempt acting for one). `active` is false * when the enrollment is gone or no longer active. */ export async function allowEnrollmentScreenControl( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; subjectId: string | null; sessionId?: string | null; attemptId?: string | null; }, ): Promise<{ updated: boolean; active: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const target = and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), ); const rows = await scopedDb .update(schema.enrollments) .set({ allowScreenControl: true, updatedAt: new Date() }) .where(and(target, eq(schema.enrollments.allowScreenControl, false))) .returning({ id: schema.enrollments.id }); if (rows.length === 0) { const [current] = await scopedDb .select({ id: schema.enrollments.id }) .from(schema.enrollments) .where(target) .limit(1); return { updated: false, active: current !== undefined }; } await scopedDb.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "connected_machine.screen_control.allowed", targetType: "enrollment", targetId: input.enrollmentId, metadata: { ...(input.sessionId ? { sessionId: input.sessionId } : {}), ...(input.attemptId ? { attemptId: input.attemptId } : {}), }, }); return { updated: true, active: true }; }, ); } // Live op-stream cursor: the agent's connect Hello advertises whether it supports // the streaming exec transport. This is deliberately persisted separately from the // server rollout flag so routing can require BOTH server enablement and the live // runner capability; agents predating the op-stream engine remain false, so exec // fails closed until they advertise the required transport. // // CHANGE-GUARDED at the SQL layer: the write fires only when `op_stream` differs // from what the row already holds, so a steady-state Hello updates zero rows and // never churns. Returns whether a row was actually changed. Best-effort — the // caller swallows failures so capability refresh never breaks the agent's connect. export async function setEnrollmentOpStreamState( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; opStream: boolean; /** When present, fence the update to the exact still-live runner. */ connectionInstanceId?: string; }, ): Promise<{ updated: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.enrollments) .set({ opStream: input.opStream, updatedAt: new Date(), }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), ...(input.connectionInstanceId ? [ eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), ] : []), ne(schema.enrollments.opStream, input.opStream), ), ) .returning({ id: schema.enrollments.id }); return { updated: rows.length > 0 }; }, ); } /** Refresh the exact running agent build/capabilities from an authoritative * process Hello. An update becomes succeeded only when the successor reports * BOTH the requested version and the artifact digest its managed-update receipt * recorded for that version. Merely reaching `restarting` never counts as * success. * * The updater is process-global: one agent process serves every enrollment it * is linked to, so only one of them owns the operation that installs a build, * and the others are refused or postponed while it runs. The receipt therefore * proves the target for every enrollment of that process, whichever operation * installed it, and settles a pending, postponed or failed update whose target * is now running. */ export async function setEnrollmentAgentRuntime( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; agentVersion: string | null; binarySha256: string | null; updateChannel: "stable" | "beta" | null; capabilities: Record; /** Omitted when an older or malformed Hello did not report a usable root. */ workspaceRoot?: string; completedUpdate: { operationId: string; targetVersion: string; binarySha256: string; } | null; }, ): Promise<{ updated: boolean; updateCompleted: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); const completedTargetVersion = input.completedUpdate?.targetVersion ?? null; const completedBinarySha256 = input.completedUpdate?.binarySha256 ?? null; const activeUpdate = sql`${schema.enrollments.agentUpdateStatus} in ( 'requested', 'accepted', 'waiting_for_idle', 'downloading', 'verifying', 'applying', 'restarting' )`; // No receipt (manual install or ordinary restart) is false, not SQL NULL: // the negation below must still settle the replaced process's operation. const successorProvesCompletion = sql`coalesce(( (${activeUpdate} or ${schema.enrollments.agentUpdateStatus} = 'failed') and ${schema.enrollments.agentUpdateTargetVersion} = ${completedTargetVersion} and ${schema.enrollments.agentUpdateTargetVersion} = ${input.agentVersion} and ${completedBinarySha256} = ${input.binarySha256} ), false)`; const acceptingProcessWasReplaced = sql`( ${activeUpdate} and ${schema.enrollments.agentUpdateConnectionInstanceId} is distinct from ${input.connectionInstanceId} and not ${successorProvesCompletion} )`; const rows = await scopedDb .update(schema.enrollments) .set({ agentVersion: input.agentVersion, agentBinarySha256: input.binarySha256, agentUpdateChannel: input.updateChannel, agentCapabilities: input.capabilities, ...(input.workspaceRoot !== undefined ? { workspaceRoot: input.workspaceRoot } : {}), // Success is derived atomically from the successor's durable updater // receipt + exact running build. If another process replaced the // accepting one without that proof, fail retryably instead of leaving // the dashboard stuck forever. agentUpdateStatus: sql`case when ${successorProvesCompletion} then 'succeeded' when ${acceptingProcessWasReplaced} then 'failed' else ${schema.enrollments.agentUpdateStatus} end`, agentUpdateExpectedBinarySha256: sql`case when ${successorProvesCompletion} then ${completedBinarySha256} else ${schema.enrollments.agentUpdateExpectedBinarySha256} end`, agentUpdateErrorCode: sql`case when ${successorProvesCompletion} then null when ${acceptingProcessWasReplaced} then 'accepting_process_replaced' else ${schema.enrollments.agentUpdateErrorCode} end`, agentUpdateBlockers: sql`case when ${successorProvesCompletion} or ${acceptingProcessWasReplaced} then '[]'::jsonb else ${schema.enrollments.agentUpdateBlockers} end`, agentUpdateRetryable: sql`case when ${successorProvesCompletion} then false when ${acceptingProcessWasReplaced} then true else ${schema.enrollments.agentUpdateRetryable} end`, agentUpdateRolledBack: sql`case when ${successorProvesCompletion} then false else ${schema.enrollments.agentUpdateRolledBack} end`, agentUpdateCompletedAt: sql`case when ${successorProvesCompletion} or ${acceptingProcessWasReplaced} then ${now.toISOString()}::timestamptz else ${schema.enrollments.agentUpdateCompletedAt} end`, agentUpdateUpdatedAt: sql`case when ${successorProvesCompletion} or ${acceptingProcessWasReplaced} then ${now.toISOString()}::timestamptz else ${schema.enrollments.agentUpdateUpdatedAt} end`, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), or( sql`${schema.enrollments.agentVersion} is distinct from ${input.agentVersion}`, sql`${schema.enrollments.agentBinarySha256} is distinct from ${input.binarySha256}`, sql`${schema.enrollments.agentUpdateChannel} is distinct from ${input.updateChannel}`, sql`${schema.enrollments.agentCapabilities} is distinct from ${JSON.stringify(input.capabilities)}::jsonb`, ...(input.workspaceRoot !== undefined ? [sql`${schema.enrollments.workspaceRoot} is distinct from ${input.workspaceRoot}`] : []), successorProvesCompletion, acceptingProcessWasReplaced, ), ), ) .returning({ id: schema.enrollments.id, updateStatus: schema.enrollments.agentUpdateStatus, completedAt: schema.enrollments.agentUpdateCompletedAt, }); return { updated: rows.length > 0, updateCompleted: rows[0]?.updateStatus === "succeeded" && rows[0].completedAt !== null, }; }, ); } /** Atomically reserve the one process-global update slot on an exact live * runner generation. An in-flight operation is never overwritten. */ export async function beginEnrollmentAgentUpdate( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; connectionGeneration: number; operationId: string; targetVersion: string; /** Announce that this update closes the machine's managed browsers at * this time, or clear an announcement (null). Otherwise an announced time * is kept while the run continues. */ browsersCloseAt?: Date | null; /** For a postponement for browsers in use: `start` keeps the run's wait * or begins it now, `restart` begins it again now. Otherwise the wait is * kept while the run continues. */ browsersWait?: "start" | "restart"; /** The target is newer than the one the latest attempt was for, so the * run's failed attempts no longer count. */ newerTarget?: boolean; /** Reserve only while the machine's latest operation is still this one * (null: none), so a decision made from an older read of the machine * never replaces a newer record. */ expectedOperationId?: string | null; /** Also replace an unfinished operation whose last progress is at or * before this time: its runner was asked and has not been heard from * since, so it is treated as lost. A fresh progress event moves the * operation past this time and keeps it. */ replaceUnfinishedBefore?: Date; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); // A run of unsuccessful attempts continues while the latest one failed // retryably or was postponed (`update_busy_*`); a success, a // non-retryable failure or a first attempt starts a new one. const previousFailureWasBusy = sql`starts_with(coalesce(${schema.enrollments.agentUpdateErrorCode}, ''), 'update_busy')`; const continuesRun = sql`(${schema.enrollments.agentUpdateStatus} = 'failed' and (${schema.enrollments.agentUpdateRetryable} or ${previousFailureWasBusy}))`; const nowSql = sql`${now.toISOString()}::timestamptz`; const rows = await scopedDb .update(schema.enrollments) .set({ agentUpdateOperationId: input.operationId, agentUpdateStatus: "requested", agentUpdateTargetVersion: input.targetVersion, agentUpdateExpectedBinarySha256: null, agentUpdateErrorCode: null, agentUpdateBlockers: [], agentUpdateRetryable: false, agentUpdateRolledBack: false, agentUpdateConnectionInstanceId: input.connectionInstanceId, agentUpdateConnectionGeneration: input.connectionGeneration, agentUpdateRequestedAt: now, agentUpdateUpdatedAt: now, agentUpdateCompletedAt: null, agentUpdateBrowsersWaitSince: input.browsersWait === "restart" ? now : input.browsersWait === "start" ? sql`case when ${continuesRun} then coalesce(${schema.enrollments.agentUpdateBrowsersWaitSince}, ${nowSql}) else ${nowSql} end` : sql`case when ${continuesRun} then ${schema.enrollments.agentUpdateBrowsersWaitSince} else null end`, agentUpdateFailedAttempts: input.newerTarget === true ? 0 : sql`case when ${continuesRun} and not ${previousFailureWasBusy} then ${schema.enrollments.agentUpdateFailedAttempts} + 1 when ${continuesRun} then ${schema.enrollments.agentUpdateFailedAttempts} else 0 end`, agentUpdateBrowsersCloseAt: input.browsersCloseAt !== undefined ? input.browsersCloseAt : sql`case when ${continuesRun} then ${schema.enrollments.agentUpdateBrowsersCloseAt} else null end`, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), eq(schema.enrollments.connectionGeneration, input.connectionGeneration), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), or( sql`${schema.enrollments.agentUpdateStatus} is null`, eq(schema.enrollments.agentUpdateStatus, "succeeded"), eq(schema.enrollments.agentUpdateStatus, "failed"), input.replaceUnfinishedBefore === undefined ? undefined : sql`${schema.enrollments.agentUpdateUpdatedAt} <= ${input.replaceUnfinishedBefore.toISOString()}::timestamptz`, ), input.expectedOperationId === undefined ? undefined : sql`${schema.enrollments.agentUpdateOperationId} is not distinct from ${input.expectedOperationId}::uuid`, ), ) .returning(); return rows[0] ? mapEnrollment(rows[0]) : null; }, ); } const AGENT_UPDATE_PROGRESS_RANK: Record< Exclude, number > = { accepted: 1, waiting_for_idle: 2, downloading: 3, verifying: 4, applying: 5, restarting: 6, failed: 99, }; /** Fold one progress event/dispatch failure into the reserved update. Exact * operation + process authority coordinates fence stale events; monotonic rank * prevents reordered NATS delivery from regressing the UI. */ export async function advanceEnrollmentAgentUpdate( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; connectionGeneration: number; operationId: string; status: Exclude; expectedBinarySha256?: string | null; errorCode?: string | null; blockers?: Array<{ kind: string; count: number }>; retryable?: boolean; rolledBack?: boolean; }, ): Promise<{ updated: boolean }> { const nextRank = AGENT_UPDATE_PROGRESS_RANK[input.status]; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const now = new Date(); const currentRank = sql`case ${schema.enrollments.agentUpdateStatus} when 'requested' then 0 when 'accepted' then 1 when 'waiting_for_idle' then 2 when 'downloading' then 3 when 'verifying' then 4 when 'applying' then 5 when 'restarting' then 6 else 100 end`; const rows = await scopedDb .update(schema.enrollments) .set({ agentUpdateStatus: input.status, ...(input.expectedBinarySha256 !== undefined && input.expectedBinarySha256 ? { agentUpdateExpectedBinarySha256: input.expectedBinarySha256 } : {}), agentUpdateErrorCode: input.errorCode ?? null, agentUpdateBlockers: input.status === "waiting_for_idle" ? (input.blockers ?? []) : [], agentUpdateRetryable: input.retryable ?? false, agentUpdateRolledBack: input.rolledBack ?? false, agentUpdateUpdatedAt: now, ...(input.status === "failed" ? { agentUpdateCompletedAt: now } : {}), updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.status, "active"), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), eq(schema.enrollments.connectionGeneration, input.connectionGeneration), gt(schema.enrollments.connectionLeaseExpiresAt, sql`clock_timestamp()`), eq(schema.enrollments.agentUpdateOperationId, input.operationId), eq(schema.enrollments.agentUpdateConnectionInstanceId, input.connectionInstanceId), eq(schema.enrollments.agentUpdateConnectionGeneration, input.connectionGeneration), sql`${schema.enrollments.agentUpdateStatus} not in ('succeeded', 'failed')`, input.status === "failed" ? sql`true` : sql`${currentRank} <= ${nextRank}`, ), ) .returning({ id: schema.enrollments.id }); return { updated: rows.length > 0 }; }, ); } // ---- device-flow enrollment requests (M5, migration 0025) ----------------- // // The OAuth 2.0 device-authorization (RFC 8628) PENDING request: one short-TTL, // single-use row per in-flight enrollment. The agent starts a flow (gets a // device_code + user_code), the user approves it (LOUD consent capture + // createEnrollment + createSandbox), and the agent polls the device_code for the // resulting EnrollmentCredentials. export type DeviceEnrollmentStatus = (typeof schema.deviceEnrollmentStatusValues)[number]; export type DeviceEnrollmentRequestRecord = { id: string; deviceCode: string; userCode: string; accountId: string; workspaceId: string; pubkey: string; os: EnrollmentOs; arch: string; machineName: string | null; requestedExposure: EnrollmentExposure; canOfferDisplay: boolean; requestsScreenControl: boolean; status: DeviceEnrollmentStatus; approvedBySubjectId: string | null; approvedBySubjectLabel: string | null; allowScreenControl: boolean; approvedAt: string | null; enrollmentId: string | null; sandboxId: string | null; expiresAt: string; createdAt: string; updatedAt: string; }; function mapDeviceEnrollmentRequest( row: typeof schema.deviceEnrollmentRequests.$inferSelect, ): DeviceEnrollmentRequestRecord { return { id: row.id, deviceCode: row.deviceCode, userCode: row.userCode, accountId: row.accountId, workspaceId: row.workspaceId, pubkey: row.pubkey, os: row.os as EnrollmentOs, arch: row.arch, machineName: row.machineName ?? null, requestedExposure: row.requestedExposure as EnrollmentExposure, canOfferDisplay: row.canOfferDisplay, requestsScreenControl: row.requestsScreenControl, status: row.status as DeviceEnrollmentStatus, approvedBySubjectId: row.approvedBySubjectId ?? null, approvedBySubjectLabel: row.approvedBySubjectLabel ?? null, allowScreenControl: row.allowScreenControl, approvedAt: row.approvedAt ? row.approvedAt.toISOString() : null, enrollmentId: row.enrollmentId ?? null, sandboxId: row.sandboxId ?? null, expiresAt: row.expiresAt.toISOString(), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } // Persist a fresh PENDING device-auth request (the agent's POST /start). The // caller supplies the unguessable device_code + user_code (minted with a CSPRNG) // and the short TTL. RLS-scoped to the workspace the flow binds to. export async function createDeviceEnrollmentRequest( db: Database, input: { accountId: string; workspaceId: string; deviceCode: string; userCode: string; pubkey: string; os?: EnrollmentOs; arch?: string; machineName?: string | null; requestedExposure?: EnrollmentExposure; canOfferDisplay?: boolean; requestsScreenControl?: boolean; expiresAt: Date; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.deviceEnrollmentRequests) .values({ accountId: input.accountId, workspaceId: input.workspaceId, deviceCode: input.deviceCode, userCode: input.userCode, pubkey: input.pubkey, os: input.os ?? "linux", arch: input.arch ?? "x86_64", machineName: input.machineName ?? null, requestedExposure: input.requestedExposure ?? "whole-machine", canOfferDisplay: input.canOfferDisplay ?? false, requestsScreenControl: input.requestsScreenControl ?? false, status: "pending", expiresAt: input.expiresAt, }) .returning(); if (!row) { throw new Error("Failed to create device enrollment request"); } return mapDeviceEnrollmentRequest(row); }, ); } // Look up a request by its opaque device_code (the agent's poll key). The // device_code IS the capability (unguessable + unique) and the agent has NO // workspace context yet, so resolve (account_id, workspace_id) via the SECURITY // DEFINER resolver (mirrors the global reaper's cross-workspace read), then re-read // the FULL row under that workspace's RLS scope. Returns null when unknown. export async function getDeviceEnrollmentRequestByDeviceCode( db: Database, deviceCode: string, ): Promise { const resolved = await db.execute<{ account_id: string; workspace_id: string; }>(sql` select account_id, workspace_id from opengeni_private.resolve_device_enrollment_request(${deviceCode}) `); const ctx = resolved[0]; if (!ctx) { return null; } return await withRlsContext( db, { accountId: ctx.account_id, workspaceId: ctx.workspace_id }, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.deviceEnrollmentRequests) .where(eq(schema.deviceEnrollmentRequests.deviceCode, deviceCode)) .limit(1); return row ? mapDeviceEnrollmentRequest(row) : null; }, ); } // Look up the PENDING request for a user_code within a workspace (the approve // lookup). Workspace-scoped: a user can only approve a request bound to a // workspace they hold a grant in. Returns null when no LIVE pending row matches. export async function getPendingDeviceEnrollmentRequestByUserCode( db: Database, workspaceId: string, userCode: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.deviceEnrollmentRequests) .where( and( eq(schema.deviceEnrollmentRequests.workspaceId, workspaceId), eq(schema.deviceEnrollmentRequests.userCode, userCode), eq(schema.deviceEnrollmentRequests.status, "pending"), ), ) .limit(1); return row ? mapDeviceEnrollmentRequest(row) : null; }); } // Look up the PENDING request for a user_code GLOBALLY (no workspace context) — // the click-Grant approve page lookup (design 11 §B.1). The user_code is globally // unique among LIVE (pending) rows, so — exactly like getDeviceEnrollmentRequestByDeviceCode // resolves a device_code — this resolves (account_id, workspace_id) via the 0026 // SECURITY DEFINER resolver, then re-reads the FULL pending row under that // workspace's RLS scope. The ROUTE then re-checks the caller holds a grant in the // resolved workspace before returning anything. Returns null when no live pending // row matches (an unknown / terminal / expired code). export async function getPendingDeviceEnrollmentRequestByUserCodeGlobal( db: Database, userCode: string, ): Promise { const resolved = await db.execute<{ account_id: string; workspace_id: string; }>(sql` select account_id, workspace_id from opengeni_private.resolve_pending_device_enrollment_by_user_code(${userCode}) `); const ctx = resolved[0]; if (!ctx) { return null; } return await withRlsContext( db, { accountId: ctx.account_id, workspaceId: ctx.workspace_id }, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.deviceEnrollmentRequests) .where( and( eq(schema.deviceEnrollmentRequests.userCode, userCode), eq(schema.deviceEnrollmentRequests.status, "pending"), ), ) .limit(1); return row ? mapDeviceEnrollmentRequest(row) : null; }, ); } // The SHARED finalize core (design 11 §A2.3 "reuse, don't fork"): "upsert the // enrollment (idempotent on (workspace_id, pubkey)) + ensure a kind='selfhosted' // sandbox row" — the exact end state BOTH the device approve and the headless // token exchange must produce. Takes an ALREADY-RLS-SCOPED `scopedDb` so the // caller controls the transaction boundary: // * approveDeviceEnrollmentRequest calls it INSIDE its FOR-UPDATE txn (so the // re-read fence + the request stamp stay in ONE txn — semantics unchanged), and // * finalizeEnrollmentByToken calls it inside its OWN txn (no pending row exists // for a stateless token). // A fresh finalize for the same (workspace, pubkey) re-activates the existing // enrollment, atomically increments its credential generation, and REUSES its // selfhosted sandbox — never a duplicate. Device-approval retries are intercepted // before this helper so replaying one already-approved request does not rotate. // // A live personal machine belongs to the workspace it was connected from, and // finalize_scoped_enrollment reuses the owner's live enrollment for the same // public key wherever that is. Credentials and connection lookups are per // workspace, so a personal finalize from any other workspace while it is live // is refused with PersonalMachineConnectedElsewhereError (the machine serves // the owner's other workspaces through grants instead). The caller's // transaction rolls back, so nothing is written and a single-use token is not // claimed. Once removed, the machine can be connected again from any of the // owner's workspaces: a new enrollment is made there (0996). export class PersonalMachineConnectedElsewhereError extends Error { constructor() { super("this machine was first connected as a personal machine from another workspace"); this.name = "PersonalMachineConnectedElsewhereError"; } } async function finalizeEnrollmentInScope( scopedDb: Database, input: { accountId: string; workspaceId: string; scope?: EnrollmentRecord["scope"]; allowOrganization?: boolean; pubkey: string; hasDisplay: boolean; allowScreenControl: boolean; os: EnrollmentOs; arch: string; sandboxName: string; now: Date; }, ): Promise<{ enrollment: EnrollmentRecord; sandbox: SandboxRecord }> { if (input.scope !== undefined) { const [created] = await rawRows<{ enrollmentId: string; sandboxId: string; }>( scopedDb, sql`select enrollment_id as "enrollmentId", sandbox_id as "sandboxId" from finalize_scoped_enrollment( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.scope}, ${input.pubkey}, ${input.hasDisplay}, ${input.allowScreenControl}, ${input.os}, ${input.arch}, ${input.sandboxName}, ${input.allowOrganization === true} )`, ); if (!created) throw new Error("Failed to finalize scoped enrollment"); const [enrollmentRow] = await scopedDb .select() .from(schema.enrollments) .where(eq(schema.enrollments.id, created.enrollmentId)) .limit(1); const [sandboxRow] = await scopedDb .select() .from(schema.sandboxes) .where(eq(schema.sandboxes.id, created.sandboxId)) .limit(1); if ( input.scope === "user" && (!enrollmentRow || enrollmentRow.workspaceId !== input.workspaceId) ) { // The owner's existing enrollment for this key lives in another workspace: // this workspace cannot read it, and its credentials would not match. throw new PersonalMachineConnectedElsewhereError(); } if (!enrollmentRow || !sandboxRow) throw new Error("Scoped enrollment finalize lost rows"); return { enrollment: mapEnrollment(enrollmentRow), sandbox: mapSandbox(sandboxRow), }; } // createEnrollment (idempotent upsert) — whole-machine is mandatory; display + // screen-control come from the agent's offer + the consenting decision. We inline // the insert here (rather than calling createEnrollment, which opens its OWN // scope) so it shares the caller's transaction. const [enrollmentRow] = await scopedDb .insert(schema.enrollments) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pubkey: input.pubkey, exposure: "whole-machine", hasDisplay: input.hasDisplay, allowScreenControl: input.allowScreenControl, os: input.os, arch: input.arch, status: "active", }) .onConflictDoUpdate({ target: [schema.enrollments.workspaceId, schema.enrollments.pubkey], targetWhere: sql`authority_scope = 'workspace'`, set: { exposure: "whole-machine", hasDisplay: input.hasDisplay, allowScreenControl: input.allowScreenControl, os: input.os, arch: input.arch, status: "active", revokedAt: null, credentialGeneration: sql`${schema.enrollments.credentialGeneration} + 1`, updatedAt: input.now, }, }) .returning(); if (!enrollmentRow) { throw new Error("Failed to create enrollment during finalize"); } const enrollment = mapEnrollment(enrollmentRow); // Ensure a selfhosted sandbox for this enrollment. A re-finalize of the SAME // machine reuses the existing sandbox rather than creating a duplicate. const [existingSandbox] = await scopedDb .select() .from(schema.sandboxes) .where( and( eq(schema.sandboxes.workspaceId, input.workspaceId), eq(schema.sandboxes.enrollmentId, enrollment.id), ), ) .limit(1); let sandbox: SandboxRecord; if (existingSandbox) { sandbox = mapSandbox(existingSandbox); } else { const [sandboxRow] = await scopedDb .insert(schema.sandboxes) .values({ accountId: input.accountId, workspaceId: input.workspaceId, kind: "selfhosted", name: input.sandboxName, enrollmentId: enrollment.id, }) .returning(); if (!sandboxRow) { throw new Error("Failed to create sandbox during finalize"); } sandbox = mapSandbox(sandboxRow); } return { enrollment, sandbox }; } // FINALIZE a headless enroll-token exchange (design 11 §A2.3). Produces the SAME // end state as approveDeviceEnrollmentRequest — an enrollments row + a selfhosted // sandbox row — but WITHOUT a pending device-flow request (a stateless `oget_` // token carries the grant). Idempotent via the shared finalize core's upsert. // // A token with an id (`jti`) is single-use: its redemption is recorded in the // same transaction as the enrollment, so it connects exactly one machine. The // same machine (same public key) may repeat the exchange while its enrollment is // still active; any other machine, or a machine removed since, gets // EnrollTokenAlreadyRedeemedError and nothing is written. Legacy tokens without // an id keep their old multi-use behavior until they expire. // A personal token for a machine that is already its owner's personal machine // from another workspace gets PersonalMachineConnectedElsewhereError, also // without writing anything or claiming the token. export class EnrollTokenAlreadyRedeemedError extends Error { constructor() { super("enroll token was already used to connect another machine"); this.name = "EnrollTokenAlreadyRedeemedError"; } } // A personal token's owner can no longer own a machine here: they left the // organization, lost access to the minting workspace, or were suspended after // the command was created. Nothing is written. export class EnrollTokenOwnerUnavailableError extends Error { constructor(options?: { cause?: unknown }) { super( "the person who created this connect command can no longer connect machines here", options, ); this.name = "EnrollTokenOwnerUnavailableError"; } } function databaseErrorCode(error: unknown): string { let current: unknown = error; for (let depth = 0; depth < 8 && current && typeof current === "object"; depth += 1) { const code = (current as { code?: unknown }).code; if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return code; current = (current as { cause?: unknown }).cause; } return ""; } export async function finalizeEnrollmentByToken( db: Database, input: { accountId: string; workspaceId: string; /** * The signed owner of a personal (`enroll_user`) token. When present the * machine is created user-owned through the same scoped finalizer and * organization-membership fence as a personal device-flow approval, which * rechecks the owner's live membership and workspace access now. */ ownerSubjectId?: string | null; pubkey: string; hasDisplay: boolean; allowScreenControl: boolean; os: EnrollmentOs; arch: string; sandboxName: string; /** The token's `jti`; when present the token is single-use. */ tokenId?: string | null; /** The token's expiry; required with tokenId (bounds redemption retention). */ tokenExpiresAt?: Date | null; now?: Date; }, ): Promise<{ enrollment: EnrollmentRecord; sandbox: SandboxRecord }> { const now = input.now ?? new Date(); const tokenId = input.tokenId ?? null; if (tokenId !== null && !input.tokenExpiresAt) { throw new Error("a single-use enroll token requires its expiry"); } const ownerSubjectId = input.ownerSubjectId ?? null; if (ownerSubjectId !== null && !ownerSubjectId.trim()) { throw new Error("a personal enroll token requires its owner"); } const finalizeInScope = (database: Database) => withRlsContext( database, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { if (ownerSubjectId !== null) { // The scoped finalizer reads the owner from this transaction-local // subject, exactly as a personal device-flow approval does. await setSubjectRlsContext(scopedDb, ownerSubjectId); } if (tokenId !== null) { // Expired redemptions can never match a live token; drop them so the // ledger stays bounded per workspace. await scopedDb.execute(sql` delete from enrollment_token_redemptions where workspace_id = ${input.workspaceId}::uuid and expires_at < ${new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString()}::timestamptz`); // Claim the token first. A concurrent claim by another machine blocks on // the primary key, then sees this row and is refused. const claimed = await rawRows<{ tokenId: string }>( scopedDb, sql`insert into enrollment_token_redemptions (token_id, account_id, workspace_id, pubkey, expires_at, redeemed_at) values (${tokenId}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.pubkey}, ${input.tokenExpiresAt!.toISOString()}::timestamptz, ${now.toISOString()}::timestamptz) on conflict (token_id) do nothing returning token_id as "tokenId"`, ); if (claimed.length === 0) { // A repeat by the same machine is a retry only while the machine it // connected is still enrolled; a removed machine needs a new token. const [existing] = await rawRows<{ pubkey: string; enrollmentActive: boolean }>( scopedDb, sql`select r.pubkey, coalesce(e.status = 'active', false) as "enrollmentActive" from enrollment_token_redemptions r left join enrollments e on e.id = r.enrollment_id where r.token_id = ${tokenId} and r.workspace_id = ${input.workspaceId}::uuid`, ); if (!existing || existing.pubkey !== input.pubkey || !existing.enrollmentActive) { throw new EnrollTokenAlreadyRedeemedError(); } } } const finalized = await finalizeEnrollmentInScope(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, ...(ownerSubjectId !== null ? { scope: "user" as const } : {}), pubkey: input.pubkey, hasDisplay: input.hasDisplay, allowScreenControl: input.allowScreenControl, os: input.os, arch: input.arch, sandboxName: input.sandboxName, now, }); if (tokenId !== null) { await scopedDb.execute(sql` update enrollment_token_redemptions set enrollment_id = ${finalized.enrollment.id}::uuid where token_id = ${tokenId} and workspace_id = ${input.workspaceId}::uuid`); } return finalized; }, ); if (ownerSubjectId === null) return await finalizeInScope(db); // Organization membership precedes the tenancy fence, then the redemption and // enrollment rows (the same order as approveDeviceEnrollmentRequest). Fail // closed on contention rather than wait on an unknown reverse-order holder. try { return await db.transaction(async (tx) => { const database = tx as unknown as Database; const [fence] = await rawRows<{ acquired: boolean }>( database, sql` select pg_try_advisory_xact_lock(hashtextextended( ${`organization-membership:${input.accountId}`}, 0 )) as acquired `, ); if (!fence?.acquired) { throw Object.assign(new Error("Enrollment membership is changing; retry the transaction"), { code: "55P03", }); } return await finalizeInScope(database); }); } catch (error) { // P0002: no active organization membership for the owner (STRICT lookup); // 42501: the owner no longer has access to the minting workspace. const code = databaseErrorCode(error); if (code === "P0002" || code === "42501") { throw new EnrollTokenOwnerUnavailableError({ cause: error }); } throw error; } } // CREATE a compute sandbox's enrollment. Opengeni makes it itself, before the // control service create, under the id the sandbox's init names as its agent id. It is // active at once, kind 'sandbox', bound to the sandbox group, with no public // key and no bearer: the agent inside holds no credential and is reached only // through its host's link to the agent gateway. It gets no sandboxes row and // is never a machine; its use is authorized by its lease. Repeating the create // for the same id and group is a no-op. export class SandboxEnrollmentConflictError extends Error { constructor() { super("The enrollment id is taken by another enrollment"); this.name = "SandboxEnrollmentConflictError"; } } export async function createSandboxEnrollment( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sandboxGroupId: string; hasDisplay: boolean; workspaceRoot: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .insert(schema.enrollments) .values({ id: input.enrollmentId, accountId: input.accountId, workspaceId: input.workspaceId, kind: "sandbox", sandboxGroupId: input.sandboxGroupId, pubkey: null, exposure: "whole-machine", hasDisplay: input.hasDisplay, // Opengeni owns the sandbox; screen control needs no human consent. allowScreenControl: true, workspaceRoot: input.workspaceRoot, status: "active", }) .onConflictDoNothing({ target: schema.enrollments.id }); const [row] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), ), ) .limit(1); if ( !row || row.kind !== "sandbox" || row.sandboxGroupId !== input.sandboxGroupId || row.status !== "active" ) { throw new SandboxEnrollmentConflictError(); } return mapEnrollment(row); }, ); } /** Why the agent gateway refuses or ends a sandbox's link session. */ export type SandboxAgentLinkRefusal = "unknown_agent" | "revoked" | "stale_epoch" | "duplicate"; export type SandboxAgentLinkEnd = "revoked" | "superseded" | "lost"; type SandboxAgentLinkInput = { workspaceId: string; agentId: string; /** The owner epoch from the sandbox's ticket. */ epoch: number; connectionInstanceId: string; }; function assertSandboxAgentLinkInput(input: SandboxAgentLinkInput, leaseMs?: number): void { if (!input.connectionInstanceId || input.connectionInstanceId.length > 128) { throw new Error("connection instance id must be 1-128 characters"); } if (!Number.isSafeInteger(input.epoch) || input.epoch < 0) { throw new Error("link epoch must be a non-negative integer"); } if (leaseMs !== undefined && (!Number.isSafeInteger(leaseMs) || leaseMs < 1_000)) { throw new Error("connection lease must be at least one second"); } } async function lockSandboxEnrollment(scopedDb: Database, workspaceId: string, agentId: string) { const [row] = await scopedDb .select() .from(schema.enrollments) .where(and(eq(schema.enrollments.workspaceId, workspaceId), eq(schema.enrollments.id, agentId))) .for("update") .limit(1); return row; } /** * OPEN a sandbox's link session at the agent gateway: fence it by the control service's * owner epoch, then claim the agent's connection instance. Under the row lock: * an epoch below the highest recorded is refused (`stale_epoch`); a higher one * is recorded and takes the claim from any other instance, since the control service * has fenced the sandbox's previous owner; an equal one claims exactly as the * NATS callout does for a Connected Machine (`duplicate` while another * instance's lease is live). The claim's lease is the database clock's. */ export async function openSandboxAgentLink( db: Database, input: SandboxAgentLinkInput & { leaseMs: number }, ): Promise< | { opened: true; connectionGeneration: number; superseded: boolean } | { opened: false; code: SandboxAgentLinkRefusal } > { assertSandboxAgentLinkInput(input, input.leaseMs); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const row = await lockSandboxEnrollment(scopedDb, input.workspaceId, input.agentId); if (!row || row.kind !== "sandbox") return { opened: false, code: "unknown_agent" }; if (row.status !== "active") return { opened: false, code: "revoked" }; const recordedEpoch = row.linkEpoch === null ? null : Number(row.linkEpoch); if (recordedEpoch !== null && input.epoch < recordedEpoch) { return { opened: false, code: "stale_epoch" }; } const now = await enrollmentConnectionClock(scopedDb); const sameInstance = row.connectionInstanceId === input.connectionInstanceId; const newerEpoch = recordedEpoch === null || input.epoch > recordedEpoch; const claimAvailable = newerEpoch || sameInstance || row.connectionInstanceId === null || row.connectionLeaseExpiresAt === null || row.connectionLeaseExpiresAt.getTime() <= now.getTime(); if (!claimAvailable) { await scopedDb .update(schema.enrollments) .set({ connectionDuplicateDeniedCount: sql`${schema.enrollments.connectionDuplicateDeniedCount} + 1`, connectionDuplicateDeniedAt: now, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.agentId), ), ); return { opened: false, code: "duplicate" }; } const connectionGeneration = Number(row.connectionGeneration) + (sameInstance ? 0 : 1); await scopedDb .update(schema.enrollments) .set({ linkEpoch: input.epoch, connectionInstanceId: input.connectionInstanceId, connectionGeneration, connectionLeaseExpiresAt: new Date(now.getTime() + input.leaseMs), updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.agentId), ), ); return { opened: true, connectionGeneration, superseded: newerEpoch && recordedEpoch !== null, }; }); } /** * RENEW an open link session's claim. The gateway calls this every few seconds * while the session is open, whether the sandbox runs or sleeps, so a sleeping * sandbox stays reachable. It ends the session when the enrollment was revoked, * a later epoch opened elsewhere (`superseded`), or another instance holds the * claim (`lost`). */ export async function renewSandboxAgentLink( db: Database, input: SandboxAgentLinkInput & { leaseMs: number }, ): Promise<{ renewed: true } | { renewed: false; code: SandboxAgentLinkEnd }> { assertSandboxAgentLinkInput(input, input.leaseMs); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { // Lock first, then sample time: clock_timestamp() in the locking SELECT's // projection would run before a contended row lock is acquired. Materialize // the locked row before the clock/decision, preserving the old lock order // and refusal precedence without two extra database round trips. const [result] = await rawRows<{ renewed: boolean; code: SandboxAgentLinkEnd }>( scopedDb, sql` with locked as materialized ( select id, kind, status, link_epoch, connection_instance_id, connection_lease_expires_at from enrollments where workspace_id = ${input.workspaceId} and id = ${input.agentId} for update ), checked as materialized ( select locked.*, case when kind <> 'sandbox' or status <> 'active' then 'revoked' when link_epoch > ${input.epoch} then 'superseded' when connection_instance_id is distinct from ${input.connectionInstanceId} then 'lost' else null end as refusal, date_trunc('milliseconds', clock_timestamp()) as renewed_at from locked ), updated as ( update enrollments e set connection_lease_expires_at = greatest( case when isfinite(checked.connection_lease_expires_at) -- Match Date's upper bound after its millisecond truncation. and date_trunc('milliseconds', checked.connection_lease_expires_at) <= '275760-09-13 00:00:00+00'::timestamptz then date_trunc('milliseconds', checked.connection_lease_expires_at) else null end, checked.renewed_at + ${input.leaseMs} * interval '1 millisecond' ), updated_at = checked.renewed_at from checked where e.id = checked.id and e.workspace_id = ${input.workspaceId} and checked.refusal is null returning e.id ) select exists(select 1 from updated) as renewed, coalesce((select refusal from checked), 'revoked') as code `, ); return result?.renewed ? { renewed: true } : { renewed: false, code: result?.code ?? "revoked" }; }); } /** How long after its host reported a hand-off of a compute sandbox it may * still be refusing wakes. A host refuses them for at most two minutes of a * hand-off; a wake later than that cancels the hand-off and the sandbox runs * again. The extra minute covers clocks and a report still in flight. */ export const COMPUTE_HAND_OFF_UNWAKEABLE_MS = 3 * 60_000; /** Whether the host of a compute lease's sandbox reported handing it off * recently enough that it may be refusing wakes: commands cannot start for * now, and its agent not answering is no failure of the agent. */ export function computeHostHandingOff( lease: Pick | null, nowMs = Date.now(), ): boolean { const since = lease?.backend === "compute" ? lease.computeHandingOffSince : null; return Boolean(since && nowMs - since.getTime() < COMPUTE_HAND_OFF_UNWAKEABLE_MS); } /** * RECORD that a compute sandbox went to sleep or woke, as its host reports it * through the agent gateway. Warm time accrues only while the sandbox is awake: * asleep stamps `compute_asleep_since` (no tick accrues past it), and awake * moves the meter cursor forward by exactly the time asleep, so the awake time * before the sleep is still billed and the sleep is not. Only the exact * current claim speaks for the sandbox: the enrollment must be active with this * epoch and connection instance and a live claim lease, so a report delayed * past a newer epoch's open, or one sent after a revocation, is refused * (`accepted: false`). Only the lease whose current box is this sandbox * changes; anything else is a no-op. `handingOff` stamps or clears * `compute_handing_off_since`: its host is handing it off and may refuse * wakes for a short while, which is not its agent failing. */ export async function recordComputeSandboxPower( db: Database, input: SandboxAgentLinkInput & { sandboxId: string; asleep: boolean; handingOff?: boolean }, ): Promise<{ accepted: boolean; changed: boolean }> { assertSandboxAgentLinkInput(input); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // The enrollment row first, as the link's open and renewal lock it: a // newer epoch's open or a revocation commits wholly before or after. const enrollment = await lockSandboxEnrollment(tx, input.workspaceId, input.agentId); const now = await enrollmentConnectionClock(tx); if ( !enrollment || enrollment.kind !== "sandbox" || enrollment.status !== "active" || enrollment.linkEpoch === null || Number(enrollment.linkEpoch) !== input.epoch || enrollment.connectionInstanceId !== input.connectionInstanceId || !enrollment.connectionLeaseExpiresAt || enrollment.connectionLeaseExpiresAt <= now ) { return { accepted: false, changed: false }; } const rows = await tx.execute(sql` select lease.* from sandbox_leases lease join enrollments e on e.workspace_id = lease.workspace_id and e.sandbox_group_id = lease.sandbox_group_id where lease.workspace_id = ${input.workspaceId} and e.id = ${input.agentId} and e.kind = 'sandbox' and lease.backend = 'compute' and lease.instance_id = ${input.sandboxId} for update of lease `); const row = rows[0]; if (!row) return { accepted: true, changed: false }; const handingOff = input.handingOff === true; const handOffChanged = handingOff !== Boolean(row.compute_handing_off_since); if (handOffChanged) { await tx.execute(sql` update sandbox_leases set compute_handing_off_since = ${handingOff ? sql`clock_timestamp()` : sql`null`}, updated_at = now() where id = ${row.id} `); } const asleepSince = row.compute_asleep_since ? new Date(row.compute_asleep_since) : null; if (input.asleep) { if (asleepSince) return { accepted: true, changed: handOffChanged }; await tx.execute(sql` update sandbox_leases set compute_asleep_since = clock_timestamp(), updated_at = now() where id = ${row.id} `); return { accepted: true, changed: true }; } if (!asleepSince) return { accepted: true, changed: handOffChanged }; // The cursor accrual starts from: the last tick, else the warm instant. const recovery = row.resume_state?.opengeniRecovery as | { restore?: { completedAt?: unknown } } | undefined; const warmStartMs = typeof recovery?.restore?.completedAt === "string" ? Date.parse(recovery.restore.completedAt) : Number.NaN; const cursorMs = row.last_meter_at ? new Date(row.last_meter_at).getTime() : Number.NaN; const startMs = Number.isFinite(warmStartMs) ? Math.max(Number.isFinite(cursorMs) ? cursorMs : 0, warmStartMs) : cursorMs; if (Number.isFinite(startMs) && startMs <= asleepSince.getTime()) { // Shift the unbilled awake interval [start, asleep) to end now. await tx.execute(sql` update sandbox_leases set last_meter_at = ${new Date(startMs).toISOString()}::timestamptz + (clock_timestamp() - compute_asleep_since), compute_asleep_since = null, updated_at = now() where id = ${row.id} `); } else { await tx.execute(sql` update sandbox_leases set compute_asleep_since = null, updated_at = now() where id = ${row.id} `); } return { accepted: true, changed: true }; }), ); } /** RELEASE a link session's claim when its host closes it, so the agent's next * instance can open at once. Only the exact epoch and instance release. */ export async function releaseSandboxAgentLink( db: Database, input: SandboxAgentLinkInput, ): Promise<{ released: boolean }> { assertSandboxAgentLinkInput(input); return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const now = await enrollmentConnectionClock(scopedDb); const rows = await scopedDb .update(schema.enrollments) .set({ connectionLeaseExpiresAt: now, updatedAt: now }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.agentId), eq(schema.enrollments.kind, "sandbox"), eq(schema.enrollments.linkEpoch, input.epoch), eq(schema.enrollments.connectionInstanceId, input.connectionInstanceId), ), ) .returning({ id: schema.enrollments.id }); return { released: rows.length > 0 }; }); } /** * A deadline (and optional stop signal) for maintenance work such as the * compute orphan sweep. A bounded call runs in one transaction whose every * statement the server itself ends by the deadline: before each one the work * sets the statement timeout to the time left (`limit`), so a lock wait (the * workspace tenancy lock included) or a slow statement is cancelled by * PostgreSQL at the deadline, whatever the pool's state, and nothing else is * ever cancelled. PostgreSQL never times out COMMIT, so the work runs its * commit-time work (deferred triggers) itself, under the same limit, just * before it; COMMIT then only makes the work durable. A call whose deadline * has passed, or that waited for a pooled connection until then, does nothing. * The call itself always settles by the deadline (or the stop), even when * COMMIT or a statement's answer is held up on the way. * * How a bounded call ends says what happened to its work: * - it returns: the work committed; * - {@link DatabaseWorkDeadlineError}, the stop signal's reason or any other * error: the work rolled back, because COMMIT was never sent or the server * refused it; * - {@link DatabaseWorkOutcomeUnknownError}: the deadline passed, the call * was stopped, or it lost its connection, while COMMIT was in flight, so the * work may or may not have committed. Read the state again before relying on * either. */ export type DatabaseWorkBound = { deadlineAtMs: number; signal?: AbortSignal | undefined }; export class DatabaseWorkDeadlineError extends Error { constructor(options?: { cause?: unknown }) { super("The maintenance deadline passed; the database work was rolled back.", options); this.name = "DatabaseWorkDeadlineError"; } } export class DatabaseWorkOutcomeUnknownError extends Error { constructor(options?: { cause?: unknown }) { super( "The maintenance work was interrupted while it committed; it may or may not have committed.", options, ); this.name = "DatabaseWorkOutcomeUnknownError"; } } /** Give the next statements of bounded work at most the time left. */ type LimitToDeadline = (db: Database) => Promise; const QUERY_CANCELED_SQLSTATE = "57014"; async function withinWorkBound( db: Database, bound: DatabaseWorkBound | undefined, fn: (db: Database, limit: LimitToDeadline) => Promise, ): Promise { if (!bound) return await fn(db, async () => {}); const { deadlineAtMs, signal } = bound; const limit: LimitToDeadline = async (handle) => { signal?.throwIfAborted(); const remainingMs = Math.floor(deadlineAtMs - Date.now()); if (remainingMs <= 0) throw new DatabaseWorkDeadlineError(); await handle.execute( sql`select pg_catalog.set_config('statement_timeout', ${`${remainingMs}ms`}, true)`, ); }; signal?.throwIfAborted(); if (Date.now() >= deadlineAtMs) throw new DatabaseWorkDeadlineError(); // Set once COMMIT may be on its way; until then every failure rolls back. let committing = false; // Set when the deadline or the stop signal ends the call; checked in the // same step that lets COMMIT go, so the two never both happen. let ended = false; const work = (async () => { try { return await db.transaction(async (tx) => { const scoped = tx as unknown as Database; await limit(scoped); const value = await fn(scoped, limit); // Run the deferred work COMMIT would run, while the deadline can still // end it: PostgreSQL applies no statement timeout to COMMIT. await limit(scoped); await scoped.execute(sql`set constraints all immediate`); // Checked in the same step that lets COMMIT go: a stop or deadline // seen here rolls back, and any later one finds `committing` set. signal?.throwIfAborted(); if (ended || Date.now() >= deadlineAtMs) throw new DatabaseWorkDeadlineError(); committing = true; return value; }); } catch (error) { if (error instanceof DatabaseWorkDeadlineError) throw error; const sqlState = nestedPostgresSqlState(error); // The server cancelled a statement at the deadline: the transaction // rolled back. if (sqlState === QUERY_CANCELED_SQLSTATE) throw new DatabaseWorkDeadlineError({ cause: error }); // A COMMIT the server refused rolled back. One whose answer was lost // (the connection failed, or the server ended the session or shut // down, which can happen just after the commit) may have committed. if (committing && (sqlState === null || /^(08|57P)/.test(sqlState))) throw new DatabaseWorkOutcomeUnknownError({ cause: error }); throw error; } })(); // The call settles by its deadline whatever the connection does, COMMIT // included: PostgreSQL bounds the statements, and this bounds the wait for // a pooled connection's answers and for COMMIT's. work.catch(() => {}); let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; const stopped = new Promise((_, reject) => { const end = (reason: unknown) => { if (ended) return; ended = true; reject(committing ? new DatabaseWorkOutcomeUnknownError({ cause: reason }) : reason); }; timer = setTimeout( () => end(new DatabaseWorkDeadlineError()), Math.max(0, deadlineAtMs - Date.now()), ); if (signal) { onAbort = () => end(signal.reason ?? new Error("The maintenance work was stopped.")); signal.addEventListener("abort", onAbort, { once: true }); } }); stopped.catch(() => {}); try { return await Promise.race([work, stopped]); } finally { clearTimeout(timer); if (onAbort) signal?.removeEventListener("abort", onAbort); } } // REVOKE a compute sandbox's enrollment when the sandbox is deleted, which // ends its link session at the gateway. Idempotent; never touches a machine. // A deleted workspace took the enrollment with it, which is success too. export async function revokeSandboxEnrollment( db: Database, input: { workspaceId: string; enrollmentId: string; now?: Date }, bound?: DatabaseWorkBound, ): Promise<{ revoked: boolean }> { const now = input.now ?? new Date(); const scoped = withinWorkBound(db, bound, (boundedDb, limit) => withWorkspaceRls(boundedDb, input.workspaceId, async (scopedDb) => { // The tenancy lock is held: the statement below gets only the time left. await limit(scopedDb); const rows = await scopedDb .update(schema.enrollments) .set({ status: "revoked", revokedAt: now, connectionInstanceId: null, connectionLeaseExpiresAt: null, updatedAt: now, }) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, input.enrollmentId), eq(schema.enrollments.kind, "sandbox"), eq(schema.enrollments.status, "active"), ), ) .returning({ id: schema.enrollments.id }); return { revoked: rows.length > 0 }; }), ); try { return await scoped; } catch (error) { if (error instanceof Error && error.message === `Workspace not found: ${input.workspaceId}`) { return { revoked: false }; } throw error; } } /** * Whether Opengeni's records still name one compute sandbox, for the orphan * sweep: its enrollment is active, and its group's lease either holds this box * (by sandbox id or enrollment) or is warming, which means a creator still owns * the group and may be about to commit it. A deleted workspace, a revoked * enrollment or a lease that moved on all answer false. */ export async function computeSandboxNamed( db: Database, input: { workspaceId: string; sandboxGroupId: string; enrollmentId: string; sandboxId: string }, bound?: DatabaseWorkBound, ): Promise { const scoped = withinWorkBound(db, bound, (boundedDb, limit) => withWorkspaceRls(boundedDb, input.workspaceId, async (scopedDb) => { // The tenancy lock is held: the statement below gets only the time left. await limit(scopedDb); const rows = await rawRows<{ named: boolean }>( scopedDb, sql` select exists ( select 1 from enrollments e join sandbox_leases lease on lease.workspace_id = e.workspace_id and lease.sandbox_group_id = e.sandbox_group_id where e.workspace_id = ${input.workspaceId} and e.id = ${input.enrollmentId} and e.kind = 'sandbox' and e.status = 'active' and e.sandbox_group_id = ${input.sandboxGroupId} and ( lease.liveness = 'warming' or lease.instance_id = ${input.sandboxId} or lease.resume_state #>> '{sessionState,providerState,sandboxId}' = ${input.sandboxId} or lease.resume_state #>> '{sessionState,providerState,enrollmentId}' = ${input.enrollmentId} ) ) as named `, ); return rows[0]?.named === true; }), ); try { return await scoped; } catch (error) { // A deleted workspace took its enrollments and leases with it. if (error instanceof Error && error.message === `Workspace not found: ${input.workspaceId}`) { return false; } throw error; } } /** * The compute sandbox an active sandbox enrollment runs in, as its group's * lease names it (its envelope's provider state, else the lease's instance), * or null for any other enrollment: a Connected Machine's, a revoked one, or * one no lease names. With a bound, the read ends by its deadline. */ export async function computeSandboxOfEnrollment( db: Database, input: { workspaceId: string; enrollmentId: string }, bound?: DatabaseWorkBound, ): Promise { const scoped = withinWorkBound(db, bound, (boundedDb, limit) => withWorkspaceRls(boundedDb, input.workspaceId, async (scopedDb) => { // The tenancy lock is held: the statement below gets only the time left. await limit(scopedDb); const rows = await rawRows<{ sandbox_id: string | null }>( scopedDb, sql` select coalesce( lease.resume_state #>> '{sessionState,providerState,sandboxId}', lease.instance_id ) as sandbox_id from enrollments e join sandbox_leases lease on lease.workspace_id = e.workspace_id and lease.sandbox_group_id = e.sandbox_group_id where e.workspace_id = ${input.workspaceId} and e.id::text = ${input.enrollmentId} and e.kind = 'sandbox' and e.status = 'active' and lease.resume_state #>> '{sessionState,providerState,enrollmentId}' = ${input.enrollmentId} limit 1 `, ); return rows[0]?.sandbox_id ?? null; }), ); try { return await scoped; } catch (error) { // A deleted workspace took its enrollments and leases with it. if (error instanceof Error && error.message === `Workspace not found: ${input.workspaceId}`) { return null; } throw error; } } /** The most entries one page of the stale compute enrollment inventory holds. */ export const STALE_COMPUTE_ENROLLMENT_PAGE_SIZE = 100; /** * Compute sandbox enrollments nothing can use any more: active, created more * than ten minutes ago (the create settle window), and their group's lease * neither names them (in its envelope, sessionState.providerState.enrollmentId) * nor is warming a new box, nor holds a live compute box whose envelope does * not say which enrollment it runs. These are enrollments whose * sandbox is already gone (a delete whose revoke failed, a create that never * made one), which no listing from the control service shows the orphan sweep. The * cross-workspace inventory (migration 0862) returns ids only, one page in * enrollment-id order after `after` (from the start without it), with `more` * when the inventory may go on past the page; revoke each with * {@link revokeStaleComputeSandboxEnrollment}. */ export async function listStaleComputeSandboxEnrollments( db: Database, after: string | undefined, bound?: DatabaseWorkBound, ): Promise<{ candidates: { workspaceId: string; enrollmentId: string }[]; more: boolean }> { const rows = await withinWorkBound( db, bound, async (boundedDb) => await rawRows<{ workspace_id: string; enrollment_id: string }>( boundedDb, sql` select workspace_id, enrollment_id from opengeni_private.list_stale_compute_sandbox_enrollments(${after ?? null}::uuid) order by enrollment_id `, ), ); return { candidates: rows.map((row) => ({ workspaceId: row.workspace_id, enrollmentId: row.enrollment_id, })), more: rows.length >= STALE_COMPUTE_ENROLLMENT_PAGE_SIZE, }; } /** * Revoke one enrollment the stale inventory listed, under its workspace's RLS. * The revoke re-checks the inventory's condition, so an enrollment a lease * names in the meantime stays active (false). A deleted workspace took the * enrollment with it, which is false too. With a bound, the work ends by its * deadline or stop and then commits nothing. */ export async function revokeStaleComputeSandboxEnrollment( db: Database, candidate: { workspaceId: string; enrollmentId: string }, bound?: DatabaseWorkBound, ): Promise { const scoped = withinWorkBound(db, bound, (boundedDb, limit) => withWorkspaceRls(boundedDb, candidate.workspaceId, async (scopedDb) => { // The tenancy lock is held: the statement below gets only the time left. await limit(scopedDb); const rows = await rawRows<{ id: string }>( scopedDb, sql` update enrollments e set status = 'revoked', revoked_at = now(), connection_instance_id = null, connection_lease_expires_at = null, updated_at = now() where e.workspace_id = ${candidate.workspaceId} and e.id = ${candidate.enrollmentId} and e.kind = 'sandbox' and e.status = 'active' and e.created_at < now() - interval '10 minutes' and not exists ( select 1 from sandbox_leases lease where lease.workspace_id = e.workspace_id and lease.sandbox_group_id = e.sandbox_group_id and ( lease.liveness = 'warming' or ( lease.backend = 'compute' and lease.liveness in ('warm', 'draining') and lease.instance_id is not null and lease.resume_state #>> '{sessionState,providerState,enrollmentId}' is null ) or lease.resume_state #>> '{sessionState,providerState,enrollmentId}' = e.id::text ) ) returning e.id `, ); return rows.length > 0; }), ); try { return await scoped; } catch (error) { if ( error instanceof Error && error.message === `Workspace not found: ${candidate.workspaceId}` ) { return false; } throw error; } } // THE LOUD-CONSENT APPROVE (the user's POST /approve). In ONE transaction: // 1. re-read the pending row FOR UPDATE (fence against a double-approve / a // concurrent expiry), // 2. createEnrollment (idempotent upsert: pubkey, whole-machine exposure, // has_display from can_offer_display, allow_screen_control per the user's // decision, os/arch) → an enrollments row, // 3. createSandbox (kind selfhosted, enrollment_id, a generated name) → a // sandboxes row (acceptance #2), // 4. stamp the request approved + the consent record (WHO approved WHEN to WHAT) // + the resulting enrollment_id / sandbox_id. // IDEMPOTENT: a re-approve of an ALREADY-approved row (same user_code re-submitted) // returns the existing enrollment/sandbox WITHOUT re-running the enrollment upsert, // so a lost approval response cannot rotate the credential generation. A genuinely // fresh request for the same pubkey does run the upsert and rotates. An expired / // denied / consumed row is a no-op (approved:false). export async function approveDeviceEnrollmentRequest( db: Database, input: { accountId: string; workspaceId: string; scope?: EnrollmentRecord["scope"]; allowOrganization?: boolean; requestId: string; allowScreenControl: boolean; approvedBySubjectId: string; approvedBySubjectLabel?: string | null; // A name for the generated sandbox (machine name or a fallback). sandboxName: string; now?: Date; }, ): Promise<{ approved: boolean; enrollment: EnrollmentRecord | null; sandbox: SandboxRecord | null; }> { const now = input.now ?? new Date(); const approveInScope = (database: Database) => withRlsContext( database, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.approvedBySubjectId); // Re-read FOR UPDATE under the txn so a concurrent approve / expiry can't race. const [pending] = await scopedDb .select() .from(schema.deviceEnrollmentRequests) .where( and( eq(schema.deviceEnrollmentRequests.workspaceId, input.workspaceId), eq(schema.deviceEnrollmentRequests.id, input.requestId), ), ) .for("update") .limit(1); if (!pending) { return { approved: false, enrollment: null, sandbox: null }; } // Already approved → idempotent return of the exact existing rows. Do not run // the finalize upsert again: that operation is the credential-generation // rotation boundary for a genuinely new enrollment request. if (pending.status === "approved") { if (!pending.enrollmentId || !pending.sandboxId) { throw new Error("Approved enrollment request is missing its finalized row ids"); } const [existingEnrollment] = await scopedDb .select() .from(schema.enrollments) .where( and( eq(schema.enrollments.workspaceId, input.workspaceId), eq(schema.enrollments.id, pending.enrollmentId), ), ) .limit(1); const [existingSandbox] = await scopedDb .select() .from(schema.sandboxes) .where( and( eq(schema.sandboxes.workspaceId, input.workspaceId), eq(schema.sandboxes.id, pending.sandboxId), eq(schema.sandboxes.enrollmentId, pending.enrollmentId), ), ) .limit(1); if (!existingEnrollment || !existingSandbox) { throw new Error("Approved enrollment request references missing finalized rows"); } return { approved: true, enrollment: mapEnrollment(existingEnrollment), sandbox: mapSandbox(existingSandbox), }; } const expired = pending.expiresAt.getTime() <= now.getTime(); if (pending.status === "denied" || pending.status === "consumed") { return { approved: false, enrollment: null, sandbox: null }; } if (pending.status === "pending" && expired) { return { approved: false, enrollment: null, sandbox: null }; } // The SHARED finalize core: upsert the enrollment (idempotent) + ensure a // selfhosted sandbox. RLS is already set on scopedDb's session and this call // runs INSIDE this FOR-UPDATE txn, so the re-read fence + the stamp below + the // enrollment/sandbox writes all commit atomically (semantics unchanged from the // pre-refactor inline block — acceptance #2 stays one machine). The headless // token exchange (finalizeEnrollmentByToken) calls the SAME core. const { enrollment, sandbox } = await finalizeEnrollmentInScope(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, ...(input.scope ? { scope: input.scope } : {}), allowOrganization: input.allowOrganization === true, pubkey: pending.pubkey, hasDisplay: pending.canOfferDisplay, allowScreenControl: input.allowScreenControl, os: pending.os as EnrollmentOs, arch: pending.arch, sandboxName: input.sandboxName, now, }); // Stamp the request approved + the LOUD CONSENT record (who/when/what). await scopedDb .update(schema.deviceEnrollmentRequests) .set({ status: "approved", allowScreenControl: input.allowScreenControl, approvedBySubjectId: input.approvedBySubjectId, approvedBySubjectLabel: input.approvedBySubjectLabel ?? null, approvedAt: now, enrollmentId: enrollment.id, sandboxId: sandbox.id, updatedAt: now, }) .where(eq(schema.deviceEnrollmentRequests.id, pending.id)); return { approved: true, enrollment, sandbox }; }, ); if (input.scope !== "user") return await approveInScope(db); // Organization membership precedes the tenancy fence acquired by // withRlsContext, then the pending request and enrollment rows. A Database // can itself be a transaction holding locks: fail closed rather than wait // on an unknown caller's reverse-order prefix. The SQL finalizer repeats // this nonblocking check for direct callers and old binaries. return await db.transaction(async (tx) => { const database = tx as unknown as Database; const [fence] = await rawRows<{ acquired: boolean }>( database, sql` select pg_try_advisory_xact_lock(hashtextextended( ${`organization-membership:${input.accountId}`}, 0 )) as acquired `, ); if (!fence?.acquired) { throw Object.assign(new Error("Enrollment membership is changing; retry the transaction"), { code: "55P03", }); } return await approveInScope(database); }); } // Mark a pending request DENIED (an explicit user "no" at the approve page). // Idempotent: a non-pending row is a no-op (denied:false). export async function denyDeviceEnrollmentRequest( db: Database, input: { accountId: string; workspaceId: string; requestId: string; }, ): Promise<{ denied: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.deviceEnrollmentRequests) .set({ status: "denied", updatedAt: new Date() }) .where( and( eq(schema.deviceEnrollmentRequests.workspaceId, input.workspaceId), eq(schema.deviceEnrollmentRequests.id, input.requestId), eq(schema.deviceEnrollmentRequests.status, "pending"), ), ) .returning({ id: schema.deviceEnrollmentRequests.id }); return { denied: rows.length > 0 }; }, ); } // Flip an APPROVED request to CONSUMED once the agent has polled its credentials // (single-use). Fenced on status='approved' so a double-poll consumes exactly once; // a second poll then re-reads the consumed row and still returns credentials (the // agent may legitimately retry the same poll) — the route decides. Returns whether // THIS call performed the consume transition. export async function consumeDeviceEnrollmentRequest( db: Database, input: { accountId: string; workspaceId: string; requestId: string; }, ): Promise<{ consumed: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.deviceEnrollmentRequests) .set({ status: "consumed", updatedAt: new Date() }) .where( and( eq(schema.deviceEnrollmentRequests.workspaceId, input.workspaceId), eq(schema.deviceEnrollmentRequests.id, input.requestId), eq(schema.deviceEnrollmentRequests.status, "approved"), ), ) .returning({ id: schema.deviceEnrollmentRequests.id }); return { consumed: rows.length > 0 }; }, ); } // ---- sandboxes ------------------------------------------------------------ // Create a first-class named sandbox (the pointer target a session swaps to). The // DB CHECK pins selfhosted<->enrollment_id: a selfhosted sandbox MUST carry an // enrollment; a modal sandbox MUST NOT. We surface that as a typed pre-check so // the caller gets a clear error rather than a raw constraint violation. export async function createSandbox( db: Database, input: { accountId: string; workspaceId: string; kind: SandboxKind; name: string; enrollmentId?: string | null; }, ): Promise { const enrollmentId = input.enrollmentId ?? null; if (input.kind === "selfhosted" && !enrollmentId) { throw new Error("A selfhosted sandbox requires an enrollmentId."); } if (input.kind !== "selfhosted" && enrollmentId) { throw new Error(`A ${input.kind} sandbox must not carry an enrollmentId.`); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.sandboxes) .values({ accountId: input.accountId, workspaceId: input.workspaceId, kind: input.kind, name: input.name, enrollmentId, }) .returning(); if (!row) { throw new Error("Failed to create sandbox"); } return mapSandbox(row); }, ); } export async function getSandbox( db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string }, sandboxId: string, ): Promise { // Sandbox ids are UUIDs. Anything else (for example a machine's display name) // names no sandbox, so answer "not found" rather than failing the uuid cast. if (!UUID_PATTERN.test(sandboxId)) return null; if (typeof access !== "string") { return await withRlsContext(db, access, async (scopedDb) => { await setSubjectRlsContext(scopedDb, access.subjectId); const [row] = await rawRows<{ value: SandboxRecord | null }>( scopedDb, sql`select get_scoped_sandbox( ${access.accountId}::uuid, ${access.workspaceId}::uuid, ${sandboxId}::uuid ) as value`, ); return row?.value ?? null; }); } const workspaceId = access; return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sandboxes) .where(and(eq(schema.sandboxes.workspaceId, workspaceId), eq(schema.sandboxes.id, sandboxId))) .limit(1); return row ? mapSandbox(row) : null; }); } /** Exact-turn machine consent can expose one route without exposing the owner's * machine list or borrowing their authority for any other resource. */ export async function getSandboxForAttempt( db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; }, sandboxId: string, ): Promise { if (!UUID_PATTERN.test(sandboxId)) return null; const projection = await withRlsContext(db, input, async (scopedDb) => { await setMachineAttemptSubject(scopedDb, input.subjectId); const [row] = await rawRows<{ value: { sandbox: SandboxRecord | null } | null }>( scopedDb, sql`select get_session_attempt_machine( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.attemptId}::uuid, ${input.executionGeneration}::integer, ${sandboxId}::uuid, null, false, true ) as value`, ); return row?.value ?? null; }); if (projection) return projection.sandbox; return await getSandbox( db, input.subjectId ? { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId } : input.workspaceId, sandboxId, ); } async function setMachineAttemptSubject(db: Database, subjectId: string | null): Promise { if (subjectId) await setSubjectRlsContext(db, subjectId); // A service turn has no human. Explicitly clear any ambient actor rather than // borrowing the owner who consented to its machine route. await db.execute(sql`select set_config('opengeni.subject_id', ${subjectId ?? ""}, true), set_config('opengeni.initiating_human_subject_id', ${subjectId ?? ""}, true) `); } // List a workspace's sandboxes, newest first (the sandboxes_list tool surface). export async function listSandboxes(db: Database, workspaceId: string): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sandboxes) .where(eq(schema.sandboxes.workspaceId, workspaceId)) .orderBy(desc(schema.sandboxes.createdAt)); return rows.map(mapSandbox); }); } // ---- the per-session active-sandbox pointer (epoch-fenced swap) ----------- // The swap itself lives in ./active-sandbox. // The INVERSE of readActiveSandbox: every session in a workspace whose ACTIVE // SANDBOX resolves to enrollment X AND that has a RUNNING TURN — i.e. "sessions // with an active op on machine X". This is the fan-out target set for the // machine-link session events (a machine's control link changing only concerns the // sessions actively using it; an idle-machine blip must never spam historical // sessions). ONE indexed lookup: the query drives from `sandboxes` via the partial // `sandboxes_enrollment_idx` (enrollment_id WHERE NOT NULL), joins `sessions` on // the active-sandbox pointer, and keeps only rows with a non-null active_turn_id (a // running turn). Deliberately a v1 OVER-APPROXIMATION — no per-op tracking table. export async function sessionsWithActiveOpOnEnrollment( db: Database, input: { workspaceId: string; enrollmentId: string }, ): Promise> { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await scopedDb .select({ sessionId: schema.sessions.id, activeTurnId: schema.sessions.activeTurnId, }) .from(schema.sandboxes) .innerJoin(schema.sessions, eq(schema.sessions.activeSandboxId, schema.sandboxes.id)) .where( and( eq(schema.sandboxes.workspaceId, input.workspaceId), eq(schema.sandboxes.kind, "selfhosted"), eq(schema.sandboxes.enrollmentId, input.enrollmentId), isNotNull(schema.sessions.activeTurnId), ), ) // Stable fan-out order (oldest session first): makes the emission // deterministic + replayable, so a per-session emission failure is isolated // predictably rather than depending on the planner's row order. .orderBy(asc(schema.sessions.createdAt), asc(schema.sessions.id)); // active_turn_id is non-null by the WHERE guard; the map narrows the type. return rows.flatMap((row) => row.activeTurnId ? [{ sessionId: row.sessionId, activeTurnId: row.activeTurnId }] : [], ); }); } // Read the session's current pointer (the routing proxy re-reads this PER TOOL // CALL). NULL active_sandbox_id == "use the session's own group sandbox". export async function readActiveSandbox( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ activeSandboxId: schema.sessions.activeSandboxId, activeEpoch: schema.sessions.activeEpoch, workingDir: schema.sessions.workingDir, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!row) { return null; } return { activeSandboxId: row.activeSandboxId ?? null, activeEpoch: Number(row.activeEpoch), workingDir: row.workingDir ?? null, }; }); } // ---- per-machine metrics (§10.7) ------------------------------------------ // The sampled signal set the agent piggybacks on the heartbeat. Every field is // optional (a platform/sample may not provide it — no GPU, headless, etc.). export type MachineMetricsSample = { cpuPercent?: number | null; load1?: number | null; load5?: number | null; load15?: number | null; memUsedBytes?: number | null; memTotalBytes?: number | null; diskUsedBytes?: number | null; diskTotalBytes?: number | null; gpuUtilPercent?: number | null; gpuMemUsedBytes?: number | null; gpuMemTotalBytes?: number | null; contention?: number | null; sampledAt: Date; }; function metricColumns(sample: MachineMetricsSample) { return { cpuPercent: sample.cpuPercent ?? null, load1: sample.load1 ?? null, load5: sample.load5 ?? null, load15: sample.load15 ?? null, memUsedBytes: sample.memUsedBytes ?? null, memTotalBytes: sample.memTotalBytes ?? null, diskUsedBytes: sample.diskUsedBytes ?? null, diskTotalBytes: sample.diskTotalBytes ?? null, gpuUtilPercent: sample.gpuUtilPercent ?? null, gpuMemUsedBytes: sample.gpuMemUsedBytes ?? null, gpuMemTotalBytes: sample.gpuMemTotalBytes ?? null, contention: sample.contention ?? null, sampledAt: sample.sampledAt, }; } // Last-sample UPSERT: one row per enrollment, overwritten every sample (PK on // enrollment_id is the conflict target). The Machines dashboard's "now" read. export async function upsertMachineMetricsLatest( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sample: MachineMetricsSample; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const cols = metricColumns(input.sample); await scopedDb .insert(schema.machineMetricsLatest) .values({ enrollmentId: input.enrollmentId, accountId: input.accountId, workspaceId: input.workspaceId, ...cols, }) .onConflictDoUpdate({ target: schema.machineMetricsLatest.enrollmentId, set: { ...cols, updatedAt: new Date() }, }); }, ); } // Append a downsampled (~1/min) series row (the history the dashboard time-range // reads + the later retention sweep prune). export async function insertMachineMetricsSeries( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sample: MachineMetricsSample; }, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb.insert(schema.machineMetricsSeries).values({ enrollmentId: input.enrollmentId, accountId: input.accountId, workspaceId: input.workspaceId, ...metricColumns(input.sample), }); }, ); } // The target spacing between series rows: the agent heartbeats ~every 5s, but we // downsample the long-term history to ~1/min. A new series row is // appended only when >= this much time has elapsed since the last one. export const MACHINE_METRICS_SERIES_INTERVAL_MS = 60_000; /** * Ingest ONE sampled metrics point for an enrollment (the M10 ingestion seam): * 1. UPSERT machine_metrics_latest (the "now" row, one per enrollment) — always. * 2. APPEND a machine_metrics_series row only when >= ~1/min has elapsed since * the last series row (downsample) — so the 5s heartbeat cadence does not * flood the history table. * Both happen under the same RLS context. Returns whether a series row was * appended (the downsample decision) so the caller / tests can assert the ~1/min * spacing. A null/absent `sampledAt` on the prior row treats it as "no prior" → * append. */ export async function ingestMachineMetricsSample( db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sample: MachineMetricsSample; /** Override the downsample interval (tests). Defaults to ~1/min. */ seriesIntervalMs?: number; }, ): Promise<{ latestUpserted: true; seriesAppended: boolean }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const cols = metricColumns(input.sample); // 1. Latest upsert — always. await scopedDb .insert(schema.machineMetricsLatest) .values({ enrollmentId: input.enrollmentId, accountId: input.accountId, workspaceId: input.workspaceId, ...cols, }) .onConflictDoUpdate({ target: schema.machineMetricsLatest.enrollmentId, set: { ...cols, updatedAt: new Date() }, }); // 2. Series append — downsampled. Read the most recent series sampled_at and // only append when the new sample is >= the interval newer (or there is no // prior row). Done in-context so RLS scopes the read to this workspace. const intervalMs = input.seriesIntervalMs ?? MACHINE_METRICS_SERIES_INTERVAL_MS; const [prior] = await scopedDb .select({ sampledAt: schema.machineMetricsSeries.sampledAt }) .from(schema.machineMetricsSeries) .where(eq(schema.machineMetricsSeries.enrollmentId, input.enrollmentId)) .orderBy(desc(schema.machineMetricsSeries.sampledAt)) .limit(1); const priorMs = prior?.sampledAt ? prior.sampledAt.getTime() : null; const sampleMs = input.sample.sampledAt.getTime(); const seriesAppended = priorMs === null || sampleMs - priorMs >= intervalMs; if (seriesAppended) { await scopedDb.insert(schema.machineMetricsSeries).values({ enrollmentId: input.enrollmentId, accountId: input.accountId, workspaceId: input.workspaceId, ...cols, }); } return { latestUpserted: true, seriesAppended }; }, ); } // The mapped read shape of a stored metrics sample (latest or a series point). // numeric columns come back as strings from postgres-js; map them to numbers (or // null when never reported). The byte columns are bigint(mode:"number"). export type MachineMetricsRow = { enrollmentId: string; cpuPercent: number | null; load1: number | null; load5: number | null; load15: number | null; memUsedBytes: number | null; memTotalBytes: number | null; diskUsedBytes: number | null; diskTotalBytes: number | null; gpuUtilPercent: number | null; gpuMemUsedBytes: number | null; gpuMemTotalBytes: number | null; contention: number | null; sampledAt: string; }; function numericOrNull(value: unknown): number | null { if (value === null || value === undefined) return null; const n = typeof value === "number" ? value : Number(value); return Number.isFinite(n) ? n : null; } function mapMetricsRow(row: { enrollmentId: string; cpuPercent: number | string | null; load1: number | string | null; load5: number | string | null; load15: number | string | null; memUsedBytes: number | null; memTotalBytes: number | null; diskUsedBytes: number | null; diskTotalBytes: number | null; gpuUtilPercent: number | string | null; gpuMemUsedBytes: number | null; gpuMemTotalBytes: number | null; contention: number | string | null; sampledAt: Date; }): MachineMetricsRow { return { enrollmentId: row.enrollmentId, cpuPercent: numericOrNull(row.cpuPercent), load1: numericOrNull(row.load1), load5: numericOrNull(row.load5), load15: numericOrNull(row.load15), memUsedBytes: row.memUsedBytes ?? null, memTotalBytes: row.memTotalBytes ?? null, diskUsedBytes: row.diskUsedBytes ?? null, diskTotalBytes: row.diskTotalBytes ?? null, gpuUtilPercent: numericOrNull(row.gpuUtilPercent), gpuMemUsedBytes: row.gpuMemUsedBytes ?? null, gpuMemTotalBytes: row.gpuMemTotalBytes ?? null, contention: numericOrNull(row.contention), sampledAt: row.sampledAt.toISOString(), }; } // Read the latest sample for ONE enrollment (the dashboard "now" read), or null // when none has landed (never seen / offline before a first heartbeat). export async function readMachineMetricsLatest( db: Database, workspaceId: string, enrollmentId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.machineMetricsLatest) .where( and( eq(schema.machineMetricsLatest.workspaceId, workspaceId), eq(schema.machineMetricsLatest.enrollmentId, enrollmentId), ), ) .limit(1); return row ? mapMetricsRow(row) : null; }); } // Read the latest sample for EVERY enrollment in a workspace, keyed by // enrollmentId — the Machines list joins this onto the fleet entries with ONE // query rather than N per-machine reads. export async function readMachineMetricsLatestForWorkspace( db: Database, workspaceId: string, ): Promise> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.machineMetricsLatest) .where(eq(schema.machineMetricsLatest.workspaceId, workspaceId)); const byEnrollment = new Map(); for (const row of rows) { byEnrollment.set(row.enrollmentId, mapMetricsRow(row)); } return byEnrollment; }); } // Read the downsampled series for ONE enrollment over a time window (the // dashboard time-range read). `sinceMs` bounds the window (e.g. now - 1h); // ordered oldest-first for a left-to-right chart. `limit` caps the row count // (defensive against an unbounded window). export async function readMachineMetricsSeries( db: Database, input: { workspaceId: string; enrollmentId: string; since: Date; limit?: number; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.machineMetricsSeries) .where( and( eq(schema.machineMetricsSeries.workspaceId, input.workspaceId), eq(schema.machineMetricsSeries.enrollmentId, input.enrollmentId), gte(schema.machineMetricsSeries.sampledAt, input.since), ), ) .orderBy(asc(schema.machineMetricsSeries.sampledAt)) .limit(input.limit ?? 5_000); return rows.map(mapMetricsRow); }); } // ============================================================================ // P3.2 — the direct-pixel consent gate + viewer revocation. // // The desktop-stream path is gated behind an explicit acknowledgment that the // pixel plane exposes the desktop exactly (it can show credentials the agent // renders in a terminal — strictly broader than the structured Channel-A event // log). For a // SHARED box (the group has >1 session) the principal must additionally consent // to the shared-exposure disclosure: watching A's desktop also shows B's agent // on the one :0 framebuffer (addendum E.1 / stress g). Consent is per-PRINCIPAL // and per-GROUP (one :0 per group), recorded in session_stream_acknowledgments // (0019). Reuses the acknowledgment machinery — no new permission beyond // stream:acknowledge. // ============================================================================ export interface StreamAcknowledgment { acknowledgedUnredacted: boolean; acknowledgedShared: boolean; } // Record (or upsert) a principal's acknowledgment of the group's direct // pixel plane (and, when shared, the shared-exposure disclosure). Keyed on // (workspace, group, subject); a re-ack (e.g. a solo→shared upgrade adding the // shared consent) is ON CONFLICT DO UPDATE, never a duplicate row. export async function recordStreamAcknowledgment( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; subjectId: string; acknowledgeUnredacted: boolean; acknowledgeShared: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ acknowledged_unredacted: boolean; acknowledged_shared: boolean; }>(sql` insert into session_stream_acknowledgments (account_id, workspace_id, sandbox_group_id, subject_id, acknowledged_unredacted, acknowledged_shared, acknowledged_at, updated_at) values (${input.accountId}, ${input.workspaceId}, ${input.sandboxGroupId}, ${input.subjectId}, ${input.acknowledgeUnredacted}, ${input.acknowledgeShared}, now(), now()) on conflict (workspace_id, sandbox_group_id, subject_id) do update set -- Acknowledgment is monotonic: a later ack can ADD the shared consent -- but never silently withdraw a prior one (OR the bits in). acknowledged_unredacted = session_stream_acknowledgments.acknowledged_unredacted or excluded.acknowledged_unredacted, acknowledged_shared = session_stream_acknowledgments.acknowledged_shared or excluded.acknowledged_shared, acknowledged_at = now(), updated_at = now() returning acknowledged_unredacted, acknowledged_shared `); const row = rows[0]!; return { acknowledgedUnredacted: row.acknowledged_unredacted, acknowledgedShared: row.acknowledged_shared, }; }, ); } // Read a principal's recorded acknowledgment for a group, or null if they have // never acknowledged the un-redacted pixel plane. The negotiation read + the // desktop-stream gate both consult this. export async function getStreamAcknowledgment( db: Database, input: { workspaceId: string; sandboxGroupId: string; subjectId: string; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const rows = await scopedDb.execute<{ acknowledged_unredacted: boolean; acknowledged_shared: boolean; }>(sql` select acknowledged_unredacted, acknowledged_shared from session_stream_acknowledgments where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and subject_id = ${input.subjectId} limit 1 `); if (!rows[0]) return null; return { acknowledgedUnredacted: rows[0].acknowledged_unredacted, acknowledgedShared: rows[0].acknowledged_shared, }; }); } // Enumerate the session ids in a group (workspace-scoped). The shared-exposure // disclosure surfaces the OTHER sessions' ids ONLY — never their goal/metadata/ // conversation. The query selects ONLY the id column (id is the disclosure // boundary; stress g). RLS-scoped: a foreign-workspace group returns no rows. export async function listSessionIdsInGroup( db: Database, workspaceId: string, sandboxGroupId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await rawRows<{ id: string }>( scopedDb, sql` select id from sessions where workspace_id = ${workspaceId} and sandbox_group_id = ${sandboxGroupId} order by created_at asc `, ); return rows.map((r) => r.id); }); } /** * Count every session on a sandbox group, including Only-me sessions the * caller cannot read. Whether a box is shared is a property of the box, so the * shared-exposure disclosure must not depend on the caller's visibility. Only * a number leaves this function; member ids stay actor-scoped * (listSessionIdsInGroup). */ export async function countAllSessionsInGroup( db: Database, workspaceId: string, sandboxGroupId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { await scopedDb.execute(sql`select set_config('opengeni.subject_id', '', true)`); const [row] = await rawRows<{ count: number }>( scopedDb, sql`select count(*)::int as count from sessions where workspace_id = ${workspaceId} and sandbox_group_id = ${sandboxGroupId}`, ); return Number(row?.count ?? 0); }); } // OD-6 v1 — revoke a viewer: DROP that viewer's holder from the GROUP lease so // refcount recomputes (the box drains iff nothing else holds it — a turn-held or // other-viewer-held box survives), AND block its reconnect by recording the // revoked subject so a re-attach with the same viewerId is refused. The // live-RFB force-disconnect of an already-open socket is a P4 follow-up; the // holder-drop (so the box can drain) is here. // // Returns the post-drop lease liveness/refcount (null if the lease was already // cold-and-reaped — a revoke is then an idempotent no-op). A revoked viewer who // independently holds a holder on a SIBLING session may still watch via that // session (correct — authorized there); this drops ONLY the named viewerId's // holder. export async function revokeViewer( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; viewerId: string; idleGraceMs: number; }, ): Promise<{ liveness: SandboxLeaseLiveness; refcount: number } | null> { // The drop is exactly releaseLeaseHolder's idempotent delete-my-row + // recompute (refcount recomputes; warm→draining is guarded refcount=0 AND // turn_holders=0, so a turn-held box never drains on a viewer revoke). The // reconnect-block is a P4 concern (the holder-drop is the v1 deliverable — // the box can now drain); a re-attach mints a fresh viewerId regardless. return await releaseLeaseHolder(db, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: input.sandboxGroupId, kind: "viewer", holderId: input.viewerId, idleGraceMs: input.idleGraceMs, }); } // ============================================================================ // Warm-time metering (P2.1) — the COST hole the lease design opens. // // A box held warm by a viewer with no agent turn running emits ZERO model usage // today; the provider bills by wall-clock and Opengeni meters nothing. Warm-time // accrues on TWO stateless ticks: (a) the turn's existing activity heartbeat // (while a turn runs); (b) the reaper sweep (for viewer-only boxes between turns). // // The meter is GROUP-KEYED + epoch-keyed + tick-keyed: // idempotencyKey = usage:sandbox.warm_seconds::: // so a SHARED box (N sessions on one group) is metered EXACTLY ONCE per tick // (N sessions != N x bill — a session-keyed meter would N x-over-bill), and a // re-dispatched/overlapping tick at the same (group,epoch,tick) can never // double-charge (recordUsageEvent is onConflictDoNothing on idempotencyKey). // // Cursor advance + usage insert + paid settlement are ATOMIC: all run inside ONE FOR UPDATE txn on // the lease row (the M3 cross-statement-atomicity fix). The insert uses ON // CONFLICT DO NOTHING on idempotency_key (matching recordUsageEvent), and the // cursor (last_meter_at/last_meter_tick) is advanced in the SAME txn — so the tick // index and the metered seconds can never desync, and a partial-failure rollback // leaves BOTH the cursor and the event untouched. // ============================================================================ export interface AccrueWarmSecondsResult { /** false when nothing was accrued (epoch fenced / not warm / no elapsed / the * first tick that only seeds the cursor). */ accrued: boolean; /** Whole seconds metered this tick (0 when accrued:false). */ seconds: number; /** The monotonic tick index this accrual was recorded under. */ tick: number; /** Internal usd_micros estimate for this tick (0 in usage_only mode). */ costMicros: number; } /** * Accrue warm-seconds for the elapsed wall-clock since the lease's last meter * cursor, idempotent on (sandbox_group_id, lease_epoch, tick). EPOCH-FENCED + * liveness-guarded (warm, or draining for a final provider-stop tick). The first * interval begins at the warm transition's recovery timestamp. A draining tick * is only allowed by the provider-stop path, never by the periodic reaper list. * In credits mode the signed full-cost ledger debit, both usage rows and cursor * commit together; a settlement failure rolls back the tick for retry. */ export async function accrueWarmSeconds( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; /** The epoch the tick observed; the fence — a stale writer no-ops. */ expectedEpoch: number; /** usd_micros per warm-second for this box's backend (0 = meter only, no cost). */ warmRateMicrosPerSecond: number; /** Optional attribution: the founding/observing session (visibility only — the * group meter key makes the workspace charge correct regardless). */ subjectId?: string | null; billingMode?: "usage_only" | "shadow" | "credits"; /** Final provider-stop tick, after provider termination and before cold CAS. */ finalDrain?: boolean; }, ): Promise { const none: AccrueWarmSecondsResult = { accrued: false, seconds: 0, tick: 0, costMicros: 0, }; const result = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Lock the group's lease row so the cursor advance + the usage insert are // one atomic step (no other tick can interleave between the diff and the // cursor write). const rows = await tx.execute(sql` select * from sandbox_leases where workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} for update `); const row = rows[0]; if (!row) return none; // An ordinary heartbeat must never charge a box already draining. if ( Number(row.lease_epoch) !== input.expectedEpoch || (row.liveness !== "warm" && !(input.finalDrain && row.liveness === "draining")) ) { return none; } // commitWarmingToWarm stores this timestamp in the recovery envelope // before changing the lease to warm. The legacy cursor is nullable and // survives a new epoch: never start a new epoch at the previous box's // cursor. Refuse an invalid/missing transition timestamp instead of // charging an arbitrary cold/warming interval. const recovery = row.resume_state?.opengeniRecovery as | { restore?: { completedAt?: unknown } } | undefined; const warmStartedAt = recovery?.restore?.completedAt; const warmStartMs = typeof warmStartedAt === "string" ? Date.parse(warmStartedAt) : NaN; const snapshot = warmBillingSnapshot(row); if (row.resume_state?.opengeniWarmBilling && !snapshot) { throw new Error("sandbox warm billing snapshot is invalid"); } // A current usage_only/shadow policy is a rollback switch for a paid // lease. In credits mode, only a box explicitly snapshotted as paid may // debit; pre-activation legacy boxes cannot acquire surprise charges. const mode = input.billingMode === "credits" ? (snapshot?.mode ?? "usage_only") : (input.billingMode ?? snapshot?.mode ?? "usage_only"); const rate = snapshot?.rateMicrosPerSecond ?? input.warmRateMicrosPerSecond; if (!Number.isFinite(warmStartMs) && mode === "credits" && rate > 0) { throw new Error("paid warm lease has no valid warm-transition timestamp"); } if (!Number.isFinite(warmStartMs) && row.last_meter_at == null) { // Legacy unpriced leases cannot prove their first warm instant. Seed // only these rows; new warm transitions carry an exact recovery clock. await tx.execute(sql` update sandbox_leases set last_meter_at = now(), updated_at = now() where id = ${row.id} `); return none; } const cursorMs = row.last_meter_at ? new Date(row.last_meter_at).getTime() : 0; const startMs = Number.isFinite(warmStartMs) ? Math.max(cursorMs, warmStartMs) : cursorMs; if (input.finalDrain && !snapshot?.stopChargeAt) { throw new Error("sandbox final tick has no durable stop cutoff"); } const chargeUntil = snapshot?.stopChargeAt && input.finalDrain ? sql`${snapshot.stopChargeAt}::timestamptz` : sql`clock_timestamp()`; // A sleeping compute sandbox runs no VM: nothing accrues past the moment // it fell asleep (recordComputeSandboxPower moves the cursor on waking). const asleepSince = row.compute_asleep_since ? new Date(row.compute_asleep_since).toISOString() : null; const upperBound = asleepSince ? sql`least(${chargeUntil}, ${asleepSince}::timestamptz)` : chargeUntil; const elapsedRows = await tx.execute<{ elapsed_ms: number | string }>(sql` select greatest(0, floor(extract(epoch from (${upperBound} - ${new Date(startMs).toISOString()}::timestamptz)) * 1000))::bigint as elapsed_ms `); const elapsedMs = Number(elapsedRows[0]?.elapsed_ms ?? 0); const elapsedS = Math.floor(elapsedMs / 1000); if (elapsedS <= 0 && !(input.finalDrain && elapsedMs > 0)) { // No whole second elapsed yet — leave the cursor untouched so the // remainder accrues on the next tick (no silent seconds loss). return none; } const tick = Number(row.last_meter_tick) + 1; const costMicros = mode === "usage_only" ? 0 : Math.round((input.finalDrain ? elapsedMs / 1000 : elapsedS) * rate); if (!Number.isSafeInteger(costMicros) || costMicros < 0) { throw new Error("warm-cost estimate exceeds safe integer micros"); } // (1) The warm-seconds meter — GROUP+epoch+tick keyed, ON CONFLICT DO // NOTHING (the idempotency that makes a shared box one stream + a re-fire a // no-op). sourceResourceId is keyed on (group, epoch). await tx.execute(sql` insert into usage_events (account_id, workspace_id, subject_id, event_type, quantity, unit, source_resource_type, source_resource_id, idempotency_key, initiator_context, occurred_at) values (${input.accountId}, ${input.workspaceId}, ${input.subjectId ?? null}, 'sandbox.warm_seconds', ${elapsedS}, 'seconds', 'sandbox_lease', ${`${input.sandboxGroupId}:${input.expectedEpoch}`}, ${`usage:sandbox.warm_seconds:${input.sandboxGroupId}:${input.expectedEpoch}:${tick}`}, ${JSON.stringify(mode === "shadow" ? { warmCostShadowMicros: costMicros } : {})}::jsonb, now()) on conflict (idempotency_key) do nothing `); // (2) Only credits mode publishes actual warm spend. Shadow's internal // estimate rides the seconds event, never a public spend event. let settledCostMicros = costMicros; if (costMicros > 0 && mode === "credits") { const costKey = `usage:sandbox.warm_cost:${input.sandboxGroupId}:${input.expectedEpoch}:${tick}`; const inserted = await tx.execute<{ quantity: number | string }>(sql` insert into usage_events (account_id, workspace_id, subject_id, event_type, quantity, unit, source_resource_type, source_resource_id, idempotency_key, occurred_at) values (${input.accountId}, ${input.workspaceId}, ${input.subjectId ?? null}, 'sandbox.warm_cost', ${costMicros}, 'usd_micros', 'sandbox_lease', ${`${input.sandboxGroupId}:${input.expectedEpoch}`}, ${costKey}, now()) on conflict (idempotency_key) do nothing returning quantity `); // Replayed historical cursor writes must settle the originally // recorded tick, not today's recalculated interval or new tariff. const previous = inserted[0] ? null : await tx.execute<{ quantity: number | string }>(sql` select quantity from usage_events where idempotency_key = ${costKey} and account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and event_type = 'sandbox.warm_cost' `); settledCostMicros = Number((inserted[0] ?? previous?.[0])?.quantity ?? 0); if (!Number.isSafeInteger(settledCostMicros) || settledCostMicros <= 0) { throw new Error("warm-cost tick idempotency key conflicts with another usage event"); } } if (costMicros > 0 && mode === "credits") { await applyCreditDebitAfterUse(tx, { accountId: input.accountId, workspaceId: input.workspaceId, type: "sandbox.warm_cost", amountMicros: settledCostMicros, sourceType: "sandbox_lease", sourceId: `${input.sandboxGroupId}:${input.expectedEpoch}`, idempotencyKey: `debit:sandbox.warm_cost:${input.sandboxGroupId}:${input.expectedEpoch}:${tick}`, metadata: creditDebitAttributionMetadata(snapshot?.attribution ?? { kind: "unknown" }), }); } // (3) Advance the cursor IN THE SAME TXN — the atomicity that makes the tick // index and the metered seconds inseparable. await tx.execute(sql` update sandbox_leases set last_meter_at = ${new Date(startMs).toISOString()}::timestamptz + (${String(input.finalDrain ? elapsedMs : elapsedS * 1000)} || ' milliseconds')::interval, last_meter_tick = ${tick}, updated_at = now() where id = ${row.id} `); return { accrued: true, seconds: elapsedS, tick, costMicros: settledCostMicros }; }), ); return result; } // §2.2/2.3 — independent optional warm quota. Exhausted credits are enforced // at paid admission; they never cancel an already active holder. The cap can // close new viewer admission but only idle, holderless boxes may drain. export interface ForceDrainResult { /** Whether the workspace exceeded its optional warm cap. */ overLimit: boolean; /** The reason, for observability. */ reason: SandboxViewerForceDrainReason | null; /** The (workspaceId, sandboxGroupId) holderless boxes CASed warm->draining. */ drained: { workspaceId: string; sandboxGroupId: string }[]; } // Start of the current UTC month (the default warm-cap window). Local helper so // packages/db has no dependency on a worker/api date util; callers may override // via capWindowStart to keep the fn time-source-agnostic for tests. function startOfUtcMonthDefault(date = new Date()): Date { return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1, 0, 0, 0, 0)); } export async function forceDrainOverLimitViewerOnlyBoxes( db: Database, input: { workspaceId: string; /** Legacy caller option; balance belongs to paid admission, not draining. */ enforceBalance: boolean; /** warm-second cap (cumulative this UTC month). 0 = unbounded (no cap gate). */ maxWarmSecondsPerWorkspace: number; /** start of the cap window (caller passes startOfUtcMonth() so the fn stays * time-source-agnostic for tests). */ capWindowStart?: Date; /** drain-grace horizon stamped on the newly-draining rows (matches the reaper). */ idleGraceMs: number; }, ): Promise { return await withWorkspaceUsageLock(db, input.workspaceId, async (scopedDb) => { // Determine over-limit under the lock (so the cap read + the drain are one // serialized critical section per workspace). let reason: SandboxViewerForceDrainReason | null = null; if (input.maxWarmSecondsPerWorkspace > 0) { const since = input.capWindowStart ?? startOfUtcMonthDefault(); const [{ total } = { total: 0 }] = await scopedDb .select({ total: sql`coalesce(sum(${schema.usageEvents.quantity}), 0)`, }) .from(schema.usageEvents) .where( and( eq(schema.usageEvents.workspaceId, input.workspaceId), eq(schema.usageEvents.eventType, "sandbox.warm_seconds"), gt(schema.usageEvents.occurredAt, since), ), ); if (Number(total) >= input.maxWarmSecondsPerWorkspace) { reason = "warm_cap"; } } if (!reason) { // A top-up, a monthly-cap rollover, or a deployment policy change clears // the durable admission gate only after this fresh serialized evaluation. await scopedDb.execute(sql` update workspaces set sandbox_viewer_force_drain_reason = null, sandbox_viewer_force_drain_requested_at = null, updated_at = now() where id = ${input.workspaceId} and sandbox_viewer_force_drain_reason is not null `); return { overLimit: false, reason: null, drained: [] }; } // Publish a cap-only gate; no paid-balance gate survives a top-up or mode // change. An already active holder keeps the provider alive. await scopedDb.execute(sql` update workspaces set sandbox_viewer_force_drain_reason = ${reason}, sandbox_viewer_force_drain_requested_at = case when sandbox_viewer_force_drain_reason is distinct from ${reason} then now() else coalesce(sandbox_viewer_force_drain_requested_at, now()) end, updated_at = now() where id = ${input.workspaceId} and ( sandbox_viewer_force_drain_reason is distinct from ${reason} or sandbox_viewer_force_drain_requested_at is null ) `); // Lock only holderless candidates. Neither the cap nor a zero balance may // mark an active Browser/ComputerSession, viewer, direct op or process lost. await scopedDb.execute(sql` select lease.id from sandbox_leases lease where lease.workspace_id = ${input.workspaceId} and lease.liveness = 'warm' and lease.refcount = 0 and lease.backend <> 'compute' and not exists (select 1 from sandbox_lease_holders h where h.lease_id = lease.id) order by id for update `); // Normal release/reaper already drains holderless boxes. This CAS is a // bounded accelerator only; it cannot delete an active holder. const drained = await rawRows<{ sandbox_group_id: string }>( scopedDb, sql` update sandbox_leases lease set liveness = 'draining', refcount = 0, turn_holders = 0, viewer_holders = 0, expires_at = now() + (${String(input.idleGraceMs)} || ' milliseconds')::interval, updated_at = now() where lease.workspace_id = ${input.workspaceId} and lease.liveness = 'warm' and lease.refcount = 0 and lease.backend <> 'compute' and not exists (select 1 from sandbox_lease_holders h where h.lease_id = lease.id) returning lease.sandbox_group_id `, ); return { overLimit: true, reason, drained: drained.map((r) => ({ workspaceId: input.workspaceId, sandboxGroupId: r.sandbox_group_id, })), }; }); } export async function saveRunState( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; serializedRunState: string; pendingApprovals: unknown[]; }, ): Promise { // Measured before the transaction; a stale attempt still reports stale first. const violation = approvalRunStateSaveViolation(input.serializedRunState, input.pendingApprovals); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const allowed = await lockTurnAttemptWriteFenceTx(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: input.expectedExecutionGeneration, attemptId: input.expectedAttemptId, }); if (!allowed.allowed) return false; if (violation) throw violation; const [{ maxVersion } = { maxVersion: 0 }] = await tx .select({ maxVersion: sql`coalesce(max(${schema.agentRunStates.stateVersion}), 0)`, }) .from(schema.agentRunStates) .where( and( eq(schema.agentRunStates.workspaceId, input.workspaceId), eq(schema.agentRunStates.sessionId, input.sessionId), ), ); await tx.insert(schema.agentRunStates).values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, stateVersion: Number(maxVersion) + 1, serializedRunState: input.serializedRunState, pendingApprovals: input.pendingApprovals, }, "serializedRunState", "serializedRunStateCodecVersion", ), "pendingApprovals", "pendingApprovalsCodecVersion", ), ); return true; }); }, ); } /** * Check a RunState against its materialization envelope before any database * work. The measurement is linear in the text (see measureJsonObjectText), so * callers run it before opening their transaction and throw the returned error * at the point where they would otherwise insert the row. */ function approvalRunStateSaveViolation( serializedRunState: string, pendingApprovals: unknown[], ): ApprovalRunStateLimitExceededError | null { const limits = DEFAULT_APPROVAL_RUN_STATE_LIMITS; const actualBytes = Buffer.byteLength(serializedRunState, "utf8"); if (actualBytes > limits.maximumJsonBytes) { return new ApprovalRunStateLimitExceededError( "json_bytes", actualBytes, limits.maximumJsonBytes, ); } if (pendingApprovals.length > limits.maximumPendingApprovalItems) { return new ApprovalRunStateLimitExceededError( "pending_approval_items", pendingApprovals.length, limits.maximumPendingApprovalItems, ); } const pendingApprovalJson = JSON.stringify(pendingApprovals); const pendingApprovalBytes = Buffer.byteLength(pendingApprovalJson, "utf8"); if (pendingApprovalBytes > limits.maximumPendingApprovalBytes) { return new ApprovalRunStateLimitExceededError( "pending_approval_bytes", pendingApprovalBytes, limits.maximumPendingApprovalBytes, ); } return approvalRunStateMeasurementViolation( { ...boundedApprovalRunStateTextMeasurement(serializedRunState, actualBytes, limits), pendingApprovalBytes, pendingApprovalItems: pendingApprovals.length, }, limits, ); } export type CreateSessionGoalInput = { accountId: string; workspaceId: string; sessionId: string; text: string; successCriteria?: string | null; rootConstraints?: string[]; reportRequirements?: SessionGoalReportRequirement[]; maxAutoContinuations?: number | null; mutationPolicy?: SessionGoalMutationPolicy; expectedObjectiveRevision?: number; expectedGoalId?: string; changeKind?: SessionGoalChangeKind; changeRationale?: string; sourceProposalId?: string; rollbackOfRevisionId?: string; createdBy: SessionGoalCreatedBy; }; export async function createSessionGoal( db: Database, input: CreateSessionGoalInput, ): Promise { const rootConstraints = normalizeAndAssertSessionGoalRootConstraints(input.rootConstraints ?? []); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .insert(schema.sessionGoals) .values({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, text: input.text, successCriteria: input.successCriteria ?? null, rootConstraints, metadata: appendGoalReportRequirements({}, input.reportRequirements), maxAutoContinuations: input.maxAutoContinuations ?? null, mutationPolicy: input.mutationPolicy ?? "preserve_intent", createdBy: input.createdBy, }) .returning(); if (!row) { throw new Error("Failed to create session goal"); } return mapSessionGoal(row); }, ); } export async function getSessionGoal( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .limit(1); return row ? mapSessionGoal(row) : null; }); } /** Bounded MCP management facts. No config, goal metadata, or event payload is materialized. * The caller must authorize session.read first, just as for getSession/queue reads. */ export async function getSessionMcpMonitoringSummary( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (tx) => { const [goal] = await tx .select({ status: schema.sessionGoals.status, text: sql`left(${schema.sessionGoals.text}, 600)`, textOriginalChars: sql`char_length(${schema.sessionGoals.text})::integer`, evidence: sql`left(${schema.sessionGoals.evidence}, 2000)`, evidenceOriginalChars: sql< number | null >`char_length(${schema.sessionGoals.evidence})::integer`, rationale: sql`left(${schema.sessionGoals.rationale}, 600)`, rationaleOriginalChars: sql< number | null >`char_length(${schema.sessionGoals.rationale})::integer`, pausedReason: sql`left(${schema.sessionGoals.pausedReason}, 600)`, pausedReasonOriginalChars: sql< number | null >`char_length(${schema.sessionGoals.pausedReason})::integer`, }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .limit(1); const [progress] = await tx .select({ sequence: schema.sessionEvents.sequence, storedPrefix: sql< string | null >`left(${schema.sessionEvents.payload}->>'progressNote', ${SESSION_MCP_PROGRESS_STORAGE_CHARS})`, storedChars: sql< number | null >`char_length(${schema.sessionEvents.payload}->>'progressNote')::integer`, codecVersion: schema.sessionEvents.payloadCodecVersion, scalarIsEncoded: sessionMcpProgressScalarIsEncodedSql( sql`${schema.sessionEvents.payload}->>'progressNote'`, schema.sessionEvents.payloadCodecVersion, ), occurredAt: schema.sessionEvents.occurredAt, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.type, "goal.progress"), ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); const [wait] = await tx .select({ reason: schema.sessions.inputWaitReason, until: schema.sessions.inputWaitUntil, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return { goal: goal ? { ...goal, status: goal.status as SessionGoalStatus } : null, progress: progress ? { sequence: progress.sequence, ...projectSessionMcpProgressText( progress.storedPrefix, progress.storedChars, progress.codecVersion, progress.scalarIsEncoded, ), occurredAt: progress.occurredAt.toISOString(), } : null, wait: wait?.reason && wait.until ? { reason: wait.reason, until: wait.until.toISOString() } : null, }; }); } export type SessionGoalContinuationProjection = { state: "inactive" | "scheduled" | "running" | "blocked" | "invariant_broken"; 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" | "compaction_failed" | "missing_obligation"; wakeRevision: number; observedRevision: number; nextAttemptAt: string | null; lastError: string | null; /** The agent's stated `wait_for_input` reason while held; null otherwise. */ holdReason: string | null; }; /** * Read the goal and its autonomy state from one repeatable Postgres snapshot. * The projection never infers liveness from the public session status alone: * goal revisions, typed internal updates/turns, capacity waiters, admission * control, and the workflow-wake delivery ledger each remain distinct truth. */ export async function getSessionGoalWithContinuation( db: Database, workspaceId: string, sessionId: string, ): Promise<(SessionGoal & { continuation: SessionGoalContinuationProjection }) | null> { const context = await rlsContextForWorkspace(db, workspaceId); return await withRlsContext( db, context, async (tx) => { const effectiveControl = await evaluateSessionControl(tx, workspaceId, sessionId, { lock: "none", }); const [session] = await tx .select() .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); const [goal] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .limit(1); if (!session || !goal) return null; const [turn] = await tx .select({ id: schema.sessionTurns.id, status: schema.sessionTurns.status, source: schema.sessionTurns.source, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), inArray(schema.sessionTurns.status, [ "queued", "running", "requires_action", "recovering", "waiting_capacity", ]), ), ) .orderBy( // The active pointer is the authoritative current execution. A Send // accepted while a goal turn is running can have a lower normalized // queue position; that future human turn must not hide the live goal // attempt in this projection. sql`case when ${schema.sessionTurns.id} = ${session.activeTurnId} then 0 else 1 end`, asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt), ) .limit(1); const [continuationUpdate] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.kind, "goal_continuation"), eq(schema.sessionSystemUpdates.state, "pending"), sql`${schema.sessionSystemUpdates.payload} ->> 'goalId' = ${goal.id}`, sql`( jsonb_typeof(${schema.sessionSystemUpdates.payload} -> 'goalVersion') = 'number' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' ~ '^[1-9][0-9]*$' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' = ${goal.version.toString()} )`, ), ) .limit(1); // A shared-core waiter (any provider) for the same goal fence: the // only kind written after that provider's cutover. const coreCapacityWait = await readSubscriptionCoreWaiterInTransaction( tx as unknown as Database, { workspaceId, sessionId, }, ); const capacityWait = coreCapacityWait && coreCapacityWait.goalId === goal.id && coreCapacityWait.goalVersion === goal.version ? { nextCheckAt: coreCapacityWait.nextCheckAt } : undefined; const [wake] = await tx .select({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision, deliveredRevision: schema.sessionWorkflowWakeOutbox.deliveredRevision, reason: schema.sessionWorkflowWakeOutbox.reason, nextAttemptAt: schema.sessionWorkflowWakeOutbox.nextAttemptAt, lastError: schema.sessionWorkflowWakeOutbox.lastError, }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, sessionId), ), ) .limit(1); // The goal pill may project the session-level wait when this session also // has an active goal. The wait itself remains independent of goal state. const sessionWait = await sessionInputWaitStateTx(tx, workspaceId, sessionId, session); const currentWaitUntil = sessionWait.disposition === "held" ? session.inputWaitUntil : null; // With no turn in flight, a terminal checkpoint failure holds the input // that was already pending (including this goal's own continuation) until // something newer arrives. Say so rather than "continuing automatically". const heldByCompactionFailure = goal.status === "active" && !turn ? await sessionHeldByCompactionFailureTx( tx as unknown as Database, workspaceId, sessionId, ) : false; const pendingWorkflowWake = wake !== undefined && wake.wakeRevision > wake.deliveredRevision ? wake : null; const base = { wakeRevision: goal.continuationWakeRevision, observedRevision: goal.continuationObservedRevision, nextAttemptAt: capacityWait?.nextCheckAt.toISOString() ?? pendingWorkflowWake?.nextAttemptAt.toISOString() ?? null, // Delivery errors belong to one still-undelivered workflow-wake // revision. A late duplicate failure must not make already-accepted // Temporal work look blocked or broken. lastError: pendingWorkflowWake?.lastError ?? null, holdReason: null, }; let continuation: SessionGoalContinuationProjection; if (goal.status !== "active") { continuation = { state: "inactive", reason: "goal_inactive", ...base }; } else if (effectiveControl.state !== "active") { continuation = { state: "blocked", reason: "workstream_paused", ...base, }; } else if (session.status === "cancelled") { continuation = { state: "blocked", reason: "session_cancelled", ...base, }; } else if (capacityWait || turn?.status === "waiting_capacity") { continuation = { state: "blocked", reason: "provider_backpressure", ...base, }; } else if (turn?.status === "requires_action") { continuation = { state: "blocked", reason: "approval_required", ...base, }; } else if (turn && ["user", "api"].includes(turn.source)) { // Human/API work is authoritative, but it is not an autonomous goal // continuation. A live human turn blocks continuation; queued or // recovering human work is scheduled. Reserve `running` exclusively // for a live goal-owned attempt so clients never paint false pursuit. continuation = turn.status === "running" ? { state: "blocked", reason: "human_turn_running", ...base } : { state: "scheduled", reason: "human_work_pending", ...base }; } else if (turn?.source === "goal") { continuation = turn.status === "running" ? { state: "running", reason: "goal_turn_running", ...base } : { state: "scheduled", reason: "continuation_pending", ...base }; } else if (turn) { continuation = { state: turn.status === "running" ? "blocked" : "scheduled", reason: "system_work_pending", ...base, }; } else if (heldByCompactionFailure) { continuation = { state: "blocked", reason: "compaction_failed", ...base, }; } else if (continuationUpdate) { continuation = { state: "scheduled", reason: "continuation_pending", ...base, }; } else if (currentWaitUntil) { // The agent asked to wait for child results / external input. The // obligation stays armed (wake > observed) and the delayed workflow // wake fires at the deadline; this is a truthful blocked state, never // a broken invariant. continuation = { state: "blocked", reason: "held_for_input", ...base, nextAttemptAt: currentWaitUntil.toISOString(), holdReason: session.inputWaitReason ?? null, }; } else if ( goal.continuationWakeRevision > goal.continuationObservedRevision && pendingWorkflowWake?.reason === GOAL_IDLE_BACKOFF_WAKE_REASON ) { // Consecutive no-input continuations are paced: the obligation stays // armed (wake > observed) and the delayed workflow wake fires at // `nextAttemptAt`. Any new input pulls that wake to now. continuation = { state: "scheduled", reason: "backoff_pending", ...base, nextAttemptAt: pendingWorkflowWake.nextAttemptAt.toISOString(), }; } else if (goal.continuationWakeRevision > goal.continuationObservedRevision) { continuation = { state: "scheduled", reason: "wake_pending", ...base }; } else if (session.status === "queued") { continuation = { state: "scheduled", reason: "system_work_pending", ...base, }; } else { continuation = { state: "invariant_broken", reason: "missing_obligation", ...base, }; } return { ...mapSessionGoal(goal), continuation }; }, { isolationLevel: "repeatable read", accessMode: "read only" }, ); } export async function clearSessionGoal( db: Database, workspaceId: string, sessionId: string, options: { actor: "api" | "agent" } = { actor: "api" }, ): Promise<{ cleared: boolean; goal: SessionGoal | null; event: SessionEvent | null; }> { return await withWorkspaceSessionActivityRls( db, workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${sessionId}`); } const [existing] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .for("update") .limit(1); if (!existing) { return { cleared: false, goal: null, event: null }; } if ( existing.status !== "completed" && goalReportRequirements(existing.metadata).length > 0 ) { if (options.actor === "agent") { throw new SessionControlConflictError( "An agent cannot clear pending report requirements", ); } // Exact trusted API cancellation capability; never accepted from // caller JSON. Rolling writers cannot silently delete new reports. await tx.execute( sql`select set_config('opengeni.goal_report_clear_id', ${existing.id}, true)`, ); } await tx.delete(schema.sessionGoals).where(eq(schema.sessionGoals.id, existing.id)); const sequence = session.lastSequence + 1; const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: session.workspaceId, sessionId, sequence, type: "goal.cleared", payload: { goalId: existing.id, text: existing.text, version: existing.version, }, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to create system-update pending event"); await tx .update(schema.sessions) .set({ lastSequence: sequence, updatedAt: new Date() }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); if (!event) { throw new Error("Failed to append goal.cleared event"); } return { cleared: true, goal: mapSessionGoal(existing), event: mapEvent(event), }; }), ); } /** * goal_set semantics: insert, or replace the existing goal in place. A replace * re-activates the goal (even when paused or completed), bumps the version, * and resets the continuation counters — re-stating the objective re-arms the * auto-continuation budget. */ export async function upsertSessionGoal( db: Database, input: CreateSessionGoalInput, ): Promise<{ goal: SessionGoal; replaced: boolean }> { const suppliedRootConstraints = input.rootConstraints === undefined ? null : normalizeAndAssertSessionGoalRootConstraints(input.rootConstraints); assertSessionGoalFieldBytes(input.text, SESSION_GOAL_TEXT_MAX_BYTES, "goal text"); if (input.successCriteria !== null && input.successCriteria !== undefined) { assertSessionGoalFieldBytes( input.successCriteria, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, "goal success criteria", ); } if (input.changeRationale) { assertSessionGoalFieldBytes( input.changeRationale, SESSION_GOAL_RATIONALE_MAX_BYTES, "goal rationale", ); } return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [existing] = await scopedDb .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); if (!existing) { const [row] = await scopedDb .insert(schema.sessionGoals) .values({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, text: input.text, successCriteria: input.successCriteria ?? null, rootConstraints: suppliedRootConstraints ?? [], metadata: appendGoalReportRequirements({}, input.reportRequirements), maxAutoContinuations: input.maxAutoContinuations ?? null, mutationPolicy: input.mutationPolicy ?? "preserve_intent", createdBy: input.createdBy, }) .returning(); if (!row) { throw new Error("Failed to upsert session goal"); } return { goal: mapSessionGoal(row), replaced: false }; } if ( input.expectedObjectiveRevision !== undefined && existing.objectiveRevision !== input.expectedObjectiveRevision ) { throw new SessionControlConflictError( `goal objective revision changed: expected ${input.expectedObjectiveRevision}, current ${existing.objectiveRevision}`, ); } if (input.expectedGoalId !== undefined && existing.id !== input.expectedGoalId) { throw new SessionControlConflictError( `goal identity changed: expected ${input.expectedGoalId}, current ${existing.id}`, ); } const rootConstraints = suppliedRootConstraints ?? existing.rootConstraints; if (input.sourceProposalId) { const [proposal] = await scopedDb .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, input.workspaceId), eq(schema.sessionGoalRevisions.sessionId, input.sessionId), eq(schema.sessionGoalRevisions.id, input.sourceProposalId), ), ) .limit(1); if (!proposal || proposal.disposition !== "proposed" || proposal.goalId !== existing.id) { throw new SessionControlConflictError("goal rewrite proposal is not applicable"); } const [decision] = await scopedDb .select({ id: schema.sessionGoalRevisions.id }) .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, input.workspaceId), eq(schema.sessionGoalRevisions.proposalId, proposal.id), inArray(schema.sessionGoalRevisions.disposition, ["applied", "rejected"]), ), ) .limit(1); if (decision) { throw new SessionControlConflictError("goal rewrite proposal was already decided"); } if ( proposal.baseObjectiveRevision !== existing.objectiveRevision || proposal.baseObjectiveRevision !== input.expectedObjectiveRevision ) { throw new SessionControlConflictError( `goal rewrite proposal is stale: based on ${proposal.baseObjectiveRevision}, current ${existing.objectiveRevision}`, ); } if ( proposal.text !== input.text || proposal.successCriteria !== (input.successCriteria ?? null) || proposal.mutationPolicy !== (input.mutationPolicy ?? existing.mutationPolicy) || JSON.stringify(proposal.rootConstraints) !== JSON.stringify(rootConstraints) ) { throw new SessionControlConflictError( "goal rewrite proposal content changed before apply", ); } } if (input.rollbackOfRevisionId) { const [target] = await scopedDb .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, input.workspaceId), eq(schema.sessionGoalRevisions.sessionId, input.sessionId), eq(schema.sessionGoalRevisions.id, input.rollbackOfRevisionId), eq(schema.sessionGoalRevisions.goalId, existing.id), eq(schema.sessionGoalRevisions.disposition, "applied"), ), ) .limit(1); if (!target) { throw new SessionControlConflictError("goal revision is not an applied rollback target"); } if (target.resultObjectiveRevision === existing.objectiveRevision) { throw new SessionControlConflictError("goal revision is already current"); } if ( target.text === existing.text && target.successCriteria === existing.successCriteria && target.mutationPolicy === existing.mutationPolicy && JSON.stringify(target.rootConstraints) === JSON.stringify(existing.rootConstraints) ) { throw new SessionControlConflictError( "goal rollback target matches the current objective", ); } if ( target.text !== input.text || target.successCriteria !== (input.successCriteria ?? null) || target.mutationPolicy !== (input.mutationPolicy ?? existing.mutationPolicy) || JSON.stringify(target.rootConstraints) !== JSON.stringify(rootConstraints) ) { throw new SessionControlConflictError("goal rollback target content changed"); } } if (input.changeKind) { await scopedDb.execute( sql`select set_config('opengeni.goal_change_kind', ${input.changeKind}, true)`, ); } if (input.changeRationale) { await scopedDb.execute( sql`select set_config('opengeni.goal_change_rationale', ${input.changeRationale}, true)`, ); } if (input.sourceProposalId) { await scopedDb.execute( sql`select set_config('opengeni.goal_change_proposal_id', ${input.sourceProposalId}, true)`, ); } if (input.rollbackOfRevisionId) { await scopedDb.execute( sql`select set_config('opengeni.goal_change_rollback_of_revision_id', ${input.rollbackOfRevisionId}, true)`, ); } await scopedDb.execute( sql`select set_config('opengeni.goal_change_actor', ${input.createdBy === "scheduled_task" ? "scheduled_task" : input.createdBy === "agent" ? "agent" : "api"}, true)`, ); const [row] = await scopedDb .update(schema.sessionGoals) .set({ status: "active", text: input.text, successCriteria: input.successCriteria ?? null, rootConstraints, metadata: appendGoalReportRequirements( existing.status === "completed" ? { ...existing.metadata, [GOAL_REPORT_REQUIREMENTS_KEY]: [], reportDeliveriesV1: [] } : existing.metadata, input.reportRequirements, ), maxAutoContinuations: input.maxAutoContinuations ?? null, mutationPolicy: input.mutationPolicy ?? existing.mutationPolicy, evidence: null, rationale: null, pausedReason: null, createdBy: input.createdBy, version: existing.version + 1, autoContinuations: 0, noProgressStreak: 0, lastContinuationTurnId: null, versionAtLastContinuation: null, continuationWakeRevision: existing.continuationWakeRevision + 1, ...SESSION_GOAL_SUPPRESSION_CLEARED, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, existing.id)) .returning(); if (!row) { throw new Error("Failed to upsert session goal"); } return { goal: mapSessionGoal(row), replaced: true }; }, ); } /** * Re-arm one reusable scheduled goal exactly once per admitted run. The receipt, * goal mutation, and timeline fact share the canonical session lock transaction, * so crash recovery cannot reset counters or append goal.set twice. */ export async function upsertScheduledSessionGoalForRun( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; runId: string; text: string; successCriteria?: string | null; maxAutoContinuations?: number | null; mutationPolicy?: SessionGoalMutationPolicy; }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${input.sessionId}`); } const [run] = await tx .select({ sessionId: schema.scheduledTaskRuns.sessionId, status: schema.scheduledTaskRuns.status, acceptedExecutionSnapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.workspaceId, input.workspaceId), eq(schema.scheduledTaskRuns.id, input.runId), ), ) .for("update") .limit(1); if (!run || run.sessionId !== input.sessionId || run.status !== "queued") { throw new Error("scheduled reusable goal run binding changed"); } const accepted = ScheduledTaskRunAcceptedExecution.parse(run.acceptedExecutionSnapshot); const acceptedGoal = accepted.task.agentConfig.goal ?? null; if ( accepted.task.runMode !== "reusable_session" || !acceptedGoal || stableJson({ text: input.text, successCriteria: input.successCriteria ?? null, maxAutoContinuations: input.maxAutoContinuations ?? null, mutationPolicy: input.mutationPolicy ?? null, }) !== stableJson({ text: acceptedGoal.text, successCriteria: acceptedGoal.successCriteria ?? null, maxAutoContinuations: acceptedGoal.maxAutoContinuations ?? null, mutationPolicy: acceptedGoal.mutationPolicy ?? null, }) ) { throw new Error("scheduled reusable goal differs from accepted execution"); } const requestHash = createHash("sha256") .update( stableJson({ runId: input.runId, sessionId: input.sessionId, goal: acceptedGoal, }), ) .digest("hex"); const inserted = await tx .insert(schema.sessionCommandReceipts) .values({ accountId: input.accountId, workspaceId: input.workspaceId, actorType: "service", actorSubjectId: "scheduler", action: "scheduled.goal.reset", targetSessionId: input.sessionId, operationKey: input.runId, canonicalRequestHash: requestHash, result: { runId: input.runId }, }) .onConflictDoNothing() .returning({ id: schema.sessionCommandReceipts.id }); if (inserted.length === 0) return []; const result = await upsertSessionGoal(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, text: input.text, successCriteria: input.successCriteria ?? null, maxAutoContinuations: input.maxAutoContinuations ?? null, ...(input.mutationPolicy ? { mutationPolicy: input.mutationPolicy } : {}), ...(acceptedGoal.reportRequirements ? { reportRequirements: acceptedGoal.reportRequirements } : {}), createdBy: "scheduled_task", }); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "goal.set", payload: { goalId: result.goal.id, text: result.goal.text, ...(result.goal.successCriteria ? { successCriteria: result.goal.successCriteria } : {}), version: result.goal.version, actor: "scheduled_task", replaced: result.replaced, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append scheduled goal.set event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, input.sessionId)); return [mapEvent(event)]; }), ); } /** * Agent/API goal_set: session sequence ownership, the create-or-replace * mutation, and goal.set timeline fact commit together. The session-first lock * order matches active-turn event writes; goal_set must never hold a goal row * while waiting for the session sequence owner. */ export async function upsertSessionGoalWithEvent( db: Database, input: CreateSessionGoalInput & { actor: "agent" | "api"; commandActor?: Extract; }, ): Promise<{ goal: SessionGoal; replaced: boolean; workflowWakeRevision: number | null; events: SessionEvent[]; }> { assertSessionGoalFieldBytes(input.text, SESSION_GOAL_TEXT_MAX_BYTES, "goal text"); if (input.successCriteria !== null && input.successCriteria !== undefined) { assertSessionGoalFieldBytes( input.successCriteria, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, "goal success criteria", ); } if (input.changeRationale) { assertSessionGoalFieldBytes( input.changeRationale, SESSION_GOAL_RATIONALE_MAX_BYTES, "goal rationale", ); } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${input.sessionId}`); } if (input.actor === "agent") { if (input.commandActor) { await assertAgentCommandAuthorityInTransaction(tx, { workspaceId: input.workspaceId, actor: input.commandActor, targetSessionId: input.sessionId, action: "goal", }); } const [existing] = await tx .select({ objectiveRevision: schema.sessionGoals.objectiveRevision, status: schema.sessionGoals.status, rootConstraints: schema.sessionGoals.rootConstraints, }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); const requestedRootConstraints = input.rootConstraints === undefined ? null : normalizeAndAssertSessionGoalRootConstraints(input.rootConstraints); if ( requestedRootConstraints !== null && JSON.stringify(requestedRootConstraints) !== JSON.stringify(existing?.rootConstraints ?? []) ) { throw new SessionControlConflictError( "agent goal mutations cannot change root constraints", ); } if (existing && existing.status !== "completed") { throw new SessionControlConflictError( `agent goal_set cannot replace a goal while it is ${existing.status} at objective revision ${existing.objectiveRevision}; use goal_update to revise it`, ); } } const result = await upsertSessionGoal(tx, input); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "goal.set", payload: { goalId: result.goal.id, text: result.goal.text, ...(result.goal.successCriteria ? { successCriteria: result.goal.successCriteria } : {}), rootConstraints: result.goal.rootConstraints, reportRequirements: result.goal.reportRequirements, version: result.goal.version, objectiveRevision: result.goal.objectiveRevision, mutationPolicy: result.goal.mutationPolicy, actor: input.actor, replaced: result.replaced, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.set event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, input.sessionId)); const effectiveControl = await evaluateSessionControl( tx, input.workspaceId, input.sessionId, { lock: "none" }, ); const workflowWakeRevision = input.actor === "api" && session.status !== "cancelled" && session.activeTurnId === null && effectiveControl.state === "active" ? await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${input.sessionId}`, reason: result.replaced ? "goal_redirected" : "goal_set", }) : null; return { ...result, workflowWakeRevision, events: [mapEvent(event)] }; }), ); } function mapSessionGoalRevision( row: typeof schema.sessionGoalRevisions.$inferSelect, ): SessionGoalRevision { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, goalId: row.goalId, disposition: row.disposition, changeKind: row.changeKind, baseObjectiveRevision: row.baseObjectiveRevision, resultObjectiveRevision: row.resultObjectiveRevision, text: row.text, successCriteria: row.successCriteria, rootConstraints: row.rootConstraints, mutationPolicy: row.mutationPolicy, rationale: row.rationale, actor: row.actor, actorTurnId: row.actorTurnId, actorAttemptId: row.actorAttemptId, proposalId: row.proposalId, rollbackOfRevisionId: row.rollbackOfRevisionId, createdAt: row.createdAt.toISOString(), }; } export async function listSessionGoalRevisions( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, workspaceId), eq(schema.sessionGoalRevisions.sessionId, sessionId), ), ) .orderBy(desc(schema.sessionGoalRevisions.createdAt), desc(schema.sessionGoalRevisions.id)); return rows.map(mapSessionGoalRevision); }); } export async function listSessionGoalRevisionPage( db: Database, workspaceId: string, sessionId: string, options: { limit: number; before?: string } = { limit: 50 }, ): Promise<{ revisions: SessionGoalRevision[]; hasMore: boolean; nextCursor: string | null; }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const boundedLimit = Math.max(1, Math.min(100, Math.floor(options.limit))); const [anchor] = options.before ? await scopedDb .select({ id: schema.sessionGoalRevisions.id, createdAt: schema.sessionGoalRevisions.createdAt, }) .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, workspaceId), eq(schema.sessionGoalRevisions.sessionId, sessionId), eq(schema.sessionGoalRevisions.id, options.before), ), ) .limit(1) : []; if (options.before && !anchor) { throw new SessionControlConflictError("goal revision cursor is not visible in this session"); } const rows = await scopedDb .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, workspaceId), eq(schema.sessionGoalRevisions.sessionId, sessionId), ...(anchor ? [ or( lt(schema.sessionGoalRevisions.createdAt, anchor.createdAt), and( eq(schema.sessionGoalRevisions.createdAt, anchor.createdAt), lt(schema.sessionGoalRevisions.id, anchor.id), ), )!, ] : []), ), ) .orderBy(desc(schema.sessionGoalRevisions.createdAt), desc(schema.sessionGoalRevisions.id)) .limit(boundedLimit + 1); const hasMore = rows.length > boundedLimit; const revisions = rows.slice(0, boundedLimit).map(mapSessionGoalRevision); return { revisions, hasMore, nextCursor: hasMore ? (revisions.at(-1)?.id ?? null) : null, }; }); } export async function getSessionGoalRevision( db: Database, workspaceId: string, sessionId: string, revisionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, workspaceId), eq(schema.sessionGoalRevisions.sessionId, sessionId), eq(schema.sessionGoalRevisions.id, revisionId), ), ) .limit(1); return row ? mapSessionGoalRevision(row) : null; }); } export async function rejectSessionGoalRevisionWithEvent( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; revisionId: string; expectedObjectiveRevision: number; rationale: string; }, ): Promise<{ revision: SessionGoalRevision; events: SessionEvent[]; replay: boolean; }> { assertSessionGoalFieldBytes(input.rationale, SESSION_GOAL_RATIONALE_MAX_BYTES, "goal rationale"); return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${input.sessionId}`); } const [goal] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); if (!goal) throw new Error("this session has no goal"); const [proposal] = await tx .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, input.workspaceId), eq(schema.sessionGoalRevisions.sessionId, input.sessionId), eq(schema.sessionGoalRevisions.id, input.revisionId), ), ) .limit(1); if (!proposal || proposal.disposition !== "proposed" || proposal.goalId !== goal.id) { throw new SessionControlConflictError("goal rewrite proposal is not applicable"); } const [existingDecision] = await tx .select() .from(schema.sessionGoalRevisions) .where( and( eq(schema.sessionGoalRevisions.workspaceId, input.workspaceId), eq(schema.sessionGoalRevisions.proposalId, proposal.id), inArray(schema.sessionGoalRevisions.disposition, ["applied", "rejected"]), ), ) .limit(1); if (existingDecision?.disposition === "rejected") { return { revision: mapSessionGoalRevision(existingDecision), events: [], replay: true, }; } if (existingDecision) { throw new SessionControlConflictError("goal rewrite proposal was already applied"); } if ( goal.objectiveRevision !== input.expectedObjectiveRevision || proposal.baseObjectiveRevision !== input.expectedObjectiveRevision ) { throw new SessionControlConflictError( `goal rewrite proposal is stale: based on ${proposal.baseObjectiveRevision}, current ${goal.objectiveRevision}`, ); } const [decision] = await tx .insert(schema.sessionGoalRevisions) .values({ accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, goalId: goal.id, disposition: "rejected", changeKind: proposal.changeKind, baseObjectiveRevision: proposal.baseObjectiveRevision, resultObjectiveRevision: null, text: proposal.text, successCriteria: proposal.successCriteria, rootConstraints: proposal.rootConstraints, mutationPolicy: proposal.mutationPolicy, rationale: input.rationale, actor: "api", proposalId: proposal.id, }) .returning(); if (!decision) throw new Error("Failed to reject goal rewrite proposal"); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "goal.rewrite.rejected", payload: { goalId: goal.id, proposalId: proposal.id, decisionId: decision.id, objectiveRevision: goal.objectiveRevision, rationale: input.rationale, actor: "api", }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.rewrite.rejected event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, input.sessionId)); return { revision: mapSessionGoalRevision(decision), events: [mapEvent(event)], replay: false, }; }), ); } /** * Low-level semantic goal revision. The established lifecycle version still * advances so stale continuation updates are cancelled, while the migration * trigger advances the separate objective revision. A semantic rewrite does * not synthesize or consume another continuation. */ export async function updateSessionGoal( db: Database, workspaceId: string, sessionId: string, input: { text?: string; successCriteria?: string | null; mutationPolicy?: SessionGoalMutationPolicy; }, ): Promise { if (input.text !== undefined) { assertSessionGoalFieldBytes(input.text, SESSION_GOAL_TEXT_MAX_BYTES, "goal text"); } if (input.successCriteria !== null && input.successCriteria !== undefined) { assertSessionGoalFieldBytes( input.successCriteria, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, "goal success criteria", ); } return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .update(schema.sessionGoals) .set({ ...(input.text !== undefined ? { text: input.text } : {}), ...(input.successCriteria !== undefined ? { successCriteria: input.successCriteria } : {}), ...(input.mutationPolicy !== undefined ? { mutationPolicy: input.mutationPolicy } : {}), version: sql`${schema.sessionGoals.version} + 1`, ...SESSION_GOAL_SUPPRESSION_CLEARED, updatedAt: new Date(), }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .returning(); if (!row) { throw new Error(`Session goal not found: ${sessionId}`); } return mapSessionGoal(row); }); } /** * Agent goal_update: session sequence ownership, goal mutation, and its audit * event commit together. Locking the session before the goal also matches an * active turn's event-write order and avoids the workspace->session inversion * that previously self-locked root goal mutations. */ export async function updateSessionGoalWithEvent( db: Database, workspaceId: string, sessionId: string, input: { text?: string; successCriteria?: string | null; mutationPolicy?: SessionGoalMutationPolicy; /** @deprecated A semantic rewrite never counts as progress; use goal_progress. */ progressNote?: string; changeKind?: SessionGoalChangeKind; rationale?: string; expectedObjectiveRevision?: number; actor: "agent" | "api"; command?: { accountId: string; actor: Extract; operationKey: string; }; }, ): Promise<{ goal: SessionGoal; events: SessionEvent[]; operationId: string | null; replay: boolean; /** `unchanged`: the requested content already is the goal; nothing was written. */ outcome: "applied" | "proposed" | "unchanged"; proposalId: string | null; }> { if (input.text !== undefined) { assertSessionGoalFieldBytes(input.text, SESSION_GOAL_TEXT_MAX_BYTES, "goal text"); } if (input.successCriteria !== null && input.successCriteria !== undefined) { assertSessionGoalFieldBytes( input.successCriteria, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, "goal success criteria", ); } if (input.rationale) { assertSessionGoalFieldBytes( input.rationale, SESSION_GOAL_RATIONALE_MAX_BYTES, "goal rationale", ); } if (input.progressNote) { assertSessionGoalFieldBytes( input.progressNote, SESSION_GOAL_PROGRESS_MAX_BYTES, "goal progress note", ); } return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${sessionId}`); } const reserved = input.command ? await reserveSessionCommandReceipt(tx, { accountId: input.command.accountId, workspaceId, actor: input.command.actor, action: "goal.update", targetSessionId: sessionId, targetTurnId: null, operationKey: input.command.operationKey, canonicalRequestHash: canonicalSessionCommandHash({ text: input.text ?? null, successCriteria: input.successCriteria ?? null, mutationPolicy: input.mutationPolicy ?? null, progressNote: input.progressNote ?? null, changeKind: input.changeKind ?? null, rationale: input.rationale ?? null, expectedObjectiveRevision: input.expectedObjectiveRevision ?? null, }), identityScope: "target_operation", }) : null; if (reserved?.replay) { const parsed = SessionGoalContract.safeParse(reserved.receipt.result.goal); const goalVersion = reserved.receipt.result.goalVersion; const eventId = reserved.receipt.result.eventId; const outcome = reserved.receipt.result.outcome; // An unchanged update wrote no event, so its receipt holds none. if ( !parsed.success || !Number.isSafeInteger(goalVersion) || parsed.data.version !== goalVersion || (outcome === "unchanged" ? eventId !== null : typeof eventId !== "string") ) { throw new SessionControlInvariantError( `Goal update receipt ${reserved.receipt.id} has no valid committed result`, ); } return { goal: parsed.data, events: [], operationId: reserved.receipt.id, replay: true, outcome: outcome === "proposed" || outcome === "unchanged" ? outcome : "applied", proposalId: typeof reserved.receipt.result.proposalId === "string" ? reserved.receipt.result.proposalId : null, }; } if (input.command) { await assertAgentCommandAuthorityInTransaction(tx, { workspaceId, actor: input.command.actor, targetSessionId: sessionId, action: "goal", }); } const [existing] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .for("update") .limit(1); if (!existing) { throw new Error("this session has no goal; use goal_set first"); } if (existing.status === "completed") { throw new Error("session goal is completed; use goal_set to start a new goal"); } const contentSupplied = input.text !== undefined || input.successCriteria !== undefined || input.mutationPolicy !== undefined; if ( input.actor === "agent" && contentSupplied && (!input.changeKind || !input.rationale?.trim() || input.expectedObjectiveRevision === undefined) ) { throw new Error( "agent goal_update requires changeKind, rationale, and expectedObjectiveRevision for every semantic rewrite", ); } const changeKind = input.changeKind ?? "replacement"; const rationale = input.rationale?.trim() || "Direct goal revision"; const expectedObjectiveRevision = input.expectedObjectiveRevision ?? existing.objectiveRevision; if (existing.objectiveRevision !== expectedObjectiveRevision) { throw new SessionControlConflictError( `goal objective revision changed: expected ${expectedObjectiveRevision}, current ${existing.objectiveRevision}`, ); } const nextText = input.text ?? existing.text; const nextSuccessCriteria = input.successCriteria !== undefined ? input.successCriteria : existing.successCriteria; const nextMutationPolicy = input.mutationPolicy ?? existing.mutationPolicy; // The objective revision counts semantic changes, and the revision // trigger refuses to advance it for content that did not change. Content // equal to the current goal is therefore not a rewrite at all. const semanticChange = nextText !== existing.text || nextSuccessCriteria !== existing.successCriteria || nextMutationPolicy !== existing.mutationPolicy; if (!semanticChange && contentSupplied && !input.progressNote) { const goal = mapSessionGoal(existing); if (reserved) { await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { goal, goalVersion: goal.version, eventId: null, outcome: "unchanged" }, }); } return { goal, events: [], operationId: reserved?.receipt.id ?? null, replay: false, outcome: "unchanged", proposalId: null, }; } if (!semanticChange) { if (!input.progressNote) { throw new Error("goal_update requires semantic content or a progress note"); } const goal = mapSessionGoal(existing); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: input.command?.actor.turnId ?? null, turnGeneration: input.command?.actor.executionGeneration ?? null, turnAttemptId: input.command?.actor.attemptId ?? null, turnAssociation: input.command ? "current" : null, sequence: session.lastSequence + 1, type: "goal.progress", payload: { goalId: goal.id, objectiveRevision: goal.objectiveRevision, progressNote: input.progressNote, actor: input.actor, compatibilitySource: "goal.update", }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append compatibility goal.progress event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); if (reserved) { await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { goal, goalVersion: goal.version, eventId: event.id, outcome: "applied", }, }); } return { goal, events: [mapEvent(event)], operationId: reserved?.receipt.id ?? null, replay: false, outcome: "applied", proposalId: null, }; } const shouldApply = input.actor === "api" || existing.mutationPolicy !== "review_changes"; if (!shouldApply) { const [proposal] = await tx .insert(schema.sessionGoalRevisions) .values({ accountId: session.accountId, workspaceId, sessionId, goalId: existing.id, disposition: "proposed", changeKind, baseObjectiveRevision: existing.objectiveRevision, resultObjectiveRevision: null, text: nextText, successCriteria: nextSuccessCriteria, rootConstraints: existing.rootConstraints, mutationPolicy: nextMutationPolicy, rationale, actor: input.actor, actorTurnId: input.command?.actor.turnId ?? null, actorAttemptId: input.command?.actor.attemptId ?? null, }) .returning({ id: schema.sessionGoalRevisions.id }); if (!proposal) throw new Error("Failed to persist goal rewrite proposal"); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: input.command?.actor.turnId ?? null, turnGeneration: input.command?.actor.executionGeneration ?? null, turnAttemptId: input.command?.actor.attemptId ?? null, turnAssociation: input.command ? "current" : null, sequence: session.lastSequence + 1, type: "goal.rewrite.proposed", payload: { goalId: existing.id, proposalId: proposal.id, baseObjectiveRevision: existing.objectiveRevision, changeKind, rationale, actor: input.actor, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.rewrite.proposed event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); const goal = mapSessionGoal(existing); if (reserved) { await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { goal, goalVersion: goal.version, eventId: event.id, outcome: "proposed", proposalId: proposal.id, }, }); } return { goal, events: [mapEvent(event)], operationId: reserved?.receipt.id ?? null, replay: false, outcome: "proposed", proposalId: proposal.id, }; } await tx.execute(sql`select set_config('opengeni.goal_change_kind', ${changeKind}, true)`); await tx.execute( sql`select set_config('opengeni.goal_change_rationale', ${rationale}, true)`, ); await tx.execute(sql`select set_config('opengeni.goal_change_actor', ${input.actor}, true)`); if (input.command) { await tx.execute( sql`select set_config('opengeni.goal_change_turn_id', ${input.command.actor.turnId}, true)`, ); await tx.execute( sql`select set_config('opengeni.goal_change_attempt_id', ${input.command.actor.attemptId}, true)`, ); } const [updated] = await tx .update(schema.sessionGoals) .set({ ...(input.text !== undefined ? { text: input.text } : {}), ...(input.successCriteria !== undefined ? { successCriteria: input.successCriteria } : {}), ...(input.mutationPolicy !== undefined ? { mutationPolicy: input.mutationPolicy } : {}), version: existing.version + 1, objectiveRevision: existing.objectiveRevision + 1, ...SESSION_GOAL_SUPPRESSION_CLEARED, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, existing.id)) .returning(); if (!updated) throw new Error(`Session goal not found: ${sessionId}`); const goal = mapSessionGoal(updated); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: input.command?.actor.turnId ?? null, turnGeneration: input.command?.actor.executionGeneration ?? null, turnAttemptId: input.command?.actor.attemptId ?? null, turnAssociation: input.command ? "current" : null, sequence: session.lastSequence + 1, type: "goal.updated", payload: { goalId: goal.id, text: goal.text, ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}), rootConstraints: goal.rootConstraints, ...(input.progressNote ? { progressNote: input.progressNote } : {}), version: goal.version, objectiveRevision: goal.objectiveRevision, changeKind, rationale, actor: input.actor, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.updated event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); if (reserved) { await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { goal, goalVersion: goal.version, eventId: event.id, outcome: "applied", }, }); } return { goal, events: [mapEvent(event)], operationId: reserved?.receipt.id ?? null, replay: false, outcome: "applied", proposalId: null, }; }), ); } /** Maximum relative duration accepted by the session-level out-of-turn wait. */ export const SESSION_INPUT_WAIT_MIN_SECONDS = 30; export const SESSION_INPUT_WAIT_MAX_SECONDS = 7 * 24 * 60 * 60; export const SESSION_INPUT_WAIT_REASON_MAX_BYTES = 2 * 1024; /** * The database clock of the current transaction. Wait deadlines are compared * against this rather than a worker clock because the wake-outbox dispatcher * also claims rows on PostgreSQL now(). */ async function transactionNow(tx: Database): Promise { const rows = await rawRows<{ now: string | Date }>(tx, sql`select now() as now`); const value = rows[0]?.now; if (value === undefined) throw new Error("Failed to read the transaction clock"); return value instanceof Date ? value : new Date(value); } /** * Agent `wait_for_input`: persist one session-owned, self-only out-of-turn * wait. The exact declaring turn and absolute deadline are causal authority; * Temporal/NATS are replaceable wake hints. A replacement attempt replaying * the same target-scoped operation key receives the committed result. */ export async function waitForSessionInputWithEvent( db: Database, workspaceId: string, sessionId: string, input: { reason: string; timeoutSeconds: number; command: { accountId: string; actor: Extract; operationKey: string; }; }, ): Promise<{ events: SessionEvent[]; operationId: string; replay: boolean; waitTurnId: string; deadlineAt: string; }> { assertSessionGoalFieldBytes( input.reason, SESSION_INPUT_WAIT_REASON_MAX_BYTES, "session input wait reason", ); if (!input.reason.trim()) throw new Error("session input wait reason must not be empty"); if ( !Number.isInteger(input.timeoutSeconds) || input.timeoutSeconds < SESSION_INPUT_WAIT_MIN_SECONDS || input.timeoutSeconds > SESSION_INPUT_WAIT_MAX_SECONDS ) { throw new Error( `session input wait timeoutSeconds must be an integer between ${SESSION_INPUT_WAIT_MIN_SECONDS} and ${SESSION_INPUT_WAIT_MAX_SECONDS}`, ); } return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${sessionId}`); } const reserved = await reserveSessionCommandReceipt(tx, { accountId: input.command.accountId, workspaceId, actor: input.command.actor, action: "session.wait_for_input", targetSessionId: sessionId, targetTurnId: null, operationKey: input.command.operationKey, canonicalRequestHash: canonicalSessionCommandHash({ reason: input.reason, timeoutSeconds: input.timeoutSeconds, }), identityScope: "target_operation", }); if (reserved.replay) { const stored = reserved.receipt.result as Record | null; const waitTurnId = typeof stored?.["waitTurnId"] === "string" ? stored["waitTurnId"] : null; const deadlineAt = typeof stored?.["deadlineAt"] === "string" ? stored["deadlineAt"] : null; if (!waitTurnId || !deadlineAt) { throw new SessionControlInvariantError( `Session input wait receipt ${reserved.receipt.id} has no valid committed result`, ); } return { events: [], operationId: reserved.receipt.id, replay: true, waitTurnId, deadlineAt, }; } await assertAgentCommandAuthorityInTransaction(tx, { workspaceId, actor: input.command.actor, targetSessionId: sessionId, action: "wait", }); if (session.status === "cancelled") { throw new Error("cancelled sessions cannot wait for input"); } if (!session.temporalWorkflowId) { throw new SessionControlInvariantError( `Session ${sessionId} has no Temporal workflow identity`, ); } // The first wait owns the logical turn's deadline, not a renewable lease. // Fresh operation keys and recovered attempts retain its receipt facts. if (session.inputWaitTurnId === input.command.actor.turnId && session.inputWaitUntil) { const deadlineAt = session.inputWaitUntil.toISOString(); await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { waitTurnId: session.inputWaitTurnId, deadlineAt, reason: session.inputWaitReason, }, }); return { events: [], operationId: reserved.receipt.id, replay: false, waitTurnId: session.inputWaitTurnId, deadlineAt, }; } const now = await transactionNow(tx); const deadline = new Date(now.getTime() + input.timeoutSeconds * 1000); const deadlineAt = deadline.toISOString(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: input.command.actor.turnId, turnGeneration: input.command.actor.executionGeneration, turnAttemptId: input.command.actor.attemptId, turnAssociation: "current", sequence: session.lastSequence + 1, type: "session.wait.started", payload: { waitTurnId: input.command.actor.turnId, deadlineAt, reason: input.reason, actor: "agent", }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session.wait.started event"); await tx .update(schema.sessions) .set({ inputWaitTurnId: input.command.actor.turnId, inputWaitUntil: deadline, inputWaitReason: input.reason, inputWaitSetAt: now, lastSequence: session.lastSequence + 1, updatedAt: now, }) .where(eq(schema.sessions.id, sessionId)); await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: session.accountId, workspaceId, sessionId, temporalWorkflowId: session.temporalWorkflowId, reason: "session_input_wait_deadline", notBefore: deadline, }); await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { eventId: event.id, waitTurnId: input.command.actor.turnId, deadlineAt, reason: input.reason, }, }); return { events: [mapEvent(event)], operationId: reserved.receipt.id, replay: false, waitTurnId: input.command.actor.turnId, deadlineAt, }; }), ); } /** * Record execution progress without changing goal semantics or either goal * revision. The attempt-fenced operation receipt makes a recovered tool call * converge on the original event instead of manufacturing progress twice. */ export async function recordSessionGoalProgressWithEvent( db: Database, workspaceId: string, sessionId: string, input: { progressNote: string; reportRequirements?: SessionGoalReportRequirement[]; command: { accountId: string; actor: Extract; operationKey: string; }; }, ): Promise<{ goal: SessionGoal; events: SessionEvent[]; operationId: string; replay: boolean; }> { assertSessionGoalFieldBytes( input.progressNote, SESSION_GOAL_PROGRESS_MAX_BYTES, "goal progress note", ); return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => withSessionActivitySavepoint(scopedDb, async (tx) => { // Child-lifecycle prefix: the parent session is locked with the child so // the child_progress notice can be enqueued in this same commit. const locks = await lockChildLifecycleOutboxWriteRowsTx(tx, workspaceId, { sessionId }); const session = locks.session; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${sessionId}`); } const reserved = await reserveSessionCommandReceipt(tx, { accountId: input.command.accountId, workspaceId, actor: input.command.actor, action: "goal.progress", targetSessionId: sessionId, targetTurnId: null, operationKey: input.command.operationKey, canonicalRequestHash: canonicalSessionCommandHash({ progressNote: input.progressNote, ...(input.reportRequirements !== undefined ? { reportRequirements: input.reportRequirements } : {}), }), identityScope: "target_operation", }); if (reserved.replay) { const parsed = SessionGoalContract.safeParse(reserved.receipt.result.goal); if (!parsed.success) { throw new SessionControlInvariantError( `Goal progress receipt ${reserved.receipt.id} has no valid committed result`, ); } return { goal: parsed.data, events: [], operationId: reserved.receipt.id, replay: true, }; } await assertAgentCommandAuthorityInTransaction(tx, { workspaceId, actor: input.command.actor, targetSessionId: sessionId, action: "goal", }); const [existing] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .for("update") .limit(1); if (!existing) throw new Error("this session has no goal; use goal_set first"); if (existing.status !== "active") { throw new Error("session goal is not active; progress cannot be recorded"); } const metadata = appendGoalReportRequirements(existing.metadata, input.reportRequirements); if (input.reportRequirements !== undefined) { await tx .update(schema.sessionGoals) .set({ metadata }) .where(eq(schema.sessionGoals.id, existing.id)); } const goal = mapSessionGoal({ ...existing, metadata }); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: input.command.actor.turnId, turnGeneration: input.command.actor.executionGeneration, turnAttemptId: input.command.actor.attemptId, turnAssociation: "current", sequence: session.lastSequence + 1, type: "goal.progress", payload: { goalId: goal.id, objectiveRevision: goal.objectiveRevision, progressNote: input.progressNote, ...(input.reportRequirements !== undefined ? { reportRequirements: input.reportRequirements } : {}), actor: "agent", }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.progress event"); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); await enqueueChildProgressOutboxTx(tx, workspaceId, session, { goalId: goal.id, objectiveRevision: goal.objectiveRevision, operationId: reserved.receipt.id, progressNote: input.progressNote, }); await updateSessionCommandReceiptResult(tx, reserved.receipt.id, { result: { goal, eventId: event.id }, }); return { goal, events: [mapEvent(event)], operationId: reserved.receipt.id, replay: false, }; }), ); } /** * Low-level row-only session-title update used by database-specific callers and * tests. Public product writers should use `updateSessionTitleWithEvent` so the * observable event commits atomically with this state transition. The clobber * guard lives entirely in this single atomic UPDATE: a user-set title is * permanent, so agent/auto writes * are first normalized through the shared short/sensitive-safe automatic-title * policy, then carry an `AND title_source IS DISTINCT FROM 'user'` guard * (NULL-safe in Postgres) while user writes are unconditional. Automatic * writes also bind the exact normalized candidate to a transaction-local * database capability, so a pre-policy binary cannot bypass normalization * during a rolling deployment. Never read-modify-write. * * `expectedCurrent`, when supplied, is an additional NULL-safe compare-and-set * fence. It is used by stale/retry-prone producers such as scheduled dispatch: * the write succeeds only if both the durable title and source still match. * Re-applying the exact title is also a no-op so a confused agent cannot churn * `updated_at` every turn. Returns `{ updated, title }`: `updated` is false when * the value was unchanged or an agent write was skipped because a user title * already pinned the session; `title` is always the resulting stored title when * the session exists. */ export async function updateSessionTitle( db: Database, input: { workspaceId: string; sessionId: string; title: string; source: "user" | "agent"; expectedCurrent?: { title: string | null; source: "user" | "agent" | null; }; }, ): Promise<{ updated: boolean; title: string | null }> { return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => { const title = input.source === "agent" ? normalizeAutomaticSessionTitle(input.title) : input.title; if (title === null) { const [existing] = await scopedDb .select({ title: schema.sessions.title }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); return { updated: false, title: existing?.title ?? null }; } if (input.source === "agent") { await scopedDb.execute( sql`select pg_catalog.set_config('opengeni.automatic_session_title_v1_candidate', ${title}, true)`, ); } const [row] = await scopedDb .update(schema.sessions) .set({ title, titleSource: input.source, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), sql`${schema.sessions.title} is distinct from ${title}`, ...(input.source === "agent" ? [sql`${schema.sessions.titleSource} is distinct from 'user'`] : []), ...(input.expectedCurrent ? [ sql`${schema.sessions.title} is not distinct from ${input.expectedCurrent.title}`, sql`${schema.sessions.titleSource} is not distinct from ${input.expectedCurrent.source}`, ] : []), ), ) .returning({ title: schema.sessions.title }); if (row) { return { updated: true, title: row.title }; } const [existing] = await scopedDb .select({ title: schema.sessions.title }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); return { updated: false, title: existing?.title ?? null }; }); } /** * Atomically set a session title and append its public `session.title_set` * event under the canonical workspace/session event-write lock. The row CAS, * durable sequence, and event either all commit or all roll back, so a newer * title writer can never commit between the authoritative update and an older * event append. * * Exact retries are naturally idempotent: the unchanged-title predicate (and, * for stale producers, `expectedCurrent`) makes a committed retry a no-op with * no duplicate event. Automatic titles retain the rolling-deployment trigger's * exact transaction-local candidate capability. */ export async function updateSessionTitleWithEvent( db: Database, input: { workspaceId: string; sessionId: string; title: string; source: "user" | "agent"; expectedCurrent?: { title: string | null; source: "user" | "agent" | null; }; }, ): Promise<{ updated: boolean; title: string | null; events: SessionEvent[] }> { const title = input.source === "agent" ? normalizeAutomaticSessionTitle(input.title) : input.title; return await retryWorkspaceSessionEventActivityPersistence( db, input.workspaceId, true, { stage: "session_title.update_with_event", eventTypes: ["session.title_set"], maxAttempts: 3, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session) return { updated: false, title: null, events: [] }; if (title === null) { return { updated: false, title: session.title, events: [] }; } if (input.source === "agent") { await tx.execute( sql`select pg_catalog.set_config('opengeni.automatic_session_title_v1_candidate', ${title}, true)`, ); } const now = new Date(); const sequence = session.lastSequence + 1; const [updated] = await tx .update(schema.sessions) .set({ title, titleSource: input.source, lastSequence: sequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), sql`${schema.sessions.title} is distinct from ${title}`, ...(input.source === "agent" ? [sql`${schema.sessions.titleSource} is distinct from 'user'`] : []), ...(input.expectedCurrent ? [ sql`${schema.sessions.title} is not distinct from ${input.expectedCurrent.title}`, sql`${schema.sessions.titleSource} is not distinct from ${input.expectedCurrent.source}`, ] : []), ), ) .returning({ title: schema.sessions.title }); if (!updated) { return { updated: false, title: session.title, events: [] }; } const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence, type: "session.title_set", payload: { title: updated.title ?? title, source: input.source, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session.title_set event"); return { updated: true, title: updated.title, events: [mapEvent(event)], }; }), ); } /** A stored avatar, or null for one this version cannot read. */ export function storedSessionAvatar(value: unknown): SessionAvatar | null { if (value === null || value === undefined) return null; const parsed = SessionAvatarSchema.safeParse(value); return parsed.success ? parsed.data : null; } /** * A chat's name and avatar, as a bot shows itself outside the console (its * Slack posts). Null when the chat does not exist in this workspace. */ export async function getSessionBotIdentity( db: Database, workspaceId: string, sessionId: string, ): Promise<{ title: string | null; avatar: SessionAvatar | null } | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ title: schema.sessions.title, avatar: schema.sessions.avatar }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!row) return null; return { title: row.title?.trim() || null, avatar: storedSessionAvatar(row.avatar) }; }); } /** * Set a chat's description and/or avatar (display metadata) and append its * public `session.profile_set` event under the canonical session event-write * lock, like {@link updateSessionTitleWithEvent}. Only the named fields change; * null clears one. Writing the values it already has is a no-op with no event. */ export async function updateSessionProfileWithEvent( db: Database, input: { workspaceId: string; sessionId: string; description?: string | null; avatar?: SessionAvatar | null; source: "user" | "agent"; }, ): Promise<{ updated: boolean; description: string | null; avatar: SessionAvatar | null; events: SessionEvent[]; }> { return await retryWorkspaceSessionEventActivityPersistence( db, input.workspaceId, true, { stage: "session_profile.update_with_event", eventTypes: ["session.profile_set"], maxAttempts: 3, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session) return { updated: false, description: null, avatar: null, events: [] }; const [current] = await tx .select({ description: schema.sessions.description, avatar: schema.sessions.avatar, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); const currentDescription = current?.description ?? null; const currentAvatar = storedSessionAvatar(current?.avatar); const description = input.description !== undefined ? input.description : currentDescription; const avatar = input.avatar !== undefined ? input.avatar : currentAvatar; if ( description === currentDescription && JSON.stringify(avatar) === JSON.stringify(currentAvatar) ) { return { updated: false, description, avatar, events: [] }; } const now = new Date(); const sequence = session.lastSequence + 1; await tx .update(schema.sessions) .set({ description, avatar, lastSequence: sequence, updatedAt: now }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence, type: "session.profile_set", payload: { description, avatar, source: input.source }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session.profile_set event"); return { updated: true, description, avatar, events: [mapEvent(event)] }; }), ); } /** A stored link list, or empty when absent or unreadable. */ export function storedSessionLinks(value: unknown): SessionLink[] { const parsed = SessionLinkListSchema.safeParse(value ?? []); if (parsed.success) return parsed.data; // Keep every valid link: one bad entry must not empty the list on the next write. if (!Array.isArray(value)) return []; return value .flatMap((entry) => { const link = SessionLinkSchema.safeParse(entry); return link.success ? [link.data] : []; }) .slice(0, SESSION_LINKS_MAX); } /** The chat's Linked items, in the caller's RLS scope. Null when the chat is not visible. */ export async function getSessionLinks( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ links: schema.sessions.links }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return row ? storedSessionLinks(row.links) : null; }); } /** * Change a chat's Linked items or who it waits on, and append the matching * public event under the canonical session event-write lock, like * {@link updateSessionProfileWithEvent}. `change` sees the current values and * returns the new ones, or null for no change (no event). */ export async function updateSessionCoordinationWithEvent( db: Database, input: { workspaceId: string; sessionId: string; change: (current: { links: SessionLink[]; waitingOn: (SessionWaitingOn & { turnId: string | null }) | null; }) => | { kind: "links"; links: SessionLink[] } | { kind: "waiting_on"; waitingOn: (SessionWaitingOn & { turnId: string | null }) | null } | null; }, ): Promise<{ updated: boolean; links: SessionLink[]; events: SessionEvent[] } | null> { return await retryWorkspaceSessionEventActivityPersistence( db, input.workspaceId, true, { stage: "session_coordination.update_with_event", eventTypes: ["session.links.changed", "session.waiting_on.changed"], maxAttempts: 3, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session) return null; const [current] = await tx .select({ links: schema.sessions.links, waitingOn: schema.sessions.waitingOn }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); const links = storedSessionLinks(current?.links); const storedWaiting = current?.waitingOn ?? null; const waitingParsed = storedWaiting ? SessionWaitingOnSchema.safeParse(storedWaiting) : null; const waitingOn = storedWaiting && waitingParsed?.success ? { ...waitingParsed.data, turnId: storedWaiting.turnId ?? null } : null; const next = input.change({ links, waitingOn }); if (!next) return { updated: false, links, events: [] }; const now = new Date(); const sequence = session.lastSequence + 1; const values = next.kind === "links" ? { links: SessionLinkListSchema.parse(next.links) } : { waitingOn: next.waitingOn }; await tx .update(schema.sessions) .set({ ...values, lastSequence: sequence, updatedAt: now }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); const payload = next.kind === "links" ? { links: next.links } : { waitingOn: next.waitingOn ? (({ turnId: _turnId, ...rest }) => rest)(next.waitingOn) : null, }; const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence, type: next.kind === "links" ? "session.links.changed" : "session.waiting_on.changed", payload, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session coordination event"); return { updated: true, links: next.kind === "links" ? next.links : links, events: [mapEvent(event)], }; }), ); } /** Read-only admission at a locked paused-to-active transition. */ export type SessionGoalResumeValidation = ( tx: Database, session: Pick< Session, "id" | "accountId" | "workspaceId" | "model" | "codexCompactionMode" | "latencyMode" >, causalTurn: { id: string; initiatingHumanSubjectId: string | null } | null, ) => Promise; /** * Status transition helper. Idempotent: requesting the current status returns * `changed: false` so callers can skip emitting a duplicate event. `completed` * is terminal for transitions; only `upsertSessionGoal` can replace a * completed goal. Resuming to `active` clears the pause fields and resets the * continuation counters. */ export async function setSessionGoalStatus( db: Database, workspaceId: string, sessionId: string, input: { status: SessionGoalStatus; evidence?: string; rationale?: string; pausedReason?: string; reportDeliveries?: SessionGoalReportDelivery[]; reportArtifactActor?: ReportArtifactActor; commandActor?: Extract; /** Runs under the canonical control/session/goal locks, before a paused goal changes. */ beforeResume?: SessionGoalResumeValidation; }, ): Promise<{ goal: SessionGoal; changed: boolean; workflowWakeRevision: number | null; }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const effectiveControl = await evaluateSessionControl(scopedDb, workspaceId, sessionId, { lock: "share", }); const [session] = await scopedDb .select() .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .for("no key update") .limit(1); if (!session) throw new Error(`Session not found: ${sessionId}`); if (input.commandActor) { await assertAgentCommandAuthorityInTransaction(scopedDb, { workspaceId, actor: input.commandActor, targetSessionId: sessionId, action: "goal", }); } const [existing] = await scopedDb .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .for("update") .limit(1); if (!existing) { throw new Error(`Session goal not found: ${sessionId}`); } if (existing.status === input.status) { return { goal: mapSessionGoal(existing), changed: false, workflowWakeRevision: null, }; } if (existing.status === "completed") { throw new Error("session goal is completed; set a new goal to continue"); } if (input.status === "active" && input.beforeResume) { const [effectiveSession] = await withEffectiveSessionPolicy(scopedDb, workspaceId, [session]); // An accepted running turn owns the work the goal will continue after it // settles. An idle Resume uses the exact latest-finished causal row. const causalTurnFilter = session.activeTurnId ? or( eq(schema.sessionTurns.id, session.activeTurnId), sql`${schema.sessionTurns.finishedAt} is not null`, ) : sql`${schema.sessionTurns.finishedAt} is not null`; const [causalTurn] = await scopedDb .select({ id: schema.sessionTurns.id, initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), causalTurnFilter, ), ) .orderBy( ...(session.activeTurnId ? [desc(sql`${schema.sessionTurns.id} = ${session.activeTurnId}`)] : []), desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), desc(schema.sessionTurns.id), ) .limit(1); await input.beforeResume( scopedDb, { id: sessionId, accountId: session.accountId, workspaceId, model: effectiveSession!.model, latencyMode: effectiveSession!.latencyMode as Session["latencyMode"], codexCompactionMode: session.codexCompactionMode as Session["codexCompactionMode"], }, causalTurn ?? null, ); } if (input.status === "completed") { await verifyGoalReportDeliveries(scopedDb, { accountId: session.accountId, workspaceId, sessionId, metadata: existing.metadata, deliveries: input.reportDeliveries, ...(input.reportArtifactActor ? { actor: input.reportArtifactActor } : {}), }); } const [row] = await scopedDb .update(schema.sessionGoals) .set({ status: input.status, version: existing.version + 1, updatedAt: new Date(), ...SESSION_GOAL_SUPPRESSION_CLEARED, ...(input.status === "completed" ? { evidence: input.evidence ?? null, metadata: { ...existing.metadata, reportDeliveriesV1: input.reportDeliveries ?? [] }, pausedReason: null, continuationObservedRevision: existing.continuationWakeRevision, } : {}), ...(input.status === "paused" ? { rationale: input.rationale ?? null, pausedReason: input.pausedReason ?? null, continuationObservedRevision: existing.continuationWakeRevision, } : {}), ...(input.status === "active" ? { rationale: null, pausedReason: null, // A re-armed goal starts a fresh continuation epoch; stale pointers to // a pre-pause continuation turn must not affect later lineage. ...SESSION_GOAL_CONTINUATION_EPOCH_RESET, continuationWakeRevision: existing.continuationWakeRevision + 1, } : {}), }) .where(eq(schema.sessionGoals.id, existing.id)) .returning(); if (!row) { throw new Error(`Session goal not found: ${sessionId}`); } let workflowWakeRevision: number | null = null; if ( input.status === "active" && session.status !== "cancelled" && session.activeTurnId === null && effectiveControl.state === "active" ) { workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction(scopedDb, { accountId: session.accountId, workspaceId, sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${sessionId}`, reason: "goal_resumed", }); } return { goal: mapSessionGoal(row), changed: true, workflowWakeRevision }; }); } export type SetSessionGoalStatusEvent = | { type: "goal.completed"; evidence: string } | { type: "goal.paused"; actor: "agent" | "api"; reason: string; rationale?: string; } // Operator PATCH or agent tool resume. A system resume of a `max_auto_continuations` // pause is a separate path (`autoResumeGoalPausedByCapInTransaction`) that // commits with the external input that caused it. | { type: "goal.resumed"; actor: "api" | "agent" }; /** Status mutation and its timeline fact share the same session-first commit. */ export async function setSessionGoalStatusWithEvent( db: Database, workspaceId: string, sessionId: string, input: { status: SessionGoalStatus; evidence?: string; rationale?: string; pausedReason?: string; reportDeliveries?: SessionGoalReportDelivery[]; reportArtifactActor?: ReportArtifactActor; commandActor?: Extract; beforeResume?: SessionGoalResumeValidation; event: SetSessionGoalStatusEvent; }, ): Promise<{ goal: SessionGoal; changed: boolean; workflowWakeRevision: number | null; events: SessionEvent[]; }> { if (input.rationale) { assertSessionGoalFieldBytes( input.rationale, SESSION_GOAL_RATIONALE_MAX_BYTES, "goal rationale", ); } return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${sessionId}`); } const result = await setSessionGoalStatus(tx, workspaceId, sessionId, { status: input.status, ...(input.reportDeliveries !== undefined ? { reportDeliveries: input.reportDeliveries } : {}), ...(input.reportArtifactActor ? { reportArtifactActor: input.reportArtifactActor } : {}), ...(input.commandActor ? { commandActor: input.commandActor } : {}), ...(input.beforeResume ? { beforeResume: input.beforeResume } : {}), ...(input.evidence !== undefined ? { evidence: input.evidence } : {}), ...(input.rationale !== undefined ? { rationale: input.rationale } : {}), ...(input.pausedReason !== undefined ? { pausedReason: input.pausedReason } : {}), }); if (!result.changed) return { ...result, events: [] }; const payload = input.event.type === "goal.completed" ? { goalId: result.goal.id, evidence: input.event.evidence, reportDeliveries: result.goal.metadata.reportDeliveriesV1 ?? [], version: result.goal.version, } : input.event.type === "goal.paused" ? { goalId: result.goal.id, actor: input.event.actor, reason: input.event.reason, ...(input.event.rationale ? { rationale: input.event.rationale } : {}), autoContinuations: result.goal.autoContinuations, noProgressStreak: result.goal.noProgressStreak, } : { goalId: result.goal.id, text: result.goal.text, ...(result.goal.successCriteria ? { successCriteria: result.goal.successCriteria } : {}), version: result.goal.version, objectiveRevision: result.goal.objectiveRevision, mutationPolicy: result.goal.mutationPolicy, actor: input.event.actor, reason: "api", }; const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, sequence: session.lastSequence + 1, type: input.event.type, payload: payload, ...(input.commandActor ? { turnId: input.commandActor.turnId, turnGeneration: input.commandActor.executionGeneration, turnAttemptId: input.commandActor.attemptId, turnAssociation: "current", } : {}), occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error(`Failed to append ${input.event.type} event`); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); return { ...result, events: [mapEvent(event)] }; }), ); } export async function setSessionGoalLastContinuationTurn( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { await withWorkspaceRls(db, workspaceId, async (scopedDb) => { await scopedDb .update(schema.sessionGoals) .set({ lastContinuationTurnId: turnId, updatedAt: new Date(), }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ); }); } export type GoalContinuationDecision = | { decision: "none" } | { decision: "queue" } | { decision: "paused"; reason: "max_auto_continuations" | "limits" | GoalAdmissionPausedReason; goal: SessionGoal; } | { decision: "continue"; goal: SessionGoal; autoContinuation: number; cap: number | null; }; async function turnHasFailureCodeTx( tx: Database, workspaceId: string, sessionId: string, turnId: string, code: string, ): Promise { const [failure] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.turnId, turnId), eq(schema.sessionEvents.type, "turn.failed"), sql`${schema.sessionEvents.payload} ->> 'code' = ${code}`, ), ) .limit(1); return Boolean(failure); } /** * Core continuation decision, taken in one transaction with the goal row * locked. Queued work always wins; any non-terminal turn (queued, running, or * requires_action awaiting a human approval) blocks auto-continuation. The * optional max-continuation guard mutates its counter here only, so a replaying * workflow re-reads recorded activity results and never recomputes it. */ export async function evaluateGoalContinuation( db: Database, input: { workspaceId: string; sessionId: string; // Optional: when absent (the default posture) goals are uncapped and length // is governed by explicit completion/pause and budget guards. defaultMaxAutoContinuations?: number | null; // Caller-computed billing/limits block reason. Applied inside the locked // decision (before the counter bump) so a budget pause never consumes // continuation budget. budgetBlocked?: string | null; budgetPausedReason?: "limits" | GoalAdmissionPausedReason | undefined; }, ): Promise { return await withWorkspaceRls( db, input.workspaceId, async (scopedDb) => await scopedDb.transaction(async (tx) => { const effectiveControl = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { lock: "share" }, ); const [session] = await tx .select({ id: schema.sessions.id, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("no key update") .limit(1); const [row] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); if (!session || effectiveControl.state !== "active") { return { decision: "none" } as const; } if (!row || row.status !== "active") { return { decision: "none" } as const; } // A message waiting for the personal machine's owner is not queued // work: the owner's goal keeps going beside it. const machineOwner = await sessionMachineOwnerSubject(tx, { accountId: null, workspaceId: input.workspaceId, sessionId: input.sessionId, }); const [pendingTurn] = await tx .select({ id: schema.sessionTurns.id, status: schema.sessionTurns.status, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), inArray(schema.sessionTurns.status, ["queued", "running", "requires_action"]), notWaitingForMachineOwnerSql(machineOwner), ), ) .limit(1); if (pendingTurn) { // "queue" tells the workflow to claim immediately; running/requires_action // turns (e.g. a pending approval on a restarted workflow) must not be // bypassed by a continuation, so they decline instead. return pendingTurn.status === "queued" ? ({ decision: "queue" } as const) : ({ decision: "none" } as const); } // Newest finished truth by finish time. Queue position alone is not // enough: a human prompt queued after internal turns takes a low // normalized position, yet it is the newer external input that must // restart the no-input streak. const [latestFinished] = await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), sql`${schema.sessionTurns.finishedAt} is not null`, ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), desc(schema.sessionTurns.id), ) .limit(1); const contextCompactionFailure = latestFinished ? await turnHasFailureCodeTx( tx as unknown as Database, input.workspaceId, input.sessionId, latestFinished.id, "context_compaction_failed", ) : false; const codexFailoverExhausted = row.continuationSuppressedTurnId !== null && row.continuationSuppressedTurnId === latestFinished?.id; // Some terminal failures make unchanged autonomous input unsafe: // checkpoint failure would repeat the same inference without durable // state, while bounded Codex failover exhaustion would create a fresh // turn and reset the per-turn account budget. Keep the active goal // intact but inert until newer human/API/machine work creates truth. // This never creates queue work or consumes continuation counters. if (contextCompactionFailure || codexFailoverExhausted) { return { decision: "none" } as const; } // `autoContinuations` counts only CONSECUTIVE synthesized continuations // that consumed no external input. The claim transaction already resets // it when a goal-owned turn's batch coalesced any other machine input, // and a Steer supersession resets it too; this branch covers a // human/API/scheduled turn that finished after the last continuation. let autoContinuations = row.autoContinuations; // A 429-failover continuation (the last continuation turn carried the `rotated` // marker) is a multi-account rotate, not another unit of goal work. It must not burn // the auto-continuation budget while walking accounts, matching the budget-pause rule. let rotatedFailover = false; if (row.lastContinuationTurnId) { const lastFinished = latestFinished; if (lastFinished && lastFinished.id !== row.lastContinuationTurnId) { // A user/scheduled turn ran since the last continuation: that // external input starts a fresh no-input streak. autoContinuations = 0; } else if (lastFinished) { const [{ rotatedFailures } = { rotatedFailures: 0 }] = await tx .select({ rotatedFailures: sql`count(*)::int`, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.turnId, row.lastContinuationTurnId), eq(schema.sessionEvents.type, "turn.failed"), sql`${schema.sessionEvents.payload} ->> 'rotated' = 'true'`, ), ); rotatedFailover = Number(rotatedFailures) > 0; } } // No configured default means uncapped. When a default is configured it // is a hard ceiling; per-goal overrides can only lower it. The ceiling // bounds consecutive no-input continuations only: any later external // input (machine input, human/API prompt, Steer) resumes this pause // automatically through `autoResumeGoalPausedByCapInTransaction`. const capCandidates = [row.maxAutoContinuations, input.defaultMaxAutoContinuations].filter( (value): value is number => typeof value === "number", ); const cap = capCandidates.length > 0 ? Math.min(...capCandidates) : null; if (cap !== null && autoContinuations >= cap) { const [paused] = await tx .update(schema.sessionGoals) .set({ status: "paused", pausedReason: SESSION_GOAL_CAP_PAUSED_REASON, autoContinuations, noProgressStreak: 0, version: row.version + 1, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, row.id)) .returning(); return { decision: "paused", reason: "max_auto_continuations", goal: mapSessionGoal(paused!), } as const; } if (input.budgetBlocked) { // Budget exhaustion pauses the goal visibly without bumping the // continuation counter — no turn is synthesized for this pass. const [paused] = await tx .update(schema.sessionGoals) .set({ status: "paused", pausedReason: input.budgetPausedReason ?? "limits", rationale: input.budgetBlocked, autoContinuations, noProgressStreak: 0, version: row.version + 1, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, row.id)) .returning(); return { decision: "paused", reason: input.budgetPausedReason ?? "limits", goal: mapSessionGoal(paused!), } as const; } // Freeze the counter on a rotation failover (invariant: a rotation walk never // consumes continuation budget); a normal continuation increments as before. const nextAutoContinuations = autoContinuations + (rotatedFailover ? 0 : 1); const [updated] = await tx .update(schema.sessionGoals) .set({ autoContinuations: nextAutoContinuations, noProgressStreak: 0, versionAtLastContinuation: row.version, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, row.id)) .returning(); return { decision: "continue", goal: mapSessionGoal(updated!), autoContinuation: nextAutoContinuations, cap, } as const; }), ); } export const GOAL_IDLE_BACKOFF_WAKE_REASON = "goal_idle_backoff"; /** * Pacing between consecutive no-input goal continuations. `scheduleMs[n - 1]` * (last entry repeats) is the delay before the n-th consecutive continuation, * measured from when the previous continuation turn finished; `maxMs` bounds * every delay. Omitted/null means no backoff (the legacy immediate behavior). */ export type GoalIdleBackoffPolicy = { scheduleMs: readonly number[]; maxMs: number; }; export type MaterializeGoalContinuationResult = | { action: "none" | "queue"; events: [] } // Idle backoff: the previous continuation consumed no external input and // finished less than its pacing delay ago. Nothing was materialized, the // wake/observed ledger is untouched, and a delayed workflow wake is armed at // `notBefore`; any new input pulls that wake to now. | { action: "deferred"; events: []; notBefore: Date } | { action: "paused"; events: SessionEvent[] } | { action: "continue"; events: SessionEvent[]; update: SessionSystemUpdate; goalWakeRevision: number; workflowWakeRevision: number; }; /** * Consume one durable goal-wake revision into one continuation obligation. * * This is deliberately one outer PostgreSQL transaction. The existing locked * evaluator runs as a nested savepoint, so its counter mutation is * rolled back if prompt construction, update/event insertion, metering, or the * workflow-wake outbox write fails. Retrying after a lost COMMIT response sees * the same stable goal revision and the already-pending update; it never spends * another continuation count or creates another usage row. */ export async function materializeGoalContinuation( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; workflowId: string; defaultMaxAutoContinuations?: number | null; budgetBlocked?: string | null; budgetPausedReason?: "limits" | GoalAdmissionPausedReason | undefined; /** Trusted worker admission, evaluated under the same session/goal locks * as lineage materialization. Never substitutes a mutable latest human. */ admission?: ( tx: Database, causalTurn: { id: string; initiatingHumanSubjectId: string | null } | null, ) => Promise<{ budgetBlocked: string | null; budgetPausedReason?: "limits" | GoalAdmissionPausedReason; }>; idleBackoff?: GoalIdleBackoffPolicy | null; policy: { model: string; reasoningEffort: ReasoningEffort; latencyMode: LatencyMode; turnExecutionPolicy?: TurnExecutionPolicyV1; tools: ToolRef[]; sandboxBackend: SandboxBackend; }; prompt: (goal: SessionGoal, autoContinuation: number, cap: number | null) => string; }, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${input.sessionId}`); } const effectiveControl = await evaluateSessionControl( tx, input.workspaceId, input.sessionId, { workspaceControl: locks.control }, ); const [goalRead] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); if ( !goalRead || goalRead.status !== "active" || session.status === "failed" || session.status === "cancelled" || effectiveControl.state !== "active" ) { return { action: "none", events: [] } as const; } // A migrated goal continuation can retain a malformed version even // though its discriminator is intact. Quarantine it before any mapper // can parse the payload, then let this same transaction materialize a // valid successor. The rewritten payload remains contract-parseable // and carries visible evidence for audit/reconciliation. const malformedGoalVersionEvidence = sql` jsonb_build_object( 'reason', 'malformed_goal_version', 'rawGoalVersion', ${schema.sessionSystemUpdates.payload} ->> 'goalVersion', 'expectedGoalVersion', ${goalRead.version}::bigint ) `; await tx .update(schema.sessionSystemUpdates) .set({ state: "failed", classification: "failure", deliveredTurnId: null, deliveredAt: null, summary: "Malformed goal continuation quarantined: malformed_goal_version", summaryCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, payload: sql` ( case when jsonb_typeof(${schema.sessionSystemUpdates.payload}) = 'object' then ${schema.sessionSystemUpdates.payload} else '{}'::jsonb end || jsonb_build_object( 'type', 'goal_continuation', 'goalId', ${goalRead.id}::text, 'goalVersion', ${goalRead.version}::bigint, 'prompt', coalesce( nullif(btrim(${schema.sessionSystemUpdates.payload} ->> 'prompt'), ''), 'Quarantined malformed goal continuation' ), 'quarantine', ${malformedGoalVersionEvidence} ) ) `, lineage: sql` ( case when jsonb_typeof(${schema.sessionSystemUpdates.lineage}) = 'object' then ${schema.sessionSystemUpdates.lineage} else '{}'::jsonb end || jsonb_build_object('quarantine', ${malformedGoalVersionEvidence}) ) `, // This is a partial SQL mutation of the stored JSON value, not a // full decode/re-encode replacement. Preserve the row's existing // payload codec truth: legacy NULL-version marker-shaped strings // remain literal, while an already-versioned payload stays // versioned because its untouched content is already encoded. }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "goal_continuation"), eq(schema.sessionSystemUpdates.state, "pending"), sql`${schema.sessionSystemUpdates.payload} ->> 'goalId' = ${goalRead.id}`, sql`( jsonb_typeof(${schema.sessionSystemUpdates.payload} -> 'goalVersion') = 'number' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' ~ '^[1-9][0-9]*$' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' = ${goalRead.version.toString()} ) is not true`, ), ); const machineOwner = await sessionMachineOwnerSubject(tx, { accountId: null, workspaceId: input.workspaceId, sessionId: input.sessionId, }); const [pendingTurn] = await tx .select({ id: schema.sessionTurns.id, status: schema.sessionTurns.status, source: schema.sessionTurns.source, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), inArray(schema.sessionTurns.status, [ "queued", "running", "requires_action", "recovering", "waiting_capacity", ]), // Waiting messages never hold back the owner's goal. notWaitingForMachineOwnerSql(machineOwner), ), ) .orderBy(asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt)) .limit(1); if (pendingTurn) { return pendingTurn.status === "queued" ? ({ action: "queue", events: [] } as const) : ({ action: "none", events: [] } as const); } // A human/operator Steer is the authoritative next direction. Never // synthesize a goal notice beside it; its own turn settlement will arm // the coalesced goal revision afterward if the goal remains active. const [pendingSteer] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .limit(1); if (pendingSteer) { return { action: "queue", events: [] } as const; } const [existingContinuation] = await tx .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "goal_continuation"), eq(schema.sessionSystemUpdates.state, "pending"), sql`${schema.sessionSystemUpdates.payload} ->> 'goalId' = ${goalRead.id}`, sql`( jsonb_typeof(${schema.sessionSystemUpdates.payload} -> 'goalVersion') = 'number' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' ~ '^[1-9][0-9]*$' and ${schema.sessionSystemUpdates.payload} ->> 'goalVersion' = ${goalRead.version.toString()} )`, ), ) .orderBy(desc(schema.sessionSystemUpdates.createdAt)) .limit(1); if (existingContinuation) { return { action: "continue", events: [], update: mapSessionSystemUpdate(existingContinuation), goalWakeRevision: goalRead.continuationObservedRevision, workflowWakeRevision: 0, } as const; } // A shared-core waiter of any provider (the only kind written after its cutover). const coreCapacityWait = await readSubscriptionCoreWaiterInTransaction( tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, }, ); if (coreCapacityWait) { return { action: "none", events: [] } as const; } // Pending machine input is real model input that the next claim // delivers. The workflow evaluates a session-level wait before calling // this goal materializer, so any pending update reaching this locked // boundary wins over a synthesized continuation. After a terminal // compaction failure only input committed after that failure (or an // Agent Steer) is new truth; the held backlog alone leaves the goal // inert below instead of retrying unchanged state. const compactionHoldSequence = await compactionFailureHoldSequenceTx( tx, input.workspaceId, input.sessionId, ); const pendingMachineInput = await pendingSystemUpdateWakeClassesTx( tx, input.workspaceId, input.sessionId, { pendingAfterSequence: compactionHoldSequence }, ); if ( pendingMachineInput.immediate || pendingMachineInput.deferred || (compactionHoldSequence !== null && (await pendingAgentSteerExistsTx(tx, input.workspaceId, input.sessionId))) ) { return { action: "queue", events: [] } as const; } // A bounded Codex rotation walk is terminal for this exact accepted // input. Do not let the invariant-repair path below manufacture a new // goal wake from equal revisions: that synthesized turn would reset // the per-turn failover budget. New pending input already won above, // and a later externally driven turn becomes the newest finished truth. if (goalRead.continuationSuppressedTurnId) { const [latestFinished] = await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), sql`${schema.sessionTurns.finishedAt} is not null`, ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), ) .limit(1); if (latestFinished?.id === goalRead.continuationSuppressedTurnId) { return { action: "none", events: [] } as const; } } // Idle backoff between CONSECUTIVE no-input continuations. This is // pacing, not a cap, and it is decided here, before the ledger/cap // evaluation, so a deferred pass consumes nothing. The streak is // `auto_continuations` (claim resets it whenever a goal turn's batch // carried other machine input); the previous continuation's finish time // is `session_turns.finished_at` of `last_continuation_turn_id`; the // deadline lives only in the workflow-wake outbox. Pending machine // input, a human prompt, or Steer never reaches this branch (they win // above), and they pull the delayed outbox wake to now. if ( input.idleBackoff && goalRead.autoContinuations >= 1 && goalRead.lastContinuationTurnId ) { const [latestFinishedTurn] = await tx .select({ id: schema.sessionTurns.id, source: schema.sessionTurns.source, finishedAt: schema.sessionTurns.finishedAt, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), sql`${schema.sessionTurns.finishedAt} is not null`, ), ) // Newest finished truth by finish time (see evaluateGoalContinuation): // a human turn queued after internal turns has a low position but // is the newer input that ends the no-input streak. .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), ) .limit(1); if ( latestFinishedTurn?.finishedAt && latestFinishedTurn.source === "goal" && latestFinishedTurn.id === goalRead.lastContinuationTurnId ) { const schedule = input.idleBackoff.scheduleMs; const delayMs = Math.min( schedule[Math.min(goalRead.autoContinuations - 1, schedule.length - 1)] ?? 0, input.idleBackoff.maxMs, ); const dueAt = new Date(latestFinishedTurn.finishedAt.getTime() + delayMs); // Database clock, like the hold deadline: the wake-outbox // dispatcher fires on DB `now()`. const dbNow = await transactionNow(tx); if (delayMs > 0 && dbNow.getTime() < dueAt.getTime()) { // Re-arm on every idle evaluation for the same reason the hold // does: an earlier immediate wake delivered in between advances // the outbox's delivered revision and would otherwise drop the // deadline row; an undelivered earlier wake coalesces with // `least(next_attempt_at, notBefore)`. await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? input.workflowId, reason: GOAL_IDLE_BACKOFF_WAKE_REASON, notBefore: dueAt, }); return { action: "deferred", events: [], notBefore: dueAt, } as const; } } } // Freeze one exact latest-finished causal row while holding the // canonical session lock. Admission and queued lineage reuse it. const [causalTurn] = await tx .select({ id: schema.sessionTurns.id, personalConnectionDelegations: schema.sessionTurns.personalConnectionDelegations, mcpAccountBindings: schema.sessionTurns.mcpAccountBindings, initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, initiatorKind: schema.sessionTurns.initiatorKind, initiatorSubjectId: schema.sessionTurns.initiatorSubjectId, xaiProviderAccountAuthoritySnapshot: schema.sessionTurns.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: schema.sessionTurns.claudeProviderAccountAuthoritySnapshot, metadata: schema.sessionTurns.metadata, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), sql`${schema.sessionTurns.finishedAt} is not null`, ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), desc(schema.sessionTurns.id), ) .limit(1); const admission = await input.admission?.(tx, causalTurn ?? null); let goalWakeRevision = goalRead.continuationWakeRevision; if (goalWakeRevision <= goalRead.continuationObservedRevision) { // This is an invariant-repair path, not a polling loop: a workflow // reached an admitted idle goal without the terminal-settlement arm. // Persist one new monotonic obligation before evaluating it. const [repaired] = await tx .update(schema.sessionGoals) .set({ continuationWakeRevision: sql`${schema.sessionGoals.continuationWakeRevision} + 1`, updatedAt: new Date(), }) .where(eq(schema.sessionGoals.id, goalRead.id)) .returning({ revision: schema.sessionGoals.continuationWakeRevision, }); if (!repaired) throw new Error(`Session goal not found: ${input.sessionId}`); goalWakeRevision = repaired.revision; } const decision = await evaluateGoalContinuation(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, defaultMaxAutoContinuations: input.defaultMaxAutoContinuations ?? null, budgetBlocked: admission ? admission.budgetBlocked : (input.budgetBlocked ?? null), budgetPausedReason: admission ? admission.budgetPausedReason : input.budgetPausedReason, }); if (decision.decision === "none" || decision.decision === "queue") { return { action: decision.decision, events: [] } as const; } const now = new Date(); if (decision.decision === "paused") { const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "goal.paused", payload: { goalId: decision.goal.id, actor: "system", reason: decision.reason, ...(decision.goal.rationale ? { rationale: decision.goal.rationale } : {}), autoContinuations: decision.goal.autoContinuations, noProgressStreak: decision.goal.noProgressStreak, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append goal.paused event"); await tx .update(schema.sessionGoals) .set({ continuationObservedRevision: goalWakeRevision, updatedAt: now, }) .where(eq(schema.sessionGoals.id, decision.goal.id)); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, session.id)); return { action: "paused", events: [mapEvent(event)] } as const; } const personalConnectionDelegations = causalTurn ? parsedPersonalConnectionDelegations( causalTurn.personalConnectionDelegations, `session_turns:${input.workspaceId}:${input.sessionId}:${causalTurn.id}`, ) : []; // Without a finished causal turn there is no accepted pool or human to // carry, so resolve the organization or workspace pool (never personal). const sharedGoalPool = causalTurn ? null : await sharedPoolSubscriptionAuthoritySnapshotsInTransaction(tx, input.workspaceId); const xaiProviderAccountAuthoritySnapshot = causalTurn ? XaiProviderAccountAuthoritySnapshotV1.parse( causalTurn.xaiProviderAccountAuthoritySnapshot, ) : sharedGoalPool!.xai; const claudeProviderAccountAuthoritySnapshot = causalTurn ? ClaudeProviderAccountAuthoritySnapshotV1.parse( causalTurn.claudeProviderAccountAuthoritySnapshot, ) : sharedGoalPool!.claude; const causalCodexPolicy = causalTurn ? readCodexCredentialPolicySnapshotV1(causalTurn.metadata) : { kind: "absent" as const }; const xaiAuthoritySubjectId = causalTurn && xaiProviderAccountAuthoritySnapshot.scope === "user" ? (causalTurn.initiatingHumanSubjectId ?? (causalTurn.initiatorKind === "subject" ? causalTurn.initiatorSubjectId : null)) : null; const claudeAuthoritySubjectId = causalTurn && claudeProviderAccountAuthoritySnapshot.scope === "user" ? (causalTurn.initiatingHumanSubjectId ?? (causalTurn.initiatorKind === "subject" ? causalTurn.initiatorSubjectId : null)) : null; if (xaiProviderAccountAuthoritySnapshot.scope === "user" && !xaiAuthoritySubjectId) { throw new Error("Goal continuation lost its user-scoped xAI causal subject"); } if (claudeProviderAccountAuthoritySnapshot.scope === "user" && !claudeAuthoritySubjectId) { throw new Error("Goal continuation lost its user-scoped Claude causal subject"); } const prompt = input.prompt(decision.goal, decision.autoContinuation, decision.cap); const payload = { type: "goal_continuation" as const, goalId: decision.goal.id, goalVersion: decision.goal.version, goalWakeRevision, autoContinuation: decision.autoContinuation, maxAutoContinuations: decision.cap, prompt, policy: input.policy, }; if (Buffer.byteLength(JSON.stringify(payload)) > MAX_INTERNAL_UPDATE_BYTES) { throw new Error(`Internal update payload exceeds ${MAX_INTERNAL_UPDATE_BYTES} bytes`); } if (Buffer.byteLength(prompt) > MAX_INTERNAL_UPDATE_BYTES) { throw new Error(`Goal continuation prompt exceeds ${MAX_INTERNAL_UPDATE_BYTES} bytes`); } const [update] = await tx .insert(schema.sessionSystemUpdates) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: "goal_continuation", classification: "info", sourceId: decision.goal.id, dedupeKey: `goal-continuation:${decision.goal.id}:wake:${goalWakeRevision}`, summary: "Continue active session goal", payload, lineage: { goalId: decision.goal.id, goalWakeRevision, ...(causalTurn ? { causalTurnId: causalTurn.id } : {}), ...(causalTurn?.initiatingHumanSubjectId && personalConnectionDelegations.length > 0 ? { connectionAuthoritySubjectId: causalTurn.initiatingHumanSubjectId, } : {}), ...(xaiAuthoritySubjectId ? { xaiAuthoritySubjectId } : {}), ...(claudeAuthoritySubjectId ? { claudeAuthoritySubjectId } : {}), ...(causalCodexPolicy.kind === "valid" ? { [CODEX_CREDENTIAL_POLICY_SNAPSHOT_METADATA_KEY]: causalCodexPolicy.policy, } : {}), }, personalConnectionDelegations, mcpAccountBindings: parseAcceptedMcpAccountBindings( causalTurn?.mcpAccountBindings, ), xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot, state: "pending", }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .returning(); if (!update) throw new Error("Failed to create goal continuation update"); await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_system_update", workspaceId: input.workspaceId, id: update.id }, ]); await tx .insert(schema.usageEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, eventType: "agent_run.created", quantity: 1, unit: "run", sourceResourceType: "session_system_update", sourceResourceId: update.id, idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${decision.goal.id}:${goalWakeRevision}`, occurredAt: now, }) .onConflictDoNothing({ target: schema.usageEvents.idempotencyKey }); const eventPreview = internalUpdateEventMember(update); const insertedEvents = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "system.update.pending", payload: { updateId: eventPreview.id, kind: eventPreview.kind, classification: eventPreview.classification, sourceId: eventPreview.sourceId, sourceIdTruncated: eventPreview.sourceIdTruncated, summary: eventPreview.summary, summaryTruncated: eventPreview.summaryTruncated, }, occurredAt: now, }, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2, type: "goal.continuation", payload: { goalId: decision.goal.id, text: decision.goal.text, version: decision.goal.version, goalWakeRevision, autoContinuation: decision.autoContinuation, }, occurredAt: now, }, ], "payload", "payloadCodecVersion", ), ) .returning(); if (insertedEvents.length !== 2) { throw new Error("Failed to append goal continuation events"); } await tx .update(schema.sessionGoals) .set({ continuationObservedRevision: goalWakeRevision, updatedAt: now, }) .where(eq(schema.sessionGoals.id, decision.goal.id)); const wake = await registerInternalUpdateWakeInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? input.workflowId, }); await tx .update(schema.sessions) .set({ status: "queued", lastSequence: session.lastSequence + 2, updatedAt: now, }) .where(eq(schema.sessions.id, session.id)); return { action: "continue", events: insertedEvents.map(mapEvent), update: mapSessionSystemUpdate(update), goalWakeRevision, workflowWakeRevision: wake.wakeRevision, } as const; }), ); } function mapSessionGoal(row: typeof schema.sessionGoals.$inferSelect): SessionGoal { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, status: row.status as SessionGoal["status"], text: row.text, successCriteria: row.successCriteria, rootConstraints: row.rootConstraints, reportRequirements: goalReportRequirements(row.metadata), evidence: row.evidence, rationale: row.rationale, pausedReason: row.pausedReason, createdBy: row.createdBy as SessionGoal["createdBy"], version: row.version, objectiveRevision: row.objectiveRevision, mutationPolicy: row.mutationPolicy, autoContinuations: row.autoContinuations, noProgressStreak: row.noProgressStreak, maxAutoContinuations: row.maxAutoContinuations, metadata: row.metadata, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } export type InitializeSessionStartInput = { accountId: string; workspaceId: string; sessionId: string; clientEventId?: string; reasoningEffortFallback: ReasoningEffort; /** Trusted create-session policy. Omitted only by legacy low-level callers. */ turnExecutionPolicy?: TurnExecutionPolicyV1; /** Content-free product surface the create request entered through. */ surface?: SessionTurnSurface | null; /** Funding origin frozen on the initial turn; null inherits the parent's. */ billingOrigin?: BillingOrigin | null; /** * Normalized IANA zone of the person sending the initial message, frozen in * the initial turn's metadata. */ initialTimeZone?: string; /** * Tools the opening context is for, already narrowed to the session's own * selection, frozen in the initial turn's metadata. That turn's first model * step loads them as a search by name would. */ initialOpeningTools?: readonly string[]; /** * Codex v2 (M3 PR 3b) frozen by a trusted producer for the first turn: a * scheduled firing passes its task's value, which is copied, never * recomputed. Omitted by every other caller (the acceptance rule applies). */ initialSubscriptionAuthority?: SubscriptionPersonalAuthorityV2 | null; createdEventPayload: Record; /** Trusted backend-only capture for a newly inserted initial turn. Runs under * the canonical activity transaction; failure rolls back events and turn. * Never invoked on replay or deferred starts; not caller JSON authority. */ captureInitialTurnAuthority?: (tx: Database, turnId: string) => Promise; /** Sensitive-safe semantic title supplied by the trusted agent-child create * path. It is committed with the initial timeline, never as a bare row edit. */ initialAutomaticTitle?: string | null; goal?: { text: string; successCriteria?: string | null; rootConstraints?: string[]; reportRequirements?: SessionGoalReportRequirement[]; maxAutoContinuations?: number | null; mutationPolicy?: SessionGoalMutationPolicy; createdBy?: SessionGoalCreatedBy; } | null; consumeNewSessionDraft?: { subjectId: string; expectedRevision: number; expectedSnapshot?: NewSessionDraftSnapshot; acceptedSelection?: { channelId: string | null; targetSandboxId: string | null; workingDir: string | null; }; } | null; /** Successful create that preserves, rather than consumes, the draft. */ rememberNewSessionSelection?: { subjectId: string; acceptedSelection: { channelId: string | null; targetSandboxId: string | null; workingDir: string | null; }; } | null; /** Persist session.created only; realtime will supply the first human turn. */ deferInitialTurn?: boolean; /** Public status persisted with a deferred session start. Defaults to idle. */ deferredStatus?: Extract; }; export type InitializeSessionStartResult = { events: SessionEvent[]; turn: SessionTurn | null; temporalWorkflowId: string; workflowWakeRevision: number | null; /** True when this call installed/repaired start state or committed a new wake revision. */ changed: boolean; }; /** Trusted per-message facts the create request froze for the initial turn. */ function initialTurnMetadata( input: Pick, ): Record { const timeZone = normalizeMessageTimeZone(input.initialTimeZone); const openingTools = openingToolsFromTurnMetadata({ [OPENING_TOOLS_METADATA_KEY]: input.initialOpeningTools, }); return { ...(timeZone ? { [MESSAGE_TIME_ZONE_METADATA_KEY]: timeZone } : {}), ...(openingTools.length ? { [OPENING_TOOLS_METADATA_KEY]: openingTools } : {}), }; } /** * Install a newly created session's complete first runnable unit atomically. * The canonical user event, optional goal, queued turn, public status, and * workflow wake revision either all commit or all roll back. Retrying the same * create repairs any pre-transaction partial state and emits only missing * records; it never creates a second initial turn. */ export async function initializeSessionStartAtomically( db: Database, input: InitializeSessionStartInput, ): Promise { if (input.deferInitialTurn && input.captureInitialTurnAuthority) throw new Error("Deferred session starts cannot capture initial turn authority"); return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.workspace || !session) throw new Error(`Session not found: ${input.sessionId}`); const canonicalInitialMessage = fromPostgresLosslessText( session.initialMessage, session.initialMessageCodecVersion, ); const creatorContext = session.createdByContext ?? {}; const creator: FrozenTurnInitiator = { initiator: initiatorFromStorage( session.createdByKind, session.createdBySubjectId, creatorContext, ), context: creatorContext, }; const effectiveControl = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); const temporalWorkflowId = session.temporalWorkflowId ?? `session-${session.id}`; if (session.status === "cancelled") { return { events: [], turn: null, temporalWorkflowId, workflowWakeRevision: null, changed: false, }; } const normalizedInitialAutomaticTitle = typeof input.initialAutomaticTitle === "string" ? normalizeAutomaticSessionTitle(input.initialAutomaticTitle) : null; let appliedInitialAutomaticTitle: string | null = null; if ( normalizedInitialAutomaticTitle && normalizedInitialAutomaticTitle !== AUTOMATIC_SESSION_TITLE_FALLBACK && session.title === AUTOMATIC_SESSION_TITLE_FALLBACK && session.titleSource === "agent" ) { await tx.execute( sql`select pg_catalog.set_config('opengeni.automatic_session_title_v1_candidate', ${normalizedInitialAutomaticTitle}, true)`, ); const [updatedTitle] = await tx .update(schema.sessions) .set({ title: normalizedInitialAutomaticTitle, titleSource: "agent", updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, session.id), eq(schema.sessions.title, AUTOMATIC_SESSION_TITLE_FALLBACK), eq(schema.sessions.titleSource, "agent"), ), ) .returning({ title: schema.sessions.title }); appliedInitialAutomaticTitle = updatedTitle?.title ?? null; } let insertedGoal = false; let [goal] = await tx .select() .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, session.id), ), ) .for("update") .limit(1); if (!goal && input.goal) { const rootConstraints = normalizeAndAssertSessionGoalRootConstraints( input.goal.rootConstraints ?? [], ); [goal] = await tx .insert(schema.sessionGoals) .values({ accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, text: input.goal.text, successCriteria: input.goal.successCriteria ?? null, rootConstraints, metadata: appendGoalReportRequirements({}, input.goal.reportRequirements), maxAutoContinuations: input.goal.maxAutoContinuations ?? null, mutationPolicy: input.goal.mutationPolicy ?? "preserve_intent", createdBy: input.goal.createdBy ?? "api", }) .returning(); if (!goal) throw new Error("Failed to create initial session goal"); insertedGoal = true; } if (input.deferInitialTurn) { const deferredStatus = input.deferredStatus ?? "idle"; const [existingCreatedEvent] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, session.id), eq(schema.sessionEvents.type, "session.created"), ), ) .limit(1); let sequence = session.lastSequence; let initializedNow = false; let insertedEvents: Array = []; if (!existingCreatedEvent) { insertedEvents = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.created", payload: { ...input.createdEventPayload, status: deferredStatus, createdBy: creator.initiator, ...(session.resources.length ? { resources: session.resources } : {}), }, }, ...(appliedInitialAutomaticTitle ? [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.title_set" as const, payload: { title: appliedInitialAutomaticTitle, source: "agent", }, }, ] : []), ...(goal ? [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "goal.set" as const, payload: { goalId: goal.id, text: goal.text, ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}), rootConstraints: goal.rootConstraints, version: goal.version, objectiveRevision: goal.objectiveRevision, mutationPolicy: goal.mutationPolicy, actor: input.goal?.createdBy ?? "api", replaced: false, }, }, ] : []), ], "payload", "payloadCodecVersion", ), ) .returning(); initializedNow = true; } else if (appliedInitialAutomaticTitle) { const [titleEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.title_set", payload: { title: appliedInitialAutomaticTitle, source: "agent", }, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!titleEvent) throw new Error("Failed to append initial session title event"); insertedEvents.push(titleEvent); } const deferredStatusNeedsRepair = initializedNow && session.status !== deferredStatus; const sessionNeedsRepair = session.temporalWorkflowId !== temporalWorkflowId || session.lastSequence !== sequence || deferredStatusNeedsRepair; if (sessionNeedsRepair) { await tx .update(schema.sessions) .set({ temporalWorkflowId, lastSequence: sequence, ...(deferredStatusNeedsRepair ? { status: deferredStatus } : {}), updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, session.id), ), ); } if (initializedNow && input.consumeNewSessionDraft) { await setSubjectRlsContext( tx as unknown as Database, input.consumeNewSessionDraft.subjectId, ); await seedNewSessionDraftInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, subjectId: input.consumeNewSessionDraft.subjectId, expectedRevision: input.consumeNewSessionDraft.expectedRevision, ...(input.consumeNewSessionDraft.expectedSnapshot ? { expectedSnapshot: input.consumeNewSessionDraft.expectedSnapshot, } : {}), ...(input.consumeNewSessionDraft.acceptedSelection ? { acceptedSelection: input.consumeNewSessionDraft.acceptedSelection, } : {}), }); } else if (initializedNow && input.rememberNewSessionSelection) { await setSubjectRlsContext( tx as unknown as Database, input.rememberNewSessionSelection.subjectId, ); await rememberNewSessionSelectionInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, subjectId: input.rememberNewSessionSelection.subjectId, acceptedSelection: input.rememberNewSessionSelection.acceptedSelection, }); } return { events: insertedEvents.map(mapEvent), turn: null, temporalWorkflowId, workflowWakeRevision: null, changed: insertedGoal || insertedEvents.length > 0 || sessionNeedsRepair, }; } const existingUserEvents = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, session.id), eq(schema.sessionEvents.type, "user.message"), ), ) .orderBy(asc(schema.sessionEvents.sequence)) .limit(1); let userEvent: typeof schema.sessionEvents.$inferSelect | undefined = existingUserEvents[0]; let sequence = session.lastSequence; const insertedEvents: Array = []; const runnable = effectiveControl.state === "active"; const publicQueuedStatus: SessionStatus = "queued"; let initializedNow = false; if (!userEvent) { const initialPayload = { text: canonicalInitialMessage, ...(session.resources.length ? { resources: session.resources } : {}), ...(session.tools.length ? { tools: session.tools } : {}), }; const rows = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.created", payload: { ...input.createdEventPayload, status: publicQueuedStatus, createdBy: creator.initiator, }, }, ...(appliedInitialAutomaticTitle ? [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.title_set" as const, payload: { title: appliedInitialAutomaticTitle, source: "agent", }, }, ] : []), ...(goal ? [ { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "goal.set" as const, payload: { goalId: goal.id, text: goal.text, ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}), rootConstraints: goal.rootConstraints, version: goal.version, objectiveRevision: goal.objectiveRevision, mutationPolicy: goal.mutationPolicy, actor: "api", replaced: false, }, }, ] : []), { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "user.message", payload: { ...initialPayload, ...(session.initialModelContext ? { modelContext: session.initialModelContext } : {}), routing: runnable ? "accepted_for_execution" : "queued_for_execution", initiator: creator.initiator, }, clientEventId: input.clientEventId ?? `session-initial:${session.id}`, }, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.status.changed", payload: { status: publicQueuedStatus }, }, ], "payload", "payloadCodecVersion", ), ) .returning(); insertedEvents.push(...rows); userEvent = rows.find((event) => event.type === "user.message"); if (!userEvent) throw new Error("Failed to create initial user event"); initializedNow = true; } else if (appliedInitialAutomaticTitle) { const [titleEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.title_set", payload: { title: appliedInitialAutomaticTitle, source: "agent", }, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!titleEvent) throw new Error("Failed to append initial session title event"); insertedEvents.push(titleEvent); } let [turn] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, session.id), eq(schema.sessionTurns.triggerEventId, userEvent.id), ), ) .orderBy(asc(schema.sessionTurns.createdAt)) .limit(1); let insertedTurn = false; let queueTailPosition = Number(session.queueTailPosition); if (!turn) { const initialPersonalConnectionDelegations = parsedPersonalConnectionDelegations( session.initialPersonalConnectionDelegations, `sessions:${session.workspaceId}:${session.id}:initial`, ); const creatorHumanSubjectId = creator.initiator.kind === "subject" ? creator.initiator.subjectId : null; let initialTurnInitiatingHumanSubjectId = creatorHumanSubjectId ?? onlyMeMeetingSummaryOwner(session); let causalParentSubscriptionAuthority: SubscriptionPersonalAuthorityV2 | null = null; if (session.parentSessionId && session.parentTurnId) { const [causalParentTurn] = await tx .select({ initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, initiatorKind: schema.sessionTurns.initiatorKind, initiatorSubjectId: schema.sessionTurns.initiatorSubjectId, subscriptionAuthority: schema.sessionTurns.subscriptionAuthority, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.accountId, session.accountId), eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, session.parentSessionId), eq(schema.sessionTurns.id, session.parentTurnId), ), ) .limit(1); if (!causalParentTurn) { throw new Error(`Causal parent turn not found: ${session.parentTurnId}`); } initialTurnInitiatingHumanSubjectId = causalParentTurn.initiatingHumanSubjectId ?? (causalParentTurn.initiatorKind === "subject" ? causalParentTurn.initiatorSubjectId : null); causalParentSubscriptionAuthority = causalParentTurn.subscriptionAuthority ?? null; } if (initialPersonalConnectionDelegations.length > 0) { if (!initialTurnInitiatingHumanSubjectId) { throw new Error("Personal connection acceptance requires an initiating human"); } await tx.execute(sql` SELECT set_config( 'opengeni.initiating_human_subject_id', ${initialTurnInitiatingHumanSubjectId}, true ) `); } queueTailPosition += 1; const acceptedAt = new Date(); // v2 accepted authority for every provider on the shared core (M3 // PR 2a; M4 X2b): only the owner's own initial message freezes // personal authority, so an Only me meeting summary, which runs for // its owner, still uses only shared accounts. A scheduled firing // copies its task's frozen value (M3 PR 3b). A child session's first // turn takes its exact causal parent turn's immutable value (M3 PR 3, // design 3.7 EP-T13), never a fresh computation: it gains nothing the // parent did not hold, and the database rechecks owner, session and // generation before any personal lease. A parent with no v2 value // yields the empty value. const initialSubscriptionAuthority = input.initialSubscriptionAuthority !== undefined ? subscriptionAuthorityV2OrEmpty(input.initialSubscriptionAuthority) : session.parentSessionId ? causalParentSubscriptionAuthority !== null ? causalParentSubscriptionAuthority : await coreSubscriptionAuthorityV2ForAcceptanceInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, acceptingSubjectId: null, }, ) : await coreSubscriptionAuthorityV2ForAcceptanceInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, acceptingSubjectId: creatorHumanSubjectId, }, ); [turn] = await tx .insert(schema.sessionTurns) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, triggerEventId: userEvent.id, temporalWorkflowId, status: "queued", source: "user", surface: input.surface ?? null, billingOrigin: input.billingOrigin ?? null, promptRouting: runnable ? "accepted_for_execution" : "queued_for_execution", position: queueTailPosition, prompt: canonicalInitialMessage, modelContext: session.initialModelContext ?? null, resources: session.resources, tools: session.tools, toolsProvided: session.toolPolicy?.mode === "explicit", model: session.model, reasoningEffort: session.reasoningEffort, latencyMode: input.turnExecutionPolicy?.latencyMode ?? session.latencyMode, sandboxBackend: session.sandboxBackend, sandboxOs: session.sandboxOs, metadata: input.turnExecutionPolicy ? metadataWithTurnExecutionPolicyV1( initialTurnMetadata(input), input.turnExecutionPolicy, ) : initialTurnMetadata(input), lineage: {}, ...initiatorColumns(creator), initiatingHumanSubjectId: initialTurnInitiatingHumanSubjectId, personalConnectionDelegations: initialPersonalConnectionDelegations, mcpAccountBindings: parseAcceptedMcpAccountBindings( session.initialMcpAccountBindings, ), connectionAccountIntent: parseConnectionAccountIntent( session.initialConnectionAccountIntent, ), xaiProviderAccountAuthoritySnapshot: session.initialXaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: session.initialClaudeProviderAccountAuthoritySnapshot, subscriptionAuthority: initialSubscriptionAuthority, createdAt: acceptedAt, updatedAt: acceptedAt, }, "prompt", "promptCodecVersion", ), ) .returning(); if (!turn) throw new Error("Failed to create initial session turn"); insertedTurn = true; await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_turn", workspaceId: input.workspaceId, id: turn.id }, ]); } await lockSessionEventWriteRows(tx as unknown as Database, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [turn.id], }); const initialPersonalResourceIntent = session.initialPersonalResourceAttachmentIntent; if (insertedTurn && input.captureInitialTurnAuthority) await input.captureInitialTurnAuthority(tx as unknown as Database, turn.id); if (insertedTurn && session.parentSessionId && session.parentTurnId) await inheritExternalLinkTurnAuthority(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: turn.id, sourceTurnId: session.parentTurnId, kind: "child", }); if (initialPersonalResourceIntent) { const attachmentInitiatingHumanSubjectId = turn.initiatingHumanSubjectId ?? (turn.initiatorKind === "subject" ? turn.initiatorSubjectId : null); if (!attachmentInitiatingHumanSubjectId) { throw new Error("Atomic personal-resource attachment requires an initiating human"); } const acceptedPersonalResources = turn.personalResourceProtocolVersion === 1 && turn.personalResourceAttachmentSummary ? { summary: PersonalResourceAttachmentSummary.parse( turn.personalResourceAttachmentSummary, ), replay: true, } : await acceptTurnPersonalResourceAttachmentInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: turn.id, subjectId: attachmentInitiatingHumanSubjectId, intent: { ...initialPersonalResourceIntent, expectedAuthorityEpoch: session.authorityEpoch, }, }); turn = { ...turn, personalResourceAttachmentSummary: acceptedPersonalResources.summary, personalResourceProtocolVersion: 1, }; const [existingAttachmentEvent] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, session.id), eq(schema.sessionEvents.turnId, turn.id), eq(schema.sessionEvents.type, "session.personal_resources.attached"), ), ) .limit(1); if (!existingAttachmentEvent) { const [attachmentEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: turn.id, sequence: ++sequence, type: "session.personal_resources.attached", payload: { turnId: turn.id, ...acceptedPersonalResources.summary, }, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!attachmentEvent) { throw new Error("Failed to append initial personal-resource attachment event"); } insertedEvents.push(attachmentEvent); } } const [queuedEvent] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, session.id), eq(schema.sessionEvents.turnId, turn.id), eq(schema.sessionEvents.type, "turn.queued"), ), ) .limit(1); if (!queuedEvent) { const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: turn.id, sequence: ++sequence, type: "turn.queued", payload: { turnId: turn.id, triggerEventId: userEvent.id, source: turn.source, ...(turn.promptRouting ? { routing: turn.promptRouting } : {}), initiator: creator.initiator, }, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to create initial turn event"); insertedEvents.push(event); } const turnNeedsWake = turn.status === "queued" && runnable; const sessionNeedsRepair = session.temporalWorkflowId !== temporalWorkflowId || session.lastSequence !== sequence || insertedTurn || (turn.status === "queued" && session.status !== publicQueuedStatus); if (sessionNeedsRepair) { await tx .update(schema.sessions) .set({ temporalWorkflowId, lastSequence: sequence, ...(insertedTurn ? { queueVersion: session.queueVersion + 1, queueTailPosition, } : {}), ...(turn.status === "queued" ? { status: publicQueuedStatus } : {}), updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, session.id), ), ); } const workflowWakeRevision = turnNeedsWake ? await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId, reason: "initial_session", }) : null; if (initializedNow && input.consumeNewSessionDraft) { await setSubjectRlsContext( tx as unknown as Database, input.consumeNewSessionDraft.subjectId, ); await seedNewSessionDraftInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, subjectId: input.consumeNewSessionDraft.subjectId, expectedRevision: input.consumeNewSessionDraft.expectedRevision, ...(input.consumeNewSessionDraft.expectedSnapshot ? { expectedSnapshot: input.consumeNewSessionDraft.expectedSnapshot, } : {}), ...(input.consumeNewSessionDraft.acceptedSelection ? { acceptedSelection: input.consumeNewSessionDraft.acceptedSelection, } : {}), }); } else if (initializedNow && input.rememberNewSessionSelection) { await setSubjectRlsContext( tx as unknown as Database, input.rememberNewSessionSelection.subjectId, ); await rememberNewSessionSelectionInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, subjectId: input.rememberNewSessionSelection.subjectId, acceptedSelection: input.rememberNewSessionSelection.acceptedSelection, }); } const changed = insertedGoal || insertedEvents.length > 0 || insertedTurn || sessionNeedsRepair || workflowWakeRevision !== null; return { events: insertedEvents.map(mapEvent), turn: mapSessionTurn(turn), temporalWorkflowId, workflowWakeRevision, changed, }; }), ); } export async function enqueueSessionTurn( db: Database, input: EnqueueSessionTurnInput, ): Promise { if (input.source !== "user" && input.source !== "api") { throw new Error("Only human prompts may enter the visible session queue"); } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const effectiveControl = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { lock: "share" }, ); if (input.initiator.kind === "subject") { await setSubjectRlsContext(tx as unknown as Database, input.initiator.subjectId); await assertActiveManagedHumanOrganizationMembership(tx as unknown as Database, { accountId: input.accountId, subjectId: input.initiator.subjectId, }); } const [lockedSession] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("no key update") .limit(1); if (!lockedSession) { throw new Error(`Session not found: ${input.sessionId}`); } const atHead = input.placement === "head"; const position = atHead ? Number(lockedSession.queueHeadPosition) - 1 : Number(lockedSession.queueTailPosition) + 1; const acceptedAt = new Date(); const initiatingHumanSubjectId = input.initiator.kind === "subject" ? input.initiator.subjectId : null; if ((input.personalConnectionDelegations?.length ?? 0) > 0) { if (!initiatingHumanSubjectId) { throw new Error("Personal connection acceptance requires an initiating human"); } await tx.execute(sql` SELECT set_config( 'opengeni.initiating_human_subject_id', ${initiatingHumanSubjectId}, true ) `); } // Callers that froze no pool resolve the organization or workspace // pool; a personal pool always requires an explicit frozen snapshot. const sharedTurnPool = input.xaiProviderAccountAuthoritySnapshot === undefined || input.claudeProviderAccountAuthoritySnapshot === undefined ? await sharedPoolSubscriptionAuthoritySnapshotsInTransaction( tx as unknown as Database, input.workspaceId, ) : null; const [row] = await tx .insert(schema.sessionTurns) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, triggerEventId: input.triggerEventId, temporalWorkflowId: input.temporalWorkflowId, status: "queued", source: input.source, surface: input.surface ?? null, billingOrigin: input.billingOrigin ?? null, promptRouting: "queued_for_execution", position, prompt: input.prompt, modelContext: input.modelContext ?? null, resources: input.resources, tools: input.tools, toolsProvided: input.toolsProvided ?? false, model: input.model, reasoningEffort: input.reasoningEffort, latencyMode: input.latencyMode ?? "standard", sandboxBackend: input.sandboxBackend, sandboxOs: input.sandboxOs ?? null, metadata: input.metadata, lineage: input.lineage ?? {}, ...initiatorColumns({ initiator: input.initiator, context: input.initiatorContext ?? {}, }), initiatingHumanSubjectId, personalConnectionDelegations: input.personalConnectionDelegations ?? [], mcpAccountBindings: parseAcceptedMcpAccountBindings(input.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot: input.xaiProviderAccountAuthoritySnapshot ?? sharedTurnPool!.xai, claudeProviderAccountAuthoritySnapshot: input.claudeProviderAccountAuthoritySnapshot ?? sharedTurnPool!.claude, // This exported low-level enqueue is also an acceptance boundary. // Freeze the named human (or empty service authority) exactly once, // just like the canonical prompt path; never leave postcutover NULL. subscriptionAuthority: await coreSubscriptionAuthorityV2ForAcceptanceInTransaction( tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, acceptingSubjectId: initiatingHumanSubjectId, }, ), createdAt: acceptedAt, updatedAt: acceptedAt, }, "prompt", "promptCodecVersion", ), ) .returning(); if (!row) { throw new Error("Failed to enqueue session turn"); } await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_turn", workspaceId: input.workspaceId, id: row.id }, ]); await tx .update(schema.sessions) .set({ queueVersion: lockedSession.queueVersion + 1, ...(atHead ? { queueHeadPosition: position } : { queueTailPosition: position }), status: effectiveControl.state === "active" && lockedSession.activeTurnId === null ? "queued" : lockedSession.status, updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return mapSessionTurn(row); }), ); } export type SessionWorkTrigger = { kind: "next" } | { kind: "approval"; triggerEventId: string }; export const MAX_INTERNAL_UPDATE_BYTES = 64 * 1024; export const MAX_INTERNAL_UPDATE_BATCH_MEMBERS = 100; export const MAX_INTERNAL_UPDATE_BATCH_BYTES = 256 * 1024; const MAX_INTERNAL_UPDATE_EVENT_SUMMARY_BYTES = 512; const MAX_INTERNAL_UPDATE_EVENT_SOURCE_BYTES = 256; type BoundedSystemUpdate = Pick< typeof schema.sessionSystemUpdates.$inferSelect, | "id" | "kind" | "classification" | "sourceId" | "summary" | "payload" | "lineage" | "personalConnectionDelegations" | "mcpAccountBindings" | "xaiProviderAccountAuthoritySnapshot" | "claudeProviderAccountAuthoritySnapshot" | "scheduledTaskRunId" | "subscriptionAuthority" >; export type FrozenXaiExecutionAuthority = { snapshot: XaiProviderAccountAuthoritySnapshotV1; subjectId: string | null; }; function frozenSubscriptionExecutionAuthority( update: Pick< BoundedSystemUpdate, | "id" | "lineage" | "xaiProviderAccountAuthoritySnapshot" | "claudeProviderAccountAuthoritySnapshot" >, provider: "xai" | "claude", ): FrozenXaiExecutionAuthority { const snapshot = XaiProviderAccountAuthoritySnapshotV1.parse( provider === "xai" ? update.xaiProviderAccountAuthoritySnapshot : update.claudeProviderAccountAuthoritySnapshot, ); if (snapshot.scope !== "user") return { snapshot, subjectId: null }; const subjectId = update.lineage[provider === "xai" ? "xaiAuthoritySubjectId" : "claudeAuthoritySubjectId"]; if (typeof subjectId !== "string" || subjectId.trim().length === 0) throw new Error(`User-scoped ${provider} system update has no causal subject: ${update.id}`); return { snapshot, subjectId }; } const frozenXaiExecutionAuthority = ( update: Parameters[0], ) => frozenSubscriptionExecutionAuthority(update, "xai"); const frozenClaudeExecutionAuthority = ( update: Parameters[0], ) => frozenSubscriptionExecutionAuthority(update, "claude"); function systemUpdateExecutionAuthorityKey( update: BoundedSystemUpdate, compatAuthority?: Readonly>, ): string { const personalConnectionDelegations = parsedPersonalConnectionDelegations( update.personalConnectionDelegations, `session_system_updates:${update.id}`, ); return stableJson({ personalConnectionDelegations, mcpAccountBindings: parseAcceptedMcpAccountBindings(update.mcpAccountBindings), xai: frozenXaiExecutionAuthority(update), claude: frozenClaudeExecutionAuthority(update), connectionAuthoritySubjectId: personalConnectionDelegations.length > 0 ? (update.lineage.connectionAuthoritySubjectId ?? null) : null, scheduledTaskRunId: update.scheduledTaskRunId, // Codex v2 (M3 PR 3b): updates frozen with different values never share // one internal turn. codexV2: update.subscriptionAuthority ?? null, // After a provider's own drained cutover (M4 PR 0b): its effective // accepted authority, because its post-cutover v1 default equals a real // pre-cutover `workspace` value. Absent while no provider holds records. ...(compatAuthority === undefined ? {} : { compatAuthority }), }); } /** 0716's effective authority for post-receipt work without a v2 entry or record. */ function isPostReceiptWithoutAuthority(value: unknown): boolean { return stableJson(value ?? null) === stableJson({ authority: "none" }); } function systemUpdateCausalHumanTurnId( update: Pick, ): string | null { const lineage = update.lineage && typeof update.lineage === "object" && !Array.isArray(update.lineage) ? (update.lineage as Record) : null; const value = isChildLifecycleSystemUpdateKind(update.kind) ? lineage?.parentTurnId : update.kind === "goal_continuation" || update.kind === "background_command_result" || update.kind === "session_wait_timeout" || update.kind === "capability_setup_completed" || update.kind === "secret_use_approval_decided" ? lineage?.causalTurnId : null; if (typeof value !== "string" || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu.test(value)) { return null; } return value; } function agentCommandCausalActor(update: Pick): { sessionId: string; turnId: string; attemptId: string; executionGeneration: number; } | null { if (update.kind !== "agent_steer_instruction" && update.kind !== "agent_message") return null; const lineage = update.lineage && typeof update.lineage === "object" && !Array.isArray(update.lineage) ? (update.lineage as Record) : null; const sessionId = lineage?.callerSessionId; const turnId = lineage?.callerTurnId; const attemptId = lineage?.callerAttemptId; const executionGeneration = lineage?.callerExecutionGeneration; if ( typeof sessionId !== "string" || typeof turnId !== "string" || typeof attemptId !== "string" || !UUID_PATTERN.test(sessionId) || !UUID_PATTERN.test(turnId) || !UUID_PATTERN.test(attemptId) || typeof executionGeneration !== "number" || !Number.isSafeInteger(executionGeneration) || executionGeneration < 1 ) { return null; } return { sessionId, turnId, attemptId, executionGeneration }; } function systemUpdateCausalExecutionKey( update: Pick, causalExecutionKeys: ReadonlyMap, receivingSessionId: string, ): string | null { const targetTurnId = systemUpdateCausalHumanTurnId(update); if (targetTurnId) { const human = causalExecutionKeys.get(`${receivingSessionId}:${targetTurnId}`); return human ? `target-human:${human}` : `target-turn:${targetTurnId}`; } if ( isChildLifecycleSystemUpdateKind(update.kind) || update.kind === "goal_continuation" || update.kind === "background_command_result" || update.kind === "session_wait_timeout" || update.kind === "capability_setup_completed" || update.kind === "secret_use_approval_decided" ) { // Malformed historical authority-bearing rows still own distinct claims. // They may carry ordinary authority-neutral context, but they must never // borrow another child, goal, or Steer's causal principal. return `${update.kind}-update:${update.id}`; } if (update.kind !== "agent_steer_instruction" && update.kind !== "agent_message") return null; const actor = agentCommandCausalActor(update); if (actor) { if (update.kind === "agent_message") { const human = causalExecutionKeys.get(`${actor.sessionId}:${actor.turnId}`); if (human) return `target-human:${human}`; } return `agent-command:${actor.sessionId}:${actor.turnId}:${actor.attemptId}:${actor.executionGeneration}`; } // A malformed historical agent command still owns a distinct claim. Let its // provenance fallback run without borrowing another authority-bearing // update's causal principal. return `${update.kind}-update:${update.id}`; } function systemUpdatesCanCoalesceForExecution( selected: readonly T[], candidate: T, causalExecutionKeys: ReadonlyMap, receivingSessionId: string, compatAuthority: (update: T) => Readonly> | undefined, ): boolean { const first = selected[0]; if ( !first || systemUpdateExecutionAuthorityKey(first, compatAuthority(first)) !== systemUpdateExecutionAuthorityKey(candidate, compatAuthority(candidate)) ) { return false; } // Steer has first refusal on a batch. Its own caller's messages remain // compatible context, but another caller cannot borrow that command identity. if (first.kind === "agent_steer_instruction" && candidate.kind === "agent_message") { const actor = agentCommandCausalActor(first); return actor !== null && stableJson(actor) === stableJson(agentCommandCausalActor(candidate)); } // Null is compatible context (for example an ordinary notice riding with a // goal continuation). Once a batch contains frozen causal execution, every // further authority-bearing member must have equivalent inherited authority. // Ordinary messages resolve their exact sender turn through the same check; // Steer and unresolved origins keep their existing caller isolation. const selectedCausalKey = selected .map((update) => systemUpdateCausalExecutionKey(update, causalExecutionKeys, receivingSessionId), ) .find((key): key is string => key !== null); const candidateCausalKey = systemUpdateCausalExecutionKey( candidate, causalExecutionKeys, receivingSessionId, ); return ( selectedCausalKey === undefined || candidateCausalKey === null || selectedCausalKey === candidateCausalKey ); } function boundedInternalUpdateEventText( value: string, maxBytes: number, ): { text: string; truncated: boolean; } { if (Buffer.byteLength(value) <= maxBytes) return { text: value, truncated: false }; const suffix = "…"; const bodyBudget = maxBytes - Buffer.byteLength(suffix); const bytes = Buffer.from(value); let text = bytes.subarray(0, bodyBudget).toString("utf8"); if (text.endsWith("\uFFFD")) text = text.slice(0, -1); return { text: `${text}${suffix}`, truncated: true }; } /** * The names of the automations behind these updates, by update id. An * automation run's own summary is its instructions, which only the agent * reads; people see the automation's name. */ async function automationNamesForUpdatesInTransaction( tx: Database, workspaceId: string, updates: readonly Pick[], ): Promise> { const runIds = [ ...new Set( updates.flatMap((update) => update.kind === "scheduled_occurrence" && update.scheduledTaskRunId ? [update.scheduledTaskRunId] : [], ), ), ]; const names = new Map(); if (runIds.length === 0) return names; const rows = await tx .select({ runId: schema.scheduledTaskRuns.id, name: schema.scheduledTasks.name }) .from(schema.scheduledTaskRuns) .innerJoin(schema.scheduledTasks, eq(schema.scheduledTasks.id, schema.scheduledTaskRuns.taskId)) .where( and( eq(schema.scheduledTaskRuns.workspaceId, workspaceId), inArray(schema.scheduledTaskRuns.id, runIds), ), ); const byRun = new Map(rows.map((row) => [row.runId, row.name])); for (const update of updates) { const name = update.scheduledTaskRunId ? byRun.get(update.scheduledTaskRunId) : undefined; if (update.kind === "scheduled_occurrence" && name) names.set(update.id, name); } return names; } function internalUpdateEventMember( update: BoundedSystemUpdate, automationNames?: ReadonlyMap, ) { const automation = update.kind === "scheduled_occurrence" ? automationRunPresentation(update, automationNames?.get(update.id)) : null; const summary = boundedInternalUpdateEventText( // People see what happened; only the agent gets the instructions. automation?.name ?? update.summary, MAX_INTERNAL_UPDATE_EVENT_SUMMARY_BYTES, ); const source = boundedInternalUpdateEventText( update.sourceId, MAX_INTERNAL_UPDATE_EVENT_SOURCE_BYTES, ); const preview = { id: update.id, kind: update.kind, classification: update.classification, sourceId: source.text, sourceIdTruncated: source.truncated, summary: summary.text, summaryTruncated: summary.truncated, }; if (automation) return { ...preview, automation }; if (update.kind !== "media_generation_result") return preview; const payload = SessionSystemUpdatePayload.safeParse(update.payload); return payload.success && payload.data.type === "media_generation_result" ? { ...preview, result: payload.data } : preview; } function systemUpdatesInModelOrder>( updates: readonly T[], ): T[] { // Selection gives Steer first refusal; model context puts the replacement // direction last so an older notice cannot override it. return [ ...updates.filter((update) => update.kind !== "agent_steer_instruction"), ...updates.filter((update) => update.kind === "agent_steer_instruction"), ]; } function selectBoundedSystemUpdateBatch( updates: readonly T[], canCoalesce: (selected: readonly T[], candidate: T) => boolean = () => true, skipIncompatibleCommands = false, ): T[] { const selected: T[] = []; let selectedBytes = 0; for (const update of updates) { if (selected[0] && !canCoalesce(selected, update)) { if (skipIncompatibleCommands && update.kind === "background_command_result") continue; break; } const updateBytes = Buffer.byteLength( JSON.stringify({ id: update.id, kind: update.kind, classification: update.classification, sourceId: update.sourceId, summary: update.summary, payload: update.payload, lineage: update.lineage, }), ); if ( selected.length >= MAX_INTERNAL_UPDATE_BATCH_MEMBERS || // One individually large canonical input must still make progress. The // model/context boundary may reject it explicitly, but the queue cannot // wedge forever merely because the coalescing target is smaller. (selected.length > 0 && selectedBytes + updateBytes > MAX_INTERNAL_UPDATE_BATCH_BYTES) ) { break; } selected.push(update); selectedBytes += updateBytes; } return selected; } function recognizedInboxPayload( update: Pick< typeof schema.sessionSystemUpdates.$inferSelect, "kind" | "payload" | "payloadCodecVersion" >, ): SessionSystemUpdatePayload | null { const parsed = SessionSystemUpdatePayload.safeParse( fromPostgresLosslessJson(update.payload, update.payloadCodecVersion), ); return SessionSystemUpdateKindSchema.safeParse(update.kind).success && parsed.success ? parsed.data : null; } /** Match claim's bounded read before validation, including goal supersession. * Callers retain database ordering; Date would discard timestamp precision. */ function pendingInboxReadWindow( updates: Array, supersedeGoalContinuations: boolean, ) { const steer = updates.find((update) => update.kind === "agent_steer_instruction"); const ordinary = updates .filter( (update) => update.kind !== "agent_steer_instruction" && (!(steer || supersedeGoalContinuations) || update.kind !== "goal_continuation"), ) .slice(0, MAX_INTERNAL_UPDATE_BATCH_MEMBERS + (steer ? 0 : 1)); return steer ? [steer, ...ordinary] : ordinary; } /** Select execution ownership before grouping canonical input; never rewrite producer receipts. */ async function planInboxBatch( tx: Database, session: Pick< typeof schema.sessions.$inferSelect, "id" | "accountId" | "workspaceId" | "executionContextTurnId" >, updates: Array, receivingTurn?: typeof schema.sessionTurns.$inferSelect, ) { const loaded = await loadInboxExecutionContext(tx, { accountId: session.accountId, workspaceId: session.workspaceId, sessionId: session.id, contextTurnId: receivingTurn?.id ?? session.executionContextTurnId, updates, }); // Effective accepted authority per provider holding compatibility records // (empty, and so absent from every key, until a provider's own cutover). const compat = await subscriptionAuthorityCompatForCarriersInTransaction(tx, { workspaceId: session.workspaceId, carriers: [ ...(loaded.context ? [{ kind: "session_turn" as const, id: loaded.context.id }] : []), ...updates.map((update) => ({ kind: "session_system_update" as const, id: update.id })), ], }); const compatOf = (key: string) => (compat.size === 0 ? undefined : (compat.get(key) ?? {})); const updateCompat = (update: typeof schema.sessionSystemUpdates.$inferSelect) => compatOf(`session_system_update:${update.id}`); const compatible = (update: typeof schema.sessionSystemUpdates.$inferSelect) => { if (loaded.eligibleIds.has(update.id)) return true; const context = loaded.context; if ( context && receivingTurn?.metadata.delivery === "steer" && update.kind === "agent_steer_instruction" ) { const actor = inboxOrigin(update, session.id); const origin = actor ? loaded.origins.get(actor.turnId) : undefined; return Boolean( origin && origin.sessionId === actor?.sessionId && !origin.externalLink && turnHuman(origin) && turnHuman(origin) === turnHuman(context), ); } if ( !context || update.scheduledTaskRunId || update.kind === "agent_steer_instruction" || update.kind === "agent_message" || isChildLifecycleSystemUpdateKind(update.kind) ) return false; const human = turnHuman(context); const ownCompat = updateCompat(update); const contextCompat = compatOf(`session_turn:${context.id}`); const contextReceipt = { ...update, personalConnectionDelegations: context.personalConnectionDelegations, mcpAccountBindings: context.mcpAccountBindings, xaiProviderAccountAuthoritySnapshot: context.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: context.claudeProviderAccountAuthoritySnapshot, // A Codex v2 value frozen on the update must equal the context's; an // update that froze none follows the v1 rule above and the delivering // turn copies the receiving context's value. subscriptionAuthority: update.subscriptionAuthority == null ? null : context.subscriptionAuthority, lineage: { connectionAuthoritySubjectId: human, xaiAuthoritySubjectId: human, claudeAuthoritySubjectId: human, }, }; // The provider's effective authority must equal the context's, unless // the update froze no v2 value and is post-receipt work without a record: // like a Codex value it froze none of, it follows the context (the 0608 // fence applies the same rule). const receiptCompat = ownCompat === undefined ? undefined : Object.fromEntries( Object.keys(ownCompat).map((provider) => [ provider, update.subscriptionAuthority == null && isPostReceiptWithoutAuthority(ownCompat[provider]) ? ownCompat[provider] : (contextCompat?.[provider] ?? null), ]), ); const causalKey = systemUpdateCausalExecutionKey(update, loaded.causalKeys, session.id); const ownKey = loaded.causalKeys.get(`${session.id}:${context.id}`); return ( systemUpdateExecutionAuthorityKey(update, ownCompat) === systemUpdateExecutionAuthorityKey(contextReceipt, receiptCompat) && (causalKey === null || (ownKey !== null && causalKey === `target-human:${ownKey}`)) ); }; const receiverOwned = Boolean( receivingTurn || (updates[0] && loaded.context && !loaded.context.externalLink && (loaded.eligibleIds.has(updates[0].id) || // A setup continuation stands in for the person's own "done", and a // secret approval answer for their own "go ahead": like a goal // continuation they run in the person's receiving context. ((updates[0].kind === "goal_continuation" || updates[0].kind === "capability_setup_completed" || updates[0].kind === "secret_use_approval_decided") && compatible(updates[0])))), ); const candidates = receiverOwned && updates[0] && !compatible(updates[0]) ? [] : updates; const selected = selectBoundedSystemUpdateBatch( candidates, (prior, candidate) => receiverOwned ? compatible(candidate) : systemUpdatesCanCoalesceForExecution( prior, candidate, loaded.causalKeys, session.id, updateCompat, ), true, ); const receiver = receiverOwned ? loaded.context : null; return { updates: selected, receiverContext: receiver, selectionNotes: receiver ? agentSelectionNotes(selected, receiver, loaded.origins) : {}, }; } export type ClaimSessionWorkForAttemptInput = { /** Internal worker-build declaration, never request-derived or universally * stamped by createDb. Only builds that always reconstruct the warning opt in. */ filesystemDiscontinuityProtocol?: 1 | 2 | 3 | 4; /** Internal worker-build declaration: this build adds the agent * instructions layer and channel. Without it, a claim of a chat bound to an * agent revision is refused (SQLSTATE 55000, migration 1276). */ agentInstructionsProtocol?: 1; /** Internal worker-build declaration: this build pins organization agent * versions (Instructions layer, tool server logins). Without it, a claim of * a chat with `agent_version` is refused (SQLSTATE 55000, migration 1505). */ orgAgentProtocol?: 1; sessionId: string; workflowId: string; workflowRunId: string; attemptId: string; dispatchId: string; trigger: SessionWorkTrigger; /** Optional worker-owned mutable-authority fence for pending machine inputs. */ validatePendingSystemUpdateAuthority?: ( tx: Database, update: SessionSystemUpdate, ) => Promise<{ action: "accept" } | { action: "reject"; reason: string }>; /** * Worker-owned live account resolution for an inference that continues a * turn with an account intent (goal continuation, wait wake-up, command or * child result, informational input). It resolves the intent exactly as the * person's next message would, against the session's current connectors and * accounts. Without it, the continuation copies the exact earlier accounts. */ resolveContinuedConnectionAccounts?: ( tx: Database, input: { sessionId: string; intent: ConnectionAccountIntent; /** Connector configuration from the session row this claim already locks. * No UI/control/model projection or mutable account authority is reused. */ session: Pick< Session, | "tools" | "toolPolicy" | "resources" | "mcpServers" | "firstPartyMcpTools" | "firstPartyMcpPermissions" | "agent" >; }, ) => Promise<{ mcpAccountBindings: McpConnectionAccountBinding[] | null; personalConnectionDelegations: McpPersonalConnectionDelegation[]; /** Connectors the turn runs without because their account cannot be used. */ gaps?: Array<{ serverId: string; connectionId: string | null; reason: string }>; }>; /** * A requires-action resume first persists its open tool-call result, then * re-enters this exact attempt to attach machine input that arrived while the * session was blocked. The dispatch metadata freezes the session's durable * pending-event sequence at attempt claim; timestamps cannot own this fence * because a producer transaction may wait on the session lock. Keeping this * opt-in prevents an ordinary activity retry from inserting a system message * ahead of the required call/result pair in canonical history. */ attachPendingUpdatesToRunningAttempt?: boolean; }; export type ClaimSessionWorkForAttemptResult = | { action: "claimed"; turn: SessionTurnForExecution } | { action: "unclaimed"; reason: "gate-closed" | "no-work" | "stale-approval" | "control-pending" | "dispatch-expired"; }; function assertSessionGoalFieldBytes(value: string, maxBytes: number, field: string): void { const actualBytes = sessionGoalUtf8Bytes(value); if (actualBytes > maxBytes) { throw new Error(`${field} exceeds ${maxBytes} UTF-8 bytes (received ${actualBytes})`); } } function normalizeAndAssertSessionGoalRootConstraints(values: readonly string[]): string[] { const normalized = normalizeSessionGoalRootConstraints(values); if (normalized.some((value) => value.length === 0)) { throw new Error("goal root constraints must not be blank"); } if (normalized.length > SESSION_GOAL_ROOT_CONSTRAINTS_MAX_ITEMS) { throw new Error( `goal root constraints exceed ${SESSION_GOAL_ROOT_CONSTRAINTS_MAX_ITEMS} items`, ); } for (const value of normalized) { assertSessionGoalFieldBytes( value, SESSION_GOAL_ROOT_CONSTRAINT_MAX_BYTES, "goal root constraint", ); } const aggregateBytes = normalized.reduce( (total, value) => total + sessionGoalUtf8Bytes(value), 0, ); if (aggregateBytes > SESSION_GOAL_ROOT_CONSTRAINTS_MAX_BYTES) { throw new Error( `goal root constraints exceed ${SESSION_GOAL_ROOT_CONSTRAINTS_MAX_BYTES} aggregate UTF-8 bytes (received ${aggregateBytes})`, ); } return normalized; } /** * Bound legacy exact goal content only at the immutable model-context snapshot * boundary. The canonical goal/revision remains byte-for-byte unchanged. */ export function projectSessionGoalPromptField(value: string, maxBytes: number): string { const original = Buffer.from(value, "utf8"); if (original.byteLength <= maxBytes) return value; const marker = `\n[truncated; original UTF-8 bytes=${original.byteLength}]`; const markerBytes = Buffer.byteLength(marker, "utf8"); const prefixBudget = Math.max(0, maxBytes - markerBytes); const decoder = new TextDecoder("utf-8", { fatal: true }); let prefix = ""; for (let end = prefixBudget; end >= Math.max(0, prefixBudget - 3); end -= 1) { try { prefix = decoder.decode(original.subarray(0, end)); break; } catch { // Move to the prior UTF-8 code-point boundary (at most three bytes). } } return `${prefix}${marker}`; } async function goalSnapshotForAcceptedTurnInTransaction( tx: Database, row: typeof schema.sessionTurns.$inferSelect, ): Promise { if (row.goalSnapshot !== null) { return SessionGoalSnapshot.parse(row.goalSnapshot); } // Only rolling-legacy rows can be null. Reconstruct from immutable timeline // evidence at the logical turn's accepted_at boundary, never from the mutable // current goal head. This also freezes an explicit no-goal result. const [lifecycle] = await tx .select({ type: schema.sessionEvents.type, payload: schema.sessionEvents.payload, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, row.workspaceId), eq(schema.sessionEvents.sessionId, row.sessionId), inArray(schema.sessionEvents.type, [ "goal.set", "goal.paused", "goal.resumed", "goal.completed", "goal.cleared", ]), lte(schema.sessionEvents.occurredAt, row.createdAt), ), ) .orderBy(desc(schema.sessionEvents.occurredAt), desc(schema.sessionEvents.sequence)) .limit(1); const [objective] = await tx .select({ payload: schema.sessionEvents.payload }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, row.workspaceId), eq(schema.sessionEvents.sessionId, row.sessionId), // Lifecycle events such as resume intentionally carry no objective // text. Resolve semantics only from full objective-bearing events; // the independent lifecycle query above supplies paused/active state. inArray(schema.sessionEvents.type, ["goal.set", "goal.updated"]), lte(schema.sessionEvents.occurredAt, row.createdAt), ), ) .orderBy(desc(schema.sessionEvents.occurredAt), desc(schema.sessionEvents.sequence)) .limit(1); const capturedAt = row.createdAt.toISOString(); const payload = objective?.payload as Record | undefined; const parsedRootConstraints = SessionGoalRootConstraintsWrite.safeParse( payload?.rootConstraints ?? [], ); const lifecycleType = lifecycle?.type; const state = lifecycleType === "goal.paused" ? "paused" : lifecycleType === "goal.completed" ? "completed" : lifecycleType === "goal.cleared" || !lifecycleType ? "none" : "active"; const snapshot: SessionGoalSnapshot = state === "none" || typeof payload?.goalId !== "string" || typeof payload.text !== "string" || payload.text.length === 0 ? { state: "none", capturedAt } : { state, goalId: payload.goalId, objectiveRevision: typeof payload.objectiveRevision === "number" && Number.isInteger(payload.objectiveRevision) && payload.objectiveRevision > 0 ? payload.objectiveRevision : 1, text: projectSessionGoalPromptField(payload.text, SESSION_GOAL_TEXT_MAX_BYTES), successCriteria: typeof payload.successCriteria === "string" ? projectSessionGoalPromptField( payload.successCriteria, SESSION_GOAL_SUCCESS_CRITERIA_MAX_BYTES, ) : null, rootConstraints: parsedRootConstraints.success ? parsedRootConstraints.data : [], mutationPolicy: payload.mutationPolicy === "review_changes" || payload.mutationPolicy === "autonomous_adaptation" ? payload.mutationPolicy : "preserve_intent", capturedAt, }; await tx .update(schema.sessionTurns) .set({ goalSnapshot: snapshot }) .where( and( eq(schema.sessionTurns.workspaceId, row.workspaceId), eq(schema.sessionTurns.id, row.id), isNull(schema.sessionTurns.goalSnapshot), ), ); row.goalSnapshot = snapshot; return snapshot; } /** * Every child lifecycle payload carries the same `childSessionId`. Deriving the * set from `CHILD_LIFECYCLE_SYSTEM_UPDATE_KINDS` keeps that a compiler fact: a * seventh kind without the field stops compiling here instead of silently * dropping out of the read-fence advance. */ type ChildLifecycleSystemUpdatePayload = Extract< SessionSystemUpdatePayload, { type: ChildLifecycleSystemUpdateKind } >; function isChildLifecycleSystemUpdatePayload( payload: SessionSystemUpdatePayload, ): payload is ChildLifecycleSystemUpdatePayload { return isChildLifecycleSystemUpdateKind(payload.type); } /** * The child sessions a delivered machine-input batch reports on, deduped in * first-delivery order. Keyed on the child lifecycle kind set and never on an * orchestrator/goal shape. Callers pass the payloads the delivery loop already * validated, so no row is parsed twice. */ function consumedChildLifecycleSessionIds( updates: ReadonlyArray, payloadsById: ReadonlyMap, ): ConsumedChildEvidence[] { const children: ConsumedChildEvidence[] = []; for (const update of updates) { if (!isChildLifecycleSystemUpdateKind(update.kind)) continue; const payload = payloadsById.get(update.id); // The row's kind and its payload discriminator are written together; narrow // on the discriminator so the shared field access is typed rather than cast. if (!payload || !isChildLifecycleSystemUpdatePayload(payload)) continue; // An untruncated final answer, and each goal continuation after it, is // exact content of one child answer event; claim still verifies every part // against its retained event before acknowledging. if (payload.type === "child_terminal_result") { const answer = payload.finalAnswer; if (answer && answer.truncated === false) { for (const part of [answer, ...(answer.goalContinuations ?? [])]) { if (part.sequence <= 0 || part.sequence > POSTGRES_INT_MAX) continue; children.push({ sessionId: payload.childSessionId, sequence: part.sequence, type: "turn.completed", payload: { output: part.text }, }); } } } const evidence = payload.childEventEvidence; if (!Array.isArray(evidence) || evidence.length > 32) continue; for (const event of evidence) { if ( event && typeof event === "object" && Number.isSafeInteger(event.sequence) && event.sequence > 0 && event.sequence <= POSTGRES_INT_MAX && typeof event.type === "string" && "payload" in event ) { children.push({ sessionId: payload.childSessionId, sequence: event.sequence, type: event.type, payload: event.payload, }); } } } return children; } type ConsumedChildEvidence = { sessionId: string; sequence: number; type: string; payload: unknown; }; /** * Acknowledge every child whose lifecycle notice this claim just turned into * durable model input, for the receiving turn's frozen initiating human only. * * Only complete immutable event evidence carried in the claimed payload counts. * A terminal status alone does not prove that the parent saw the child's answer. * Pure service turns and legacy notices without content evidence write nothing. * A complete final answer is a cumulative read watermark. Other evidence advances * only a contiguous meaningful prefix. The shared writer preserves newer * personal attention mutations, and never reads the child's current raw cursor * as consumption evidence. Failed/requires_action lifecycle indicators remain. * * This deliberately does NOT touch `attention_version`. That revision exists * only to order explicit human attention mutations against each other, and this * writer publishes no event, NATS invalidation, or sequence advance a browser * could learn from - bumping it would silently invalidate the version the rail * holds and turn the human's next mark-read click into a 409. * * Lock discipline: the claim transaction already owns the canonical workspace → * session → turn → attempt prefix for the PARENT. * * - It takes the `session-personal-state` fence with * `pg_try_advisory_xact_lock_shared` and SKIPS the acknowledgment when the * fence is unavailable. Membership removal (migration 0278) takes that fence * EXCLUSIVELY and BEFORE the workspace/session prefix, so blocking on it here * would invert the canonical order; a non-blocking probe cannot. Honouring the * fence is what keeps this from being the "racing pin writer recreates personal * rows after cleanup" hole 0278 exists to close, and losing the probe is a * clean no-op rather than a partial write - the child simply stays unread, * which is today's behaviour. Shared rather than exclusive because * `listSessionsForSubject` holds the shared counterpart for its whole * rail-list transaction; see the acquisition site for why exclusive would drop * acknowledgments exactly when the human is watching the rail. * - It takes no child turn/attempt lock and no explicit child session lock. * `session_pins` does carry two foreign keys to `sessions`, so each inserted * row does take `FOR KEY SHARE` on the child's session row. That is safe * rather than an inversion: `FOR KEY SHARE` conflicts only with `FOR UPDATE`, * and every canonical session writer takes `FOR NO KEY UPDATE`, which is * compatible with it. * - One statement inserts every child in `ORDER BY id`, matching the UUID lock * ordering the rest of this file uses and the index order migration 0278 * deletes in, so the two cannot deadlock against each other. * * The upsert is monotone: the conflict path re-reads the committed row under its * own row lock and refuses to move a fence backward. * * Current authority is rechecked inside the advisory fence, so historical replay * after membership removal cannot recreate deleted personal state. Frozen turn * provenance identifies the human; the canonical live-authority resolver only * checks that human's still-active shared membership or exact Personal pointer, * and is not used to authorize a caller or grant access. No creator fallback or * request-derived human is accepted. Both RLS policies on `session_pins` still apply through the * temporary subject scope, and the insert is additionally fenced on * `parent_session_id`, so a payload field can never decide whose personal state * is mutated on an unrelated session. */ async function acknowledgeConsumedChildLifecycleNotices( tx: Database, input: { workspaceId: string; sessionId: string; subjectId: string | null; childSessionIds: readonly ConsumedChildEvidence[]; }, ): Promise { const subjectId = input.subjectId?.trim(); if (!subjectId || input.childSessionIds.length === 0) return; // Payloads are evidence, not authority. Verify every complete snapshot against // its immutable child event before accepting the claimed model-input receipt. const proven = new Map(); const grouped = new Map(); for (const evidence of input.childSessionIds) { const group = grouped.get(evidence.sessionId) ?? []; group.push(evidence); grouped.set(evidence.sessionId, group); } for (const [childId, evidence] of grouped) { const events = await tx .select({ sequence: schema.sessionEvents.sequence, type: schema.sessionEvents.type, payload: schema.sessionEvents.payload, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, }) .from(schema.sessionEvents) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.sessionEvents.workspaceId), eq(schema.sessions.id, schema.sessionEvents.sessionId), eq(schema.sessions.parentSessionId, input.sessionId), ), ) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, childId), inArray(schema.sessionEvents.sequence, [ ...new Set(evidence.map((event) => event.sequence)), ]), ), ); const bySequence = new Map( events.map((event) => [event.sequence, logicalChildReadEvent(event)]), ); const sequences = evidence .filter((proof) => { const event = bySequence.get(proof.sequence); // A final answer quotes the event's content, not the `usage` written // with it; a bounded evidence copy carries `usage` on both sides. return ( event?.type === proof.type && isDeepStrictEqual( terminalTurnContentPayload(event.type, event.payload), terminalTurnContentPayload(proof.type, proof.payload), ) ); }) .map((event) => event.sequence); if (sequences.length > 0) proven.set(childId, sequences); } await acknowledgeConsumedChildSequencesInTransaction(tx, { ...input, children: [...proven].map(([sessionId, sequences]) => ({ sessionId, sequences })), }); } /** Internal read receipt. Call only after the complete bounded response has been * constructed and the exact caller attempt's frozen human reauthorized. */ export async function acknowledgeConsumedChildEvents( db: Database, input: { workspaceId: string; sessionId: string; subjectId: string | null; children: readonly { sessionId: string; sequences: readonly number[] }[]; }, ): Promise { await withWorkspaceRls(db, input.workspaceId, async (tx) => { await acknowledgeConsumedChildSequencesInTransaction(tx, input); }); } /** * Turn metadata key recording each direct child answer (`turn.completed` * sequence) that one exact attempt of the turn returned whole to its model * from a read tool, with the model's call id for that read when known. It is * bounded, append-only per turn, and only ever suppresses a duplicate: a lost * or unproven record delivers the child's result normally. */ export const CONSUMED_CHILD_ANSWERS_METADATA_KEY = "consumedChildAnswers"; /** * Turn metadata key recording each direct child answer that a Codemode client * of one exact attempt (for example `ogtool call` in a shell command) received * whole. The read alone proves nothing, since a script may keep the output to * itself: such a record counts only once a tool result in the same turn's * durable history holds that answer as a whole JSON string value, which is the * model's own view of the output. Kept apart from * `CONSUMED_CHILD_ANSWERS_METADATA_KEY` so readers that predate it never take * it for a model read. */ export const CODEMODE_CHILD_ANSWER_READS_METADATA_KEY = "codemodeChildAnswerReads"; const CONSUMED_CHILD_ANSWERS_MAX = 64; const CONSUMED_CHILD_ANSWERS_TURN_WINDOW = 16; /** The model call ids a read record keeps; longer ids are not recorded. */ const CONSUMED_CHILD_ANSWER_CALL_ID_MAX_LENGTH = 512; /** Any hex UUID shape, so a stored attempt id is cast only when castable. */ const UUID_TEXT_PATTERN_SQL = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; type ConsumedChildAnswerEntry = { childSessionId: string; sequence: number; attemptId: string; /** The model's call id of the read whose output carried the answer. */ callId?: string; }; function consumedChildAnswerEntries( metadata: unknown, key: string = CONSUMED_CHILD_ANSWERS_METADATA_KEY, ): ConsumedChildAnswerEntry[] { if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) return []; const entries = (metadata as Record)[key]; if (!Array.isArray(entries)) return []; return entries.filter( (entry): entry is ConsumedChildAnswerEntry => entry !== null && typeof entry === "object" && typeof entry.childSessionId === "string" && typeof entry.attemptId === "string" && Number.isSafeInteger(entry.sequence), ); } /** Every child answer an idle success `child_terminal_result` reports on, or * null when it carries no final answer. */ function childTerminalResultAnswerParts( payload: unknown, ): { childSessionId: string; sequences: number[] } | null { const parsed = SessionSystemUpdatePayload.safeParse(payload); if ( !parsed.success || parsed.data.type !== "child_terminal_result" || parsed.data.status !== "idle" || !parsed.data.finalAnswer ) { return null; } return { childSessionId: parsed.data.childSessionId, sequences: childTerminalResultFinalAnswerSequences(parsed.data.finalAnswer), }; } /** * The child answers the parent's model received whole, per child. A record * counts when its recording attempt completed its turn: the tool output that * carried the answer is then durable parent history. The parent's newest * completed turns hold such records (a child commits its result seconds after * the answer); a record outside that window, like a lost one, only means the * result is delivered normally. `attempt` also counts the records one exact * attempt made on its own turn: its caller proves that attempt is live, or has * just completed its turn in the same transaction. * * A turn can outlive the attempt that read: a provider interruption, worker * restart or Retry continues the same turn in a new attempt, which resumes * from the turn's durable history. A record by such an earlier attempt counts * once that history holds the read's own tool result (by the model's call id): * every later attempt of the turn received it. Without that result in history, * a record of an attempt that failed, was interrupted, or was replaced proves * nothing. * * A Codemode read (`CODEMODE_CHILD_ANSWER_READS_METADATA_KEY`) never counts by * its attempt: the script that made it may have returned only a summary. It * counts when a tool result in the same turn's durable history holds the * child's whole answer as a JSON string value, as the model received it: once * escaped (the read's own JSON, for example after `jq -r '.content[0].text'`) * or twice (the tool result as `ogtool call` prints it). Text that only * contains the answer, or an answer printed some other way, proves nothing and * the result is delivered normally. */ async function consumedChildAnswerSequencesTx( tx: Database, input: { workspaceId: string; parentSessionId: string; childSessionIds: readonly string[]; attempt?: { turnId: string; attemptId: string }; }, ): Promise>> { const consumed = new Map>(); const childSessionIds = [...new Set(input.childSessionIds)].filter((id) => UUID_PATTERN.test(id)); if (childSessionIds.length === 0) return consumed; const attempt = input.attempt && UUID_PATTERN.test(input.attempt.turnId) && UUID_PATTERN.test(input.attempt.attemptId) ? input.attempt : null; const key = CONSUMED_CHILD_ANSWERS_METADATA_KEY; const codemodeKey = CODEMODE_CHILD_ANSWER_READS_METADATA_KEY; const turns = sql`(select recent.id, recent.metadata from session_turns recent where recent.workspace_id = ${input.workspaceId}::uuid and recent.session_id = ${input.parentSessionId}::uuid and recent.status = 'completed' order by recent.position desc limit ${CONSUMED_CHILD_ANSWERS_TURN_WINDOW}) ${ attempt ? sql`union (select own.id, own.metadata from session_turns own where own.workspace_id = ${input.workspaceId}::uuid and own.session_id = ${input.parentSessionId}::uuid and own.id = ${attempt.turnId}::uuid)` : sql`` }`; const childSessionIdList = sql.join( childSessionIds.map((id) => sql`${id}`), sql`, `, ); const rows = await rawRows<{ childSessionId: string; sequence: string | number }>( tx, sql`with turn as (${turns}) select entry ->> 'childSessionId' as "childSessionId", (entry ->> 'sequence')::numeric as sequence from turn cross join lateral jsonb_array_elements( case when jsonb_typeof(turn.metadata -> ${key}) = 'array' then turn.metadata -> ${key} else '[]'::jsonb end ) as entry join session_turn_attempts attempt on attempt.workspace_id = ${input.workspaceId}::uuid and attempt.session_id = ${input.parentSessionId}::uuid and attempt.turn_id = turn.id and attempt.id = case when entry ->> 'attemptId' ~ ${UUID_TEXT_PATTERN_SQL} then (entry ->> 'attemptId')::uuid end where entry ->> 'childSessionId' in (${childSessionIdList}) and jsonb_typeof(entry -> 'sequence') = 'number' and (attempt.outcome = 'completed'${ attempt ? sql` or (turn.id = ${attempt.turnId}::uuid and attempt.id = ${attempt.attemptId}::uuid)` : sql`` } or (jsonb_typeof(entry -> 'callId') = 'string' and exists ( select 1 from session_history_items carried where carried.workspace_id = ${input.workspaceId}::uuid and carried.session_id = ${input.parentSessionId}::uuid and carried.turn_id = turn.id and carried.item_ordered ->> 'type' = 'function_call_result' and carried.item_ordered ->> 'callId' = entry ->> 'callId'))) union all select entry ->> 'childSessionId' as "childSessionId", (entry ->> 'sequence')::numeric as sequence from turn cross join lateral jsonb_array_elements( case when jsonb_typeof(turn.metadata -> ${codemodeKey}) = 'array' then turn.metadata -> ${codemodeKey} else '[]'::jsonb end ) as entry -- Bind the validated identity before probing the event index. Without -- these fences, RLS can leave the identity as a join filter after a -- workspace-wide scan of completed turns. join lateral ( select answer.payload from session_events answer where answer.workspace_id = ${input.workspaceId}::uuid and answer.session_id = (select case when entry ->> 'childSessionId' ~ ${UUID_TEXT_PATTERN_SQL} then (entry ->> 'childSessionId')::uuid end offset 0) and answer.sequence = (select case when entry ->> 'sequence' ~ '^[0-9]{1,9}$' then (entry ->> 'sequence')::integer end offset 0) and answer.type = 'turn.completed' and jsonb_typeof(answer.payload -> 'output') = 'string' and answer.payload ->> 'output' <> '' offset 0 ) answer on true -- The answer as a JSON string value, escaped once more for each layer -- of JSON it can sit in inside a stored tool result. cross join lateral (select to_json(to_json(answer.payload ->> 'output')::text)::text as quoted) once_quoted cross join lateral (select substr(once_quoted.quoted, 2, length(once_quoted.quoted) - 2) as text) escaped_once cross join lateral (select substr(to_json(escaped_once.text)::text, 2, length(to_json(escaped_once.text)::text) - 2) as text) escaped_twice where entry ->> 'childSessionId' in (${childSessionIdList}) and exists ( select 1 from session_history_items carried where carried.workspace_id = ${input.workspaceId}::uuid and carried.session_id = ${input.parentSessionId}::uuid and carried.turn_id = turn.id and carried.item_ordered ->> 'type' = 'function_call_result' and (strpos(carried.item_ordered::text, escaped_once.text) > 0 or strpos(carried.item_ordered::text, escaped_twice.text) > 0))`, ); for (const row of rows) { const sequences = consumed.get(row.childSessionId) ?? new Set(); sequences.add(Number(row.sequence)); consumed.set(row.childSessionId, sequences); } return consumed; } function childResultConsumed( parts: { childSessionId: string; sequences: readonly number[] }, consumed: ReadonlyMap>, ): boolean { const sequences = consumed.get(parts.childSessionId); return sequences !== undefined && parts.sequences.every((sequence) => sequences.has(sequence)); } /** * Whether the parent's model already received every part of this successful * idle child result (the answer and each goal continuation it reports on) * whole, through a read by an attempt that completed its turn. Such a result is * inserted already consumed. A result that arrives while the reading attempt * still runs is inserted pending; that attempt's completion supersedes it. */ async function childTerminalResultConsumedByParentReadTx( tx: Database, input: { workspaceId: string; parentSessionId: string; payload: unknown }, ): Promise { const parts = childTerminalResultAnswerParts(input.payload); if (!parts) return false; return childResultConsumed( parts, await consumedChildAnswerSequencesTx(tx, { workspaceId: input.workspaceId, parentSessionId: input.parentSessionId, childSessionIds: [parts.childSessionId], }), ); } /** Ids of this parent's pending idle child results its model already received * whole (see `consumedChildAnswerSequencesTx`). */ async function pendingChildResultsConsumedTx( tx: Database, input: { workspaceId: string; parentSessionId: string; attempt?: { turnId: string; attemptId: string }; }, ): Promise { const pending = await tx .select({ id: schema.sessionSystemUpdates.id, payload: schema.sessionSystemUpdates.payload, payloadCodecVersion: schema.sessionSystemUpdates.payloadCodecVersion, }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.parentSessionId), eq(schema.sessionSystemUpdates.kind, "child_terminal_result"), eq(schema.sessionSystemUpdates.state, "pending"), eq(schema.sessionSystemUpdates.classification, "success"), ), ); const candidates = pending.flatMap((row) => { const parts = childTerminalResultAnswerParts( fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), ); return parts ? [{ id: row.id, parts }] : []; }); if (candidates.length === 0) return []; const consumed = await consumedChildAnswerSequencesTx(tx, { workspaceId: input.workspaceId, parentSessionId: input.parentSessionId, childSessionIds: candidates.map((candidate) => candidate.parts.childSessionId), ...(input.attempt ? { attempt: input.attempt } : {}), }); return candidates .filter((candidate) => childResultConsumed(candidate.parts, consumed)) .map((candidate) => candidate.id) .sort(); } /** * Inside the successful completion settlement of a turn that recorded a * consumed child answer, by this attempt or an earlier attempt of the same * turn: supersede each still-pending idle child result the parent's model has * now received whole, before the next claim could start an inference that only * repeats it. The tool output that carried each answer is durable history once * the attempt completes (see `consumedChildAnswerSequencesTx`). The canonical * row stays as audit truth; the caller appends the `system.update.cancelled` * event. */ async function supersedeChildResultsConsumedByCompletedAttemptTx( tx: Database, input: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; turnMetadata: unknown; }, ): Promise { if ( consumedChildAnswerEntries(input.turnMetadata).length === 0 && consumedChildAnswerEntries(input.turnMetadata, CODEMODE_CHILD_ANSWER_READS_METADATA_KEY) .length === 0 ) return []; const consumed = await pendingChildResultsConsumedTx(tx, { workspaceId: input.workspaceId, parentSessionId: input.sessionId, attempt: { turnId: input.turnId, attemptId: input.attemptId }, }); if (consumed.length === 0) return []; await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "pending"), inArray(schema.sessionSystemUpdates.id, consumed), ), ); return consumed; } /** * The parent's exact live attempt has just returned a direct child's complete * final answer to its model from a read tool. Record each such result-bearing * answer on the reading turn (`CONSUMED_CHILD_ANSWERS_METADATA_KEY`). Nothing * is superseded here: the tool output is not durable parent history until the * attempt completes its turn. That completion supersedes each still-pending * idle result whose every part was received, and a result that arrives after * it is inserted already consumed. A read by an attempt that then fails, is * interrupted, or is replaced suppresses nothing. * * The caller proves the read returned whole content to the model; this proves * the attempt is still the session's current one and that each sequence is a * direct child's result-bearing answer. A read whose answers this attempt * already recorded writes nothing. `callId` is the model's id for the reading * tool call; it lets a later attempt of the same turn, resuming from the * turn's durable history, prove it holds the read's output too. Metadata * writes take the canonical session prefix: the archive guard on a turn UPDATE * also locks its session, so taking only the turn first would invert * claim/settlement and parallel tool writers. It is best effort: a busy * ownership row skips it and the result is then delivered normally. * * `via: "codemode"` records a read a Codemode client of the attempt made * (`CODEMODE_CHILD_ANSWER_READS_METADATA_KEY`). The caller cannot prove that * output reached the model, so such a record counts only when the turn's * durable history shows it did (see `consumedChildAnswerSequencesTx`). */ export async function recordConsumedChildAnswers( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; callId?: string; via?: "model" | "codemode"; children: readonly { sessionId: string; sequences: readonly number[] }[]; }, ): Promise<{ recorded: number }> { const metadataKey = input.via === "codemode" ? CODEMODE_CHILD_ANSWER_READS_METADATA_KEY : CONSUMED_CHILD_ANSWERS_METADATA_KEY; const callId = input.via !== "codemode" && typeof input.callId === "string" && input.callId.length > 0 && input.callId.length <= CONSUMED_CHILD_ANSWER_CALL_ID_MAX_LENGTH ? input.callId : undefined; const children = input.children .map((child) => ({ sessionId: child.sessionId, sequences: [ ...new Set( child.sequences.filter( (value) => Number.isSafeInteger(value) && value > 0 && value <= POSTGRES_INT_MAX, ), ), ], })) .filter((child) => UUID_PATTERN.test(child.sessionId) && child.sequences.length > 0); if ( children.length === 0 || !UUID_PATTERN.test(input.sessionId) || !UUID_PATTERN.test(input.turnId) || !UUID_PATTERN.test(input.attemptId) ) { return { recorded: 0 }; } // Most complete reads return no child answer, and a repeated read returns // one this attempt already recorded. Decide both without any lock. const probe = await withWorkspaceRls(db, input.workspaceId, async (tx) => { const answers = await tx .select({ sessionId: schema.sessionEvents.sessionId, sequence: schema.sessionEvents.sequence, }) .from(schema.sessionEvents) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.sessionEvents.workspaceId), eq(schema.sessions.id, schema.sessionEvents.sessionId), eq(schema.sessions.parentSessionId, input.sessionId), ), ) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), inArray( schema.sessionEvents.sessionId, children.map((child) => child.sessionId), ), eq(schema.sessionEvents.type, "turn.completed"), inArray(schema.sessionEvents.sequence, [ ...new Set(children.flatMap((child) => child.sequences)), ]), // Only a returned result-bearing answer proves consumption; a // commentary message or goal fact read alongside it does not. completeMeaningfulSessionEventSql("session_events"), ), ); const [turn] = await tx .select({ metadata: schema.sessionTurns.metadata }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), ), ) .limit(1); return { answers, metadata: turn?.metadata }; }); const readByChild = new Map(children.map((child) => [child.sessionId, child.sequences])); const unrecorded = (metadata: unknown) => { const recorded = consumedChildAnswerEntries(metadata, metadataKey); return probe.answers .map((answer) => ({ childSessionId: answer.sessionId, sequence: Number(answer.sequence) })) .filter( (answer) => readByChild.get(answer.childSessionId)?.includes(answer.sequence) === true && !recorded.some( (entry) => entry.attemptId === input.attemptId && entry.childSessionId === answer.childSessionId && entry.sequence === answer.sequence, ), ); }; if (unrecorded(probe.metadata).length === 0) return { recorded: 0 }; try { return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { // A request-scoped writer never waits long on the ownership rows. await tx.execute( sql`select set_config('lock_timeout', ${`${Math.max(1, workspaceControlRequestLockTimeoutMs())}ms`}, true)`, ); // 0560's BEFORE UPDATE archive guard takes the session NO KEY UPDATE // lock after PostgreSQL has locked the turn. Own that prefix first, // including the cursor, to avoid session <-> turn inversion against // pending results, event appends, system-update claim and settlement. const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); const turn = locks.turns[0]; if (!turn || turn.accountId !== input.accountId || turn.sessionId !== input.sessionId) return { recorded: 0 }; const [current] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.sessionTurnAttempts.workspaceId), eq(schema.sessions.id, schema.sessionTurnAttempts.sessionId), eq(schema.sessions.activeTurnId, input.turnId), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.turnId, input.turnId), eq(schema.sessionTurnAttempts.id, input.attemptId), eq(schema.sessionTurnAttempts.executionGeneration, input.executionGeneration), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); if (!current) return { recorded: 0 }; const newlyRecorded = unrecorded(turn.metadata).map((answer) => ({ ...answer, attemptId: input.attemptId, ...(callId ? { callId } : {}), })); if (newlyRecorded.length === 0) return { recorded: 0 }; // Under the turn row lock: only this key changes, the rest of the // turn metadata stays exactly as committed. const entries = [ ...consumedChildAnswerEntries(turn.metadata, metadataKey), ...newlyRecorded, ].slice(-CONSUMED_CHILD_ANSWERS_MAX); await tx .update(schema.sessionTurns) .set({ metadata: sql`jsonb_set(coalesce(${schema.sessionTurns.metadata}, '{}'::jsonb), ${`{${metadataKey}}`}::text[], ${JSON.stringify(entries)}::jsonb)`, }) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), ), ); return { recorded: newlyRecorded.length }; }), ); } catch (error) { if (nestedPostgresSqlState(error) === "55P03") return { recorded: 0 }; throw error; } } /** * This session's pending machine input, less each idle child result its model * already received whole: through a completed turn, or through a read by the * given exact live attempt, whose completion will supersede it. Such a result * would only repeat an answer the caller holds, so it is not input to wait for. */ export async function listOutstandingSessionSystemUpdatesForAttempt( db: Database, workspaceId: string, sessionId: string, attempt: { turnId: string; attemptId: string }, ): Promise { const pending = await listOutstandingSessionSystemUpdates(db, workspaceId, sessionId); if (!pending.some((update) => update.kind === "child_terminal_result")) return pending; const consumed = new Set( await withWorkspaceRls( db, workspaceId, async (tx) => await pendingChildResultsConsumedTx(tx, { workspaceId, parentSessionId: sessionId, attempt, }), ), ); return pending.filter((update) => !consumed.has(update.id)); } /** Bounded operator reconciliation, dry-run by default. No timestamps, session * creator or latest human are evidence of consumption. Unrecognized historical * providers/Codemode layouts remain untouched rather than guessed. */ export async function reconcileHistoricalChildReadAcknowledgments( db: Database, input: { workspaceId: string; parentSessionId: string; afterSequence?: number; limit?: number; apply?: boolean; }, ): Promise<{ scanned: number; provenEvents: number; unsupportedReceipts: number; nextAfter: number; hasMore: boolean; applied: boolean; }> { const limit = Math.max(1, Math.min(100, input.limit ?? 50)); return await withWorkspaceRls(db, input.workspaceId, async (tx) => { const outputs = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.parentSessionId), eq(schema.sessionEvents.type, "agent.toolCall.output"), gt(schema.sessionEvents.sequence, input.afterSequence ?? 0), isNull(schema.sessionEvents.duplicateOfEventId), eq(schema.sessionEvents.turnAssociation, "current"), sql`octet_length(${schema.sessionEvents.payload}::text) <= 262144`, ), ) .orderBy(asc(schema.sessionEvents.sequence)) .limit(limit + 1); let provenEvents = 0; let unsupportedReceipts = 0; for (const output of outputs.slice(0, limit)) { const payload = logicalChildReadEvent(output).payload as Record | null; if (!output.turnId || !payload || typeof payload.id !== "string" || payload.truncation) { unsupportedReceipts += 1; continue; } const [turn] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.parentSessionId), eq(schema.sessionTurns.id, output.turnId), ), ) .limit(1); const subjectId = turn?.initiatingHumanSubjectId ?? (turn?.initiatorKind === "subject" ? turn.initiatorSubjectId : null); if (!subjectId) { unsupportedReceipts += 1; continue; } const calls = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.parentSessionId), eq(schema.sessionEvents.turnId, output.turnId), eq(schema.sessionEvents.type, "agent.toolCall.created"), eq(schema.sessionEvents.turnAssociation, "current"), isNull(schema.sessionEvents.duplicateOfEventId), lt(schema.sessionEvents.sequence, output.sequence), sql`${schema.sessionEvents.payload} ->> 'id' = ${payload.id}`, sql`octet_length(${schema.sessionEvents.payload}::text) <= 16384`, ), ) .limit(2); if (calls.length !== 1) { unsupportedReceipts += 1; continue; } const call = logicalChildReadEvent(calls[0]!).payload as Record; const candidates = historicalChildReadItems(call.name, call.arguments, payload.output); const proven: ConsumedChildEvidence[] = []; for (const candidate of candidates.slice(0, 100)) { if ( !UUID_PATTERN.test(candidate.sessionId) || !Number.isSafeInteger(candidate.item.sequence) || (candidate.item.sequence as number) < 1 || (candidate.item.sequence as number) > POSTGRES_INT_MAX ) continue; const [source] = await tx .select({ event: schema.sessionEvents }) .from(schema.sessionEvents) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, schema.sessionEvents.workspaceId), eq(schema.sessions.id, schema.sessionEvents.sessionId), eq(schema.sessions.parentSessionId, input.parentSessionId), ), ) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, candidate.sessionId), eq(schema.sessionEvents.sequence, candidate.item.sequence as number), completeMeaningfulSessionEventSql("session_events"), sql`octet_length(${schema.sessionEvents.payload}::text) <= 262144`, ), ) .limit(1); if (!source) continue; const logicalEvent = logicalChildReadEvent(source.event); if (!historicalChildReadMatches(candidate, logicalEvent)) continue; proven.push({ sessionId: candidate.sessionId, sequence: source.event.sequence, type: source.event.type, payload: logicalEvent.payload, }); } if (proven.length === 0) unsupportedReceipts += 1; provenEvents += proven.length; if (input.apply && proven.length > 0) { await acknowledgeConsumedChildLifecycleNotices(tx, { workspaceId: input.workspaceId, sessionId: input.parentSessionId, subjectId, childSessionIds: proven, }); } } return { scanned: Math.min(limit, outputs.length), provenEvents, unsupportedReceipts, nextAfter: outputs[Math.min(limit, outputs.length) - 1]?.sequence ?? input.afterSequence ?? 0, hasMore: outputs.length > limit, applied: input.apply === true, }; }); } async function acknowledgeConsumedChildSequencesInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; subjectId: string | null; children: readonly { sessionId: string; sequences: readonly number[] }[]; }, ): Promise { const subjectId = input.subjectId?.trim(); if (!subjectId || input.children.length === 0) return; // SHARED, not exclusive. `listSessionsForSubject` holds the shared counterpart // of this fence for its whole rail-list transaction, and that list refreshes on // focus, online, and visibilitychange. An exclusive probe fails against a held // shared lock, so it would drop acknowledgments precisely while the human is // looking at the rail, and because `child_terminal_result` is typically a // child's LAST notice, a drop there leaves exactly the permanent blue dot this // exists to remove. Shared still conflicts with membership removal's exclusive // hold, which is the invariant the fence is here for, and acknowledgment // writers need no mutual exclusion against each other: the upsert is monotone // and row-locked. const [fence] = await rawRows<{ acquired: boolean }>( tx, sql`select pg_try_advisory_xact_lock_shared( hashtextextended(${sessionPersonalStateLockKey(input.workspaceId, subjectId)}, 0) ) as acquired`, ); if (!fence?.acquired) return; const pins = schema.sessionPins; const sessions = schema.sessions; await withTemporarySubjectRls(tx, subjectId, async () => { if ( !(await subjectHasLiveWorkspaceAuthorityInScope(tx, { accountId: await accountIdInRlsScope(tx), workspaceId: input.workspaceId, subjectId, })) ) return; // Stable UUID order preserves the personal-row lock order. A complete final // answer summarizes earlier work; nonfinal filtered reads cannot skip holes. for (const child of [...input.children].sort((a, b) => a.sessionId.localeCompare(b.sessionId), )) { const requested = [ ...new Set( child.sequences.filter( (value) => Number.isSafeInteger(value) && value > 0 && value <= POSTGRES_INT_MAX, ), ), ]; if (requested.length === 0) continue; const events = await tx .select({ sequence: schema.sessionEvents.sequence, type: schema.sessionEvents.type }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, child.sessionId), inArray(schema.sessionEvents.sequence, requested), completeMeaningfulSessionEventSql("session_events"), ), ); const sequences = events.map((event) => event.sequence); if (sequences.length === 0) continue; // status-only reads do not acknowledge const through = Math.max(...sequences); const finalThrough = Math.max( 0, ...events.filter((event) => event.type === "turn.completed").map((event) => event.sequence), ); await tx.execute(sql` insert into ${pins} ( account_id, workspace_id, subject_id, session_id, pinned, pinned_at, version, acknowledged_sequence, actively_working, attention_version, archived, archived_at, archive_version ) select ${sessions.accountId}, ${sessions.workspaceId}, ${subjectId}, ${sessions.id}, -- An acknowledgment is not a pin and not an archive. Both domains stay -- at the absent-row projection so a concurrent pin/archive writer -- holding that projection stays valid. false, null, 0, least(${through}, coalesce(( select min(unseen.sequence) - 1 from session_events unseen where unseen.workspace_id = ${sessions.workspaceId} and unseen.session_id = ${sessions.id} and unseen.sequence > greatest( coalesce(personal.acknowledged_sequence, 0), coalesce(personal.manually_unread_through, 0), ${finalThrough}) and unseen.sequence <= ${through} and ${meaningfulSessionEventSql("unseen")} and unseen.sequence not in (${sql.join( sequences.map((sequence) => sql`${sequence}`), sql`, `, )}) ), ${through})), false, 0, false, null, 0 from ${sessions} left join ${pins} personal on personal.workspace_id = ${sessions.workspaceId} and personal.session_id = ${sessions.id} and personal.subject_id = ${subjectId} where ${and( eq(sessions.workspaceId, input.workspaceId), eq(sessions.parentSessionId, input.sessionId), eq(sessions.id, child.sessionId), )} and (personal.manually_unread_through is null or ${through} > personal.manually_unread_through) order by ${sessions.id} on conflict (subject_id, workspace_id, session_id) do update set acknowledged_sequence = excluded.acknowledged_sequence, manually_unread_through = null where ${pins.acknowledgedSequence} < excluded.acknowledged_sequence and (${pins.manuallyUnreadThrough} is null or excluded.acknowledged_sequence > ${pins.manuallyUnreadThrough}) `); } }); } /** * Scope the worker-build declarations (filesystem discontinuity and agent * instructions protocols) to registration, including nested claims. One * statement reads the prior values, one sets them and one restores them. */ async function withSandboxRecoveryWarningClaimProtocol( tx: Database, version: 1 | 2 | 3 | 4 | undefined, agentInstructionsVersion: 1 | undefined, register: () => Promise, orgAgentVersion?: 1, ): Promise { const [prior] = await rawRows<{ consent_protocol: string; automatic_protocol: string; fresh_protocol: string; explicit_protocol: string; agent_instructions_protocol: string; org_agent_protocol: string; }>( tx, sql`select coalesce(current_setting('opengeni.filesystem_discontinuity_protocol_v1', true), '') as consent_protocol, coalesce(current_setting('opengeni.filesystem_discontinuity_protocol_v2', true), '') as automatic_protocol, coalesce(current_setting('opengeni.filesystem_discontinuity_protocol_v3', true), '') as fresh_protocol, coalesce(current_setting('opengeni.filesystem_discontinuity_protocol_v4', true), '') as explicit_protocol, coalesce(current_setting('opengeni.agent_instructions_protocol_v1', true), '') as agent_instructions_protocol, coalesce(current_setting('opengeni.org_agent_protocol_v1', true), '') as org_agent_protocol`, ); // Each protocol version reconstructs every earlier warning kind as well. await tx.execute( sql`select set_config('opengeni.filesystem_discontinuity_protocol_v1', ${version === 1 || version === 2 || version === 3 || version === 4 ? "1" : ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v2', ${version === 2 || version === 3 || version === 4 ? "2" : ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v3', ${version === 3 || version === 4 ? "3" : ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v4', ${version === 4 ? "4" : ""}, true), set_config('opengeni.agent_instructions_protocol_v1', ${agentInstructionsVersion === 1 ? "1" : ""}, true), set_config('opengeni.org_agent_protocol_v1', ${orgAgentVersion === 1 ? "1" : ""}, true)`, ); let completed = false; try { const result = await register(); completed = true; return result; } finally { const restore = tx.execute( sql`select set_config('opengeni.filesystem_discontinuity_protocol_v1', ${prior?.consent_protocol ?? ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v2', ${prior?.automatic_protocol ?? ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v3', ${prior?.fresh_protocol ?? ""}, true), set_config('opengeni.filesystem_discontinuity_protocol_v4', ${prior?.explicit_protocol ?? ""}, true), set_config('opengeni.agent_instructions_protocol_v1', ${prior?.agent_instructions_protocol ?? ""}, true), set_config('opengeni.org_agent_protocol_v1', ${prior?.org_agent_protocol ?? ""}, true)`, ); if (completed) await restore; else await restore.catch(() => undefined); // Claim savepoint rolls back a rejected INSERT. } } /** The session lock must already be held. Shared with pre-claim failure settlement * so a failed batch claim is attributed to the same logical turn. * * On a personal machine, messages from anyone but its owner wait * (`machine-owner-wait.ts`): they are never the head. `waiting` returns the * ones sent before the owner's claimed head (queued ahead of it, or sent * before an owner's Steer that jumped them), oldest first, which that turn * takes in as context ahead of its own prompt. */ async function selectQueuedSessionClaimBatch( tx: Database, session: typeof schema.sessions.$inferSelect, pendingAgentSteer: boolean, ): Promise<{ batch: Array; waiting: Array; }> { const machineOwner = await sessionMachineOwnerSubject(tx, { accountId: session.accountId, workspaceId: session.workspaceId, sessionId: session.id, }); const waits = machineOwner === null ? sql`false` : sql`coalesce(${waitsForMachineOwnerSql(machineOwner)}, false)`; // Only fetch full prompt/authority rows for the leading Steer run (or the // ordinary head). A long queue of later Sends must not inflate claim memory. // Waiting messages break that run, and only those sent before the head are // taken in with it. const previews = await rawRows<{ id: string; version: number; waits: boolean }>( tx, sql` with candidates as ( select id, version, position, created_at, ${waits} as waits, metadata->>'delivery' is distinct from 'steer' as send from session_turns where workspace_id = ${session.workspaceId} and session_id = ${session.id} and status = 'queued' and source in ('user', 'api') and (${pendingAgentSteer} = false or metadata->>'delivery' = 'steer') ), ordered as ( select id, version, position, created_at, waits, count(*) filter (where not waits) over run as runnable, count(*) filter (where not waits and send) over run as sends, count(*) filter (where waits) over run as waited from candidates window run as (order by position, created_at, id rows unbounded preceding) ), head as ( select waited, created_at from ordered where not waits and runnable = 1 ) select id, version, waits from ordered where exists (select 1 from head) and ( (waits and (runnable = 0 or created_at < (select created_at from head))) or (not waits and runnable = 1) or (not waits and sends = 0 and waited = (select waited from head))) order by position, created_at, id`, ); if (previews.length === 0) return { batch: [], waiting: [] }; const locked = await lockSessionEventWriteRows(tx, { workspaceId: session.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: previews.map((turn) => turn.id), }); const lockedById = new Map(locked.turns.map((turn) => [turn.id, turn])); const rows = previews.map((preview) => { const turn = lockedById.get(preview.id); if ( !turn || turn.accountId !== session.accountId || turn.sessionId !== session.id || turn.status !== "queued" || turn.version !== preview.version ) { throw new SessionControlInvariantError( "Queued claim selection changed under the session lock", ); } return { turn, waits: preview.waits === true }; }); const queued = rows.filter((row) => !row.waits).map((row) => row.turn); const first = queued[0]; if (!first) return { batch: [], waiting: [] }; const plainSteer = (turn: typeof first) => turn.metadata?.delivery === "steer" && turn.executionGeneration === 0 && turn.activeAttemptId === null && turn.startedAt === null && turn.scheduledTaskRunId === null && !isSessionRealtimeDelegationTurnMetadata(turn.metadata) && Array.isArray(turn.resources) && turn.resources.length === 0 && turn.personalResourceAttachmentSummary === null; const batch = [first]; // Validate before adding another member: a corrupt member must remain the // target of the ordinary claim/failure path, not fail an unrelated last row. const validHistory = (turn: typeof first) => { try { const dispatch = readTurnDispatchMetadata(turn.metadata); if (dispatch.kind === "malformed" || dispatch.generation >= Number.MAX_SAFE_INTEGER) return false; TimelineAnnotations.parse(turn.annotations); if (turn.goalSnapshot !== null) SessionGoalSnapshot.parse(turn.goalSnapshot); fromPostgresLosslessText(turn.prompt, turn.promptCodecVersion); return true; } catch { return false; } }; for (const next of queued.slice(1)) { if ( !plainSteer(batch[batch.length - 1]!) || !validHistory(batch[batch.length - 1]!) || !plainSteer(next) || next.initiatorKind !== first.initiatorKind || next.initiatorSubjectId !== first.initiatorSubjectId || next.initiatingHumanSubjectId !== first.initiatingHumanSubjectId || stableJson(next.initiatorContext) !== stableJson(first.initiatorContext) ) break; batch.push(next); } // A waiting message whose history cannot be rendered stays queued rather // than failing the owner's claim. const waiting = rows .filter((row) => row.waits && validHistory(row.turn)) .map((row) => row.turn) .sort( (left, right) => left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id), ); return { batch, waiting }; } /** * Claim and register one inference attempt after a turn worker has accepted the * Temporal activity. This is the only transition into `running`: queue choice, * execution generation, active attempt identity, dispatch identity, and the * session's public state commit atomically under the workspace/session lock. */ export async function claimSessionWorkForAttempt( db: Database, workspaceId: string, input: ClaimSessionWorkForAttemptInput, ): Promise { const { sessionId, workflowId } = input; return await retrySessionActivityRls( db, workspaceId, { stage: "session_attempts.claim", eventTypes: ["session.turn.attempt_claimed"], maxAttempts: 3, // No organization-membership fence, not even shared: the claim never // takes that key (no trigger or function it reaches does since the // host-MCP authority writers were retired), so it cannot invert the // membership -> tenancy -> control -> session prefix. A membership // removal racing a claim is caught at execution time: workspace-writer // admission, connection and MCP authority revalidate live membership. }, async (scopedDb) => await withSessionActivitySavepoint(scopedDb, async (tx) => { const deliverPendingUpdates = async ( accountId: string, turnId: string, turnGeneration: number, nextSequence: number, occurredAt: Date, triggerEventId?: string, options: { supersedeGoalContinuations?: boolean; deliverUpdates?: boolean; pendingEventSequenceBeforeOrAt?: number; commandOnlyMayRun?: boolean; receivingTurn?: typeof schema.sessionTurns.$inferSelect; } = {}, ): Promise<{ receiverContext: typeof schema.sessionTurns.$inferSelect | null; selectionNotes: Record; count: number; lastSequence: number; triggerEventId: string | null; historyItemId: string | null; historyItem: Record | null; /** Durable delivery time written to every delivered member. */ deliveredAt: Date; updates: Array; /** Deduped children the delivered batch reports on, in delivery order. */ childSessionIds: ConsumedChildEvidence[]; events: SessionEventInsertWithPayload[]; event: SessionEventInsertWithPayload | null; }> => { const withinPendingUpdateBoundary = options.pendingEventSequenceBeforeOrAt === undefined ? undefined : exists( tx .select({ value: sql`1` }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.type, "system.update.pending"), lte(schema.sessionEvents.sequence, options.pendingEventSequenceBeforeOrAt), sql`${schema.sessionEvents.payload} ->> 'updateId' = ${schema.sessionSystemUpdates.id}::text`, ), ), ); const [agentSteer] = options.deliverUpdates === false ? [] : await tx .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), withinPendingUpdateBoundary, ), ) .orderBy( desc(schema.sessionSystemUpdates.createdAt), desc(schema.sessionSystemUpdates.id), ) .limit(1) .for("update"); const supersededGoalUpdates = agentSteer || options.supersedeGoalContinuations ? await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.kind, "goal_continuation"), eq(schema.sessionSystemUpdates.state, "pending"), withinPendingUpdateBoundary, ), ) .returning({ id: schema.sessionSystemUpdates.id, payload: schema.sessionSystemUpdates.payload, }) : []; for (const update of supersededGoalUpdates) { const payload = SessionSystemUpdatePayload.parse(update.payload); if (payload.type !== "goal_continuation") continue; await tx .update(schema.sessionGoals) .set({ autoContinuations: 0, noProgressStreak: 0, updatedAt: occurredAt, }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), eq(schema.sessionGoals.id, payload.goalId), eq(schema.sessionGoals.version, payload.goalVersion), eq(schema.sessionGoals.status, "active"), ), ); } const supersededGoalUpdateIds = supersededGoalUpdates.map((update) => update.id); const ordinary = options.deliverUpdates === false ? [] : await tx .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ne(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), withinPendingUpdateBoundary, ), ) .orderBy( // Command notices are retained context, not a reason to // strand later actionable input behind the read limit. A // passive idle-containment notice sorts after real command // results so it can only ride along, never lead a batch // that the planner then closes on it alone. sql`case when ${passiveCommandNoticeSql()} then 2 when ${schema.sessionSystemUpdates.kind} = 'background_command_result' then 1 else 0 end`, asc(schema.sessionSystemUpdates.createdAt), asc(schema.sessionSystemUpdates.id), ) .limit(MAX_INTERNAL_UPDATE_BATCH_MEMBERS + (agentSteer ? 0 : 1)) .for("update"); const updates = pendingInboxReadWindow( agentSteer ? [agentSteer, ...ordinary] : ordinary, options.supersedeGoalContinuations === true, ); if (updates.length === 0 && supersededGoalUpdateIds.length === 0) { return { receiverContext: null, selectionNotes: {}, count: 0, lastSequence: nextSequence - 1, triggerEventId: null, historyItemId: null, historyItem: null, deliveredAt: occurredAt, updates: [], childSessionIds: [], events: [], event: null, }; } const validUpdates: typeof updates = []; const cancelledUpdateIds: string[] = []; const scheduledTaskInactiveUpdateIds: string[] = []; const authorityRejectedUpdateIds: string[] = []; const unrecognizedUpdateIds: string[] = []; // Retained so later consumers of the delivered batch (the child // read-fence advance) reuse this exact validation instead of parsing // the same payloads a second time. const parsedPayloadsById = new Map(); for (const update of updates) { // A kind or payload this image cannot parse is a bounded, visible // condition, never an endless re-peek: mark that one row failed // and record `unrecognized_kind` on the timeline; the rest of the // batch is claimed normally. const parsedPayload = recognizedInboxPayload(update); if (parsedPayload) parsedPayloadsById.set(update.id, parsedPayload); if (!parsedPayload) { await tx .update(schema.sessionSystemUpdates) .set({ state: "failed" }) .where(eq(schema.sessionSystemUpdates.id, update.id)); unrecognizedUpdateIds.push(update.id); continue; } const scheduledAuthorityDenial = update.scheduledTaskRunId ? await validateScheduledTargetExecutionAtClaim(tx as unknown as Database, { accountId, workspaceId, session: session!, runId: update.scheduledTaskRunId, }) : null; if (update.scheduledTaskRunId && scheduledAuthorityDenial) { const scheduledTaskInactive = scheduledAuthorityDenial === "scheduled_task_inactive_before_claim"; if (!scheduledTaskInactive) { await markScheduledTaskRunAuthorityRejectedInTransaction( tx as unknown as Database, { workspaceId, sessionId, runId: update.scheduledTaskRunId, error: scheduledAuthorityDenial, }, ); } await tx .update(schema.sessionSystemUpdates) .set({ state: scheduledTaskInactive ? "cancelled" : "failed" }) .where(eq(schema.sessionSystemUpdates.id, update.id)); if (scheduledTaskInactive) { scheduledTaskInactiveUpdateIds.push(update.id); } else { authorityRejectedUpdateIds.push(update.id); } continue; } if (input.validatePendingSystemUpdateAuthority) { const validation = await input.validatePendingSystemUpdateAuthority( tx as unknown as Database, mapSessionSystemUpdate(update), ); if (validation.action === "reject") { await tx .update(schema.sessionSystemUpdates) // Classification is immutable accepted content. Authority // rejection is represented by the lifecycle state and its // cancellation evidence, not by rewriting the occurrence. .set({ state: "failed" }) .where(eq(schema.sessionSystemUpdates.id, update.id)); authorityRejectedUpdateIds.push(update.id); continue; } } const payload = update.payload; if (payload.type === "goal_continuation") { const goalId = typeof payload.goalId === "string" ? payload.goalId : null; const goalVersion = typeof payload.goalVersion === "number" ? payload.goalVersion : null; const [goal] = goalId ? await tx .select({ status: schema.sessionGoals.status, version: schema.sessionGoals.version, }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), eq(schema.sessionGoals.id, goalId), ), ) .for("update") .limit(1) : []; if (!goal || goal.status !== "active" || goal.version !== goalVersion) { await tx .update(schema.sessionSystemUpdates) .set({ state: "cancelled" }) .where(eq(schema.sessionSystemUpdates.id, update.id)); cancelledUpdateIds.push(update.id); continue; } } validUpdates.push(update); } // Command results alone start a turn only under a held wait, and an // idle-containment notice never does: when every input that opened // the claim was rejected above, the notice waits for the next turn. if ( validUpdates.every((update) => update.kind === "background_command_result") && (options.commandOnlyMayRun === false || (options.commandOnlyMayRun === true && validUpdates.every(isPassiveCommandNotice))) ) { validUpdates.length = 0; } const planned = await planInboxBatch( tx as unknown as Database, session!, validUpdates, options.receivingTurn, ); const deliverable = planned.updates; if (deliverable.length === 0) { let sequence = nextSequence - 1; const cancellationEvents: SessionEventInsertWithPayload[] = []; if (supersededGoalUpdateIds.length > 0) { cancellationEvents.push({ accountId, workspaceId, sessionId, turnId: options.supersedeGoalContinuations ? turnId : null, turnGeneration: options.supersedeGoalContinuations ? turnGeneration : null, turnAttemptId: options.supersedeGoalContinuations ? input.attemptId : null, turnAssociation: options.supersedeGoalContinuations ? "current" : null, sequence: ++sequence, type: "system.update.cancelled" as const, payload: { updateIds: supersededGoalUpdateIds, count: supersededGoalUpdateIds.length, reason: "superseded_by_authoritative_input", }, occurredAt, }); } if (cancelledUpdateIds.length > 0) { cancellationEvents.push({ accountId, workspaceId, sessionId, // No receiving turn exists when every candidate was // cancelled before a model batch could be persisted. turnId: null, turnGeneration: null, turnAttemptId: null, turnAssociation: null, sequence: ++sequence, type: "system.update.cancelled" as const, payload: { updateIds: cancelledUpdateIds, count: cancelledUpdateIds.length, reason: "stale_goal_continuation", }, occurredAt, }); } if (scheduledTaskInactiveUpdateIds.length > 0) { cancellationEvents.push({ accountId, workspaceId, sessionId, turnId: null, turnGeneration: null, turnAttemptId: null, turnAssociation: null, sequence: ++sequence, type: "system.update.cancelled" as const, payload: { updateIds: scheduledTaskInactiveUpdateIds, count: scheduledTaskInactiveUpdateIds.length, reason: "scheduled_task_inactive", }, occurredAt, }); } if (authorityRejectedUpdateIds.length > 0) { cancellationEvents.push({ accountId, workspaceId, sessionId, turnId: null, turnGeneration: null, turnAttemptId: null, turnAssociation: null, sequence: ++sequence, type: "system.update.cancelled" as const, payload: { updateIds: authorityRejectedUpdateIds, count: authorityRejectedUpdateIds.length, reason: "stale_execution_authority", }, occurredAt, }); } if (unrecognizedUpdateIds.length > 0) { cancellationEvents.push({ accountId, workspaceId, sessionId, turnId: null, turnGeneration: null, turnAttemptId: null, turnAssociation: null, sequence: ++sequence, type: "system.update.cancelled" as const, payload: { updateIds: unrecognizedUpdateIds, count: unrecognizedUpdateIds.length, reason: "unrecognized_kind", }, occurredAt, }); } return { receiverContext: null, selectionNotes: {}, count: 0, lastSequence: sequence, triggerEventId: null, historyItemId: null, historyItem: null, deliveredAt: occurredAt, updates: [], childSessionIds: [], events: cancellationEvents, event: null, }; } const modelOrdered = systemUpdatesInModelOrder(deliverable); const automationNames = await automationNamesForUpdatesInTransaction( tx as unknown as Database, workspaceId, deliverable, ); const historyItemId = crypto.randomUUID(); const historyItem = sessionSystemUpdateBatchHistoryItem( modelOrdered.map((update) => mapSessionSystemUpdate(update)), undefined, { deliveredAt: occurredAt, selectionNotes: planned.selectionNotes }, ) as Record; await tx .update(schema.sessionSystemUpdates) .set({ state: "delivered", deliveredTurnId: turnId, deliveredHistoryItemId: historyItemId, deliveredAt: occurredAt, }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), inArray( schema.sessionSystemUpdates.id, deliverable.map((update) => update.id), ), ), ); for (const update of deliverable) { const payload = SessionSystemUpdatePayload.parse(update.payload); if (payload.type !== "media_generation_result") continue; const marked = await markVideoGenerationTerminalUpdateInTransaction( tx as unknown as Database, { workspaceId, operationId: payload.operationId, state: "delivered", updateId: update.id, }, ); if (!marked) { throw new Error("Video generation terminal update lost its delivery lease"); } } const eventId = triggerEventId ?? crypto.randomUUID(); let sequence = nextSequence - 1; const events: SessionEventInsertWithPayload[] = []; if (supersededGoalUpdateIds.length > 0) { events.push({ accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.cancelled", payload: { updateIds: supersededGoalUpdateIds, count: supersededGoalUpdateIds.length, reason: "superseded_by_authoritative_input", }, occurredAt, }); } if (cancelledUpdateIds.length > 0) { events.push({ accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.cancelled", payload: { updateIds: cancelledUpdateIds, count: cancelledUpdateIds.length, reason: "stale_goal_continuation", }, occurredAt, }); } if (scheduledTaskInactiveUpdateIds.length > 0) { events.push({ accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.cancelled", payload: { updateIds: scheduledTaskInactiveUpdateIds, count: scheduledTaskInactiveUpdateIds.length, reason: "scheduled_task_inactive", }, occurredAt, }); } if (authorityRejectedUpdateIds.length > 0) { events.push({ accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.cancelled", payload: { updateIds: authorityRejectedUpdateIds, count: authorityRejectedUpdateIds.length, reason: "stale_execution_authority", }, occurredAt, }); } if (unrecognizedUpdateIds.length > 0) { events.push({ accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.cancelled", payload: { updateIds: unrecognizedUpdateIds, count: unrecognizedUpdateIds.length, reason: "unrecognized_kind", }, occurredAt, }); } const event: SessionEventInsertWithPayload = { id: eventId, accountId, workspaceId, sessionId, turnId, turnGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: ++sequence, type: "system.update.delivered", payload: { updateIds: deliverable.map((update) => update.id), historyItemId, count: deliverable.length, classifications: [...new Set(deliverable.map((update) => update.classification))], members: modelOrdered.map((update) => internalUpdateEventMember(update, automationNames), ), }, occurredAt, }; events.push(event); return { receiverContext: planned.receiverContext, selectionNotes: planned.selectionNotes, count: deliverable.length, lastSequence: sequence, triggerEventId: eventId, historyItemId, historyItem, deliveredAt: occurredAt, updates: deliverable, childSessionIds: consumedChildLifecycleSessionIds(deliverable, parsedPayloadsById), events, event, }; }; const persistDeliveredUpdateBatch = async ( delivered: Awaited>, accountId: string, turnId: string, goalSnapshot?: SessionGoalSnapshot, historyItemOverride?: Record, ): Promise => { if (!delivered.historyItemId || !delivered.historyItem) { if (delivered.count !== 0) { throw new Error("Delivered machine-input batch has no model-memory item"); } return; } const [{ position } = { position: 0 }] = await tx .select({ position: sql`coalesce(max(${schema.sessionHistoryItems.position}), -1) + 1`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), ), ); await tx.insert(schema.sessionHistoryItems).values( withLosslessContentWriteVersion( { id: delivered.historyItemId, accountId, workspaceId, sessionId, turnId, position: Number(position), item: omitOutputOnlyHistoryItemFields( historyItemOverride ?? (goalSnapshot ? sessionSystemUpdateBatchHistoryItem( systemUpdatesInModelOrder(delivered.updates).map((update) => mapSessionSystemUpdate(update), ), goalSnapshot, { deliveredAt: delivered.deliveredAt, selectionNotes: delivered.selectionNotes, }, ) : delivered.historyItem), ), }, "item", "itemCodecVersion", ), ); }; // Capacity settlement and resume use session -> turn after their // workspace rotation lock. Claiming must preserve that shared order: // taking a queued turn first can deadlock with a settlement that owns // the session and is waiting for the same turn. const workspaceControl = await lockWorkspaceInferenceControl( tx as unknown as Database, workspaceId, "share", ); const prefix = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", sessionIds: [sessionId], }); const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, sessionId, { workspaceControl }, ); let session = prefix.sessions[0]; if (!session) return { action: "unclaimed", reason: "no-work" }; // Timeout recovery and claim own the same session fence. If recovery // won before this attempt existed, a delayed activity may not create // its owner (or consume machine input) after Temporal abandoned it. const expiryIdentity = { accountId: session.accountId, workspaceId, sessionId, attemptId: input.attemptId, }; const expiredDispatch = await findSessionDispatchExpiryReceiptTx( tx as unknown as Database, expiryIdentity, ); if (isSessionDispatchExpiryReceipt(expiredDispatch, expiryIdentity)) { return { action: "unclaimed", reason: "dispatch-expired" }; } // Work and realtime may coexist, but claim remains the lazy lifecycle // cleanup point for an expired voice lease. session = await settleExpiredSessionRealtimeInTransaction(tx, session); if (effectiveControl.state !== "active" || session.admissionBlock != null) { return { action: "unclaimed", reason: "gate-closed" }; } // Quiescence is a session-wide admission fence, not a property of one // queue row. The user may delete/reorder the original Steer replacement // while its predecessor is still stopping, and recovery/internal-update // claimers must remain blocked just the same. The session lock serializes // this read with markSessionAttemptQuiesced's receipt transaction. const [unquiescedInterruption] = await tx .select({ attemptId: schema.sessionAttemptInterruptions.attemptId }) .from(schema.sessionAttemptInterruptions) .innerJoin( schema.sessionTurnAttempts, and( eq( schema.sessionTurnAttempts.workspaceId, schema.sessionAttemptInterruptions.workspaceId, ), eq(schema.sessionTurnAttempts.id, schema.sessionAttemptInterruptions.attemptId), ), ) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", "settled", "rejected_stale", ]), isNull(schema.sessionTurnAttempts.quiescedAt), ), ) .orderBy(desc(schema.sessionAttemptInterruptions.requestedAt)) .limit(1); // Only a session with an unsettled admission or an active retained // process can have a pending writer. Most have neither, and then the // exact predicate below (mostly planning cost) need not run. const [writerCandidates] = await tx.execute<{ present: boolean }>(sql` select exists ${sessionPendingWriterAttemptIdsSql({ workspaceId, sessionId })} as present `); const [unsettledWriters] = writerCandidates?.present ? await tx.execute<{ pending: boolean }>(sql` select exists ( select 1 from session_turn_attempts attempt where attempt.workspace_id = ${workspaceId} and attempt.session_id = ${sessionId} and attempt.state = 'closed' and attempt.quiesced_at is null and attempt.id in ${sessionPendingWriterAttemptIdsSql({ workspaceId, sessionId })} and ${sessionAttemptPendingWritersSql(sql`attempt`, "inference")} ) as pending `) : []; if (unquiescedInterruption || unsettledWriters?.pending) { return { action: "unclaimed", reason: "control-pending" }; } const registerAttempt = async (turn: typeof schema.sessionTurns.$inferSelect) => { const policyRows = await tx .select({ serverId: schema.sessionMcpServers.serverId, requireApproval: schema.sessionMcpServers.requireApproval, }) .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionMcpServers.serverId)); const mcpApprovalPolicies: Record = Object.fromEntries( policyRows.map((row) => [row.serverId, row.requireApproval ?? false]), ); const inheritedPolicies = session.mcpApprovalPolicies ?? {}; if (Object.keys(inheritedPolicies).length > 0) { const enabled = await listEnabledMcpCapabilityServers( tx as unknown as Database, workspaceId, ); for (const server of enabled) { if ( Object.hasOwn(inheritedPolicies, server.id) && !Object.hasOwn(mcpApprovalPolicies, server.id) ) { mcpApprovalPolicies[server.id] = resolveMcpApprovalRecommendation( inheritedPolicies[server.id], server.approvalFloor, ) ?? false; } } } // Re-entering an attempt that is already claimed (attaching pending // updates to a running attempt, or replaying its claim) keeps the // connector policies it froze when first claimed. A tool the attempt // ran since can change those policies, for example an approved // GitHub action policy update; the change applies from the next // attempt, as every later policy change does. const [claimedAttempt] = await tx .select({ connectorActionPolicies: schema.sessionTurnAttempts.connectorActionPolicies }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ) .limit(1); const connectorPolicyRows = claimedAttempt?.connectorActionPolicies ?? (await connectorActionPolicySnapshotForTurn(tx as unknown as Database, { accountId: session.accountId, workspaceId, bindings: turn.mcpAccountBindings, })); // New queued, compaction, and internal-update executions are born // while the locked session still has no active-turn pointer. Publish // that ownership edge before freezing governance so the database // functions can require the complete exact-current-attempt chain. // The enclosing transaction keeps this invisible unless every later // claim/event/session settlement step succeeds. if (session.activeTurnId !== turn.id) { if (session.activeTurnId !== null) { throw new SessionControlInvariantError( `Attempt ${input.attemptId} cannot replace active turn ${session.activeTurnId}`, ); } const [claimedSession] = await tx .update(schema.sessions) .set({ activeTurnId: turn.id }) .where( and( eq(schema.sessions.accountId, session.accountId), eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), isNull(schema.sessions.activeTurnId), ), ) .returning({ id: schema.sessions.id }); if (!claimedSession) { throw new SessionControlInvariantError( `Attempt ${input.attemptId} could not establish active turn ${turn.id}`, ); } } const attempt = await withSandboxRecoveryWarningClaimProtocol( tx, input.filesystemDiscontinuityProtocol, input.agentInstructionsProtocol, () => registerSessionTurnAttemptClaim(tx as unknown as Database, { id: input.attemptId, accountId: session.accountId, workspaceId, sessionId, turnId: turn.id, executionGeneration: turn.executionGeneration, temporalWorkflowId: workflowId, temporalWorkflowRunId: input.workflowRunId, temporalActivityId: input.dispatchId, verifiedControlRevision: Number(workspaceControl.revision), authorityEpoch: session.authorityEpoch, authorityVisibility: session.visibility as "user_private" | "workspace_shared", authorityOwnerOrganizationMembershipId: session.ownerOrganizationMembershipId ?? null, personalResourceProtocolVersion: turn.personalResourceProtocolVersion, mcpApprovalPolicies, connectorActionPolicies: connectorPolicyRows, }), input.orgAgentProtocol, ); // Freeze governance only after this exact attempt is durably claimed, // while the claim transaction still owns the session/turn/attempt // locks. Policies resolve as the turn starts running (a queued turn // sees what was activated while it waited); once a turn has run, // its later attempts keep that snapshot and later activation // applies to the next turn. await tx.execute(sql` SELECT snapshot.id FROM workspace_instruction_policy_get_or_create_snapshot( ${session.accountId}::uuid, ${workspaceId}::uuid, ${sessionId}::uuid, ${turn.id}::uuid, ${input.attemptId}::uuid, ${turn.executionGeneration} ) snapshot `); const initiatingHumanSubjectId = turn.initiatingHumanSubjectId ?? (turn.initiatorKind === "subject" ? turn.initiatorSubjectId : null); if (initiatingHumanSubjectId) { await tx.execute(sql` SELECT snapshot.id FROM preference_registry_get_or_create_snapshot( ${session.accountId}::uuid, ${workspaceId}::uuid, ${sessionId}::uuid, ${turn.id}::uuid, ${input.attemptId}::uuid, ${turn.executionGeneration} ) snapshot `); // The preference function applies the immutable initiating human // only transaction-locally. Clear it before the rest of claim // settlement so no unrelated subject-scoped read inherits it. await tx.execute(sql`SELECT set_config('opengeni.subject_id', '', true)`); } return attempt; }; const rejectScheduledTurnBeforeNewAttempt = async ( turn: typeof schema.sessionTurns.$inferSelect, denial: string, ): Promise => { if (!turn.scheduledTaskRunId) { throw new SessionControlInvariantError( `Turn ${turn.id} has no scheduled run for authority rejection`, ); } await markScheduledTaskRunAuthorityRejectedInTransaction(tx as unknown as Database, { workspaceId, sessionId, runId: turn.scheduledTaskRunId, error: denial, }); await tx .update(schema.sessionSystemUpdates) .set({ state: "failed" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.scheduledTaskRunId, turn.scheduledTaskRunId), eq(schema.sessionSystemUpdates.state, "pending"), ), ); const settled = await failSessionWorkBeforeAttemptClaim( tx as unknown as Database, workspaceId, { accountId: session.accountId, sessionId, workflowId, trigger: input.trigger, error: denial, }, ); if (settled.action === "stale") { throw new SessionControlInvariantError( `Scheduled authority rejection for turn ${turn.id} lost its pre-attempt settlement`, ); } return { action: "unclaimed", reason: "no-work" }; }; if (session.activeTurnId !== null) { const [activeTurnPreview] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, session.activeTurnId), ), ) .limit(1); const activeLocks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [session.activeTurnId], attemptIds: activeTurnPreview?.activeAttemptId ? [activeTurnPreview.activeAttemptId] : [], }); const activeTurn = activeLocks.turns[0]; if ( !activeTurn || activeTurn.sessionId !== sessionId || activeTurn.accountId !== session.accountId || (activeTurn.activeAttemptId !== null && !activeLocks.attempts.some( (attempt) => attempt.id === activeTurn.activeAttemptId && attempt.sessionId === sessionId && attempt.turnId === activeTurn.id && attempt.accountId === session.accountId, )) ) { throw new Error( `Session ${sessionId} points to invalid active turn ownership ${session.activeTurnId}`, ); } await goalSnapshotForAcceptedTurnInTransaction(tx as unknown as Database, activeTurn); const parsedDispatch = readTurnDispatchMetadata(activeTurn?.metadata); if (parsedDispatch.kind === "malformed") { throw new Error(`Malformed turn dispatch metadata: ${parsedDispatch.reason}`); } const [pendingInterruption] = activeTurn?.activeAttemptId ? await tx .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), eq(schema.sessionAttemptInterruptions.attemptId, activeTurn.activeAttemptId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .limit(1) : []; if (pendingInterruption) { return { action: "unclaimed", reason: "control-pending" }; } if ( activeTurn?.status === "running" && activeTurn.activeAttemptId === input.attemptId && parsedDispatch.attempt?.id === input.dispatchId ) { if (input.attachPendingUpdatesToRunningAttempt) { const now = new Date(); let pendingEventSequenceBeforeOrAt = parsedDispatch.attempt?.pendingUpdateBoundarySequence; if (pendingEventSequenceBeforeOrAt === undefined) { // During a rolling deploy, an old worker can claim this resume // before dispatch metadata includes the new boundary, then a // new worker can retry the same exact running attempt. The // durable response event is the conservative compatibility // fence: it includes input already pending before the response // without consuming input that arrived after the user resumed. const [legacyResumeTrigger] = await tx .select({ sequence: schema.sessionEvents.sequence, type: schema.sessionEvents.type, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.id, parsedDispatch.attempt!.triggerEventId), ), ) .limit(1); if ( !legacyResumeTrigger || !["user.approvalDecision", "user.humanInputResponse"].includes( legacyResumeTrigger.type, ) ) { throw new SessionControlInvariantError( `Running turn ${activeTurn.id} has no pending-update attempt boundary`, ); } pendingEventSequenceBeforeOrAt = legacyResumeTrigger.sequence; } const delivered = await deliverPendingUpdates( session.accountId, activeTurn.id, activeTurn.executionGeneration, session.lastSequence + 1, now, undefined, { pendingEventSequenceBeforeOrAt, receivingTurn: activeTurn, }, ); await persistDeliveredUpdateBatch(delivered, session.accountId, activeTurn.id); await acknowledgeConsumedChildLifecycleNotices(tx as unknown as Database, { workspaceId, sessionId, subjectId: activeTurn.initiatingHumanSubjectId ?? (activeTurn.initiatorKind === "subject" ? activeTurn.initiatorSubjectId : null), childSessionIds: delivered.childSessionIds, }); if (delivered.events.length > 0) { await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( delivered.events, "payload", "payloadCodecVersion", ), ); await tx .update(schema.sessions) .set({ lastSequence: delivered.lastSequence, updatedAt: now }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ), ); } } await registerAttempt(activeTurn); return { action: "claimed", turn: mapSessionTurnForExecution(activeTurn), }; } if (activeTurn?.status === "requires_action") { if (input.trigger.kind !== "approval") { return { action: "unclaimed", reason: "no-work" }; } const advancesApproval = await isNewerApprovalTrigger( tx as unknown as Database, workspaceId, sessionId, activeTurn.triggerEventId, input.trigger.triggerEventId, ); if (!advancesApproval) { return { action: "unclaimed", reason: "stale-approval" }; } if (activeTurn.scheduledTaskRunId) { const denial = await validateScheduledTargetExecutionAtClaim( tx as unknown as Database, { accountId: session.accountId, workspaceId, session, runId: activeTurn.scheduledTaskRunId, }, ); if (denial) return await rejectScheduledTurnBeforeNewAttempt(activeTurn, denial); } if (parsedDispatch.generation >= Number.MAX_SAFE_INTEGER) { throw new Error("Turn dispatch generation exhausted; refusing to wrap or reuse it"); } const now = new Date(); const dispatchGeneration = parsedDispatch.generation + 1; await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); const [resumed] = await tx .update(schema.sessionTurns) .set({ status: "running", triggerEventId: input.trigger.triggerEventId, temporalWorkflowId: workflowId, executionGeneration: sql`${schema.sessionTurns.executionGeneration} + 1`, activeAttemptId: input.attemptId, metadata: metadataWithTurnDispatchAttempt(activeTurn.metadata, { id: input.dispatchId, generation: dispatchGeneration, triggerEventId: input.trigger.triggerEventId, pendingUpdateBoundarySequence: session.lastSequence, }), version: sql`${schema.sessionTurns.version} + 1`, startedAt: now, finishedAt: null, updatedAt: now, }) .where(eq(schema.sessionTurns.id, activeTurn.id)) .returning(); if (!resumed) throw new Error(`Approval turn not found: ${activeTurn.id}`); await tx .update(schema.sessions) .set({ status: "running", updatedAt: now }) .where(eq(schema.sessions.id, sessionId)); await registerAttempt(resumed); return { action: "claimed", turn: mapSessionTurnForExecution(resumed), }; } if (activeTurn?.status === "recovering" || activeTurn?.status === "waiting_capacity") { if (input.trigger.kind !== "next") { return { action: "unclaimed", reason: "stale-approval" }; } if (activeTurn.status === "recovering") { // Unknown dispatch cannot replay an unwound helper. Positive // non-dispatch also cannot replenish its exhausted budget. // Control reconciliation clears uncertainty only after exact // physical completion. Wakes or loss cannot reset exhaustion. if ( sandboxSetupOutcomeUnknownFromTurnMetadata(activeTurn.metadata) || sandboxSetupRecoveryExhaustedFromTurnMetadata(activeTurn.metadata) ) { return { action: "unclaimed", reason: "no-work" }; } const lifecycleWait = sandboxLifecycleWaitFromTurnMetadata(activeTurn.metadata); if (lifecycleWait) { const [lease] = await tx .select({ leaseEpoch: schema.sandboxLeases.leaseEpoch, liveness: schema.sandboxLeases.liveness, rotationRequestedAt: schema.sandboxLeases.rotationRequestedAt, }) .from(schema.sandboxLeases) .where( and( eq(schema.sandboxLeases.workspaceId, workspaceId), eq(schema.sandboxLeases.sandboxGroupId, lifecycleWait.sandboxGroupId), ), ) .limit(1); if (sandboxLifecycleWaitIsPending(lifecycleWait, lease)) { return { action: "unclaimed", reason: "no-work" }; } } } if (activeTurn.status === "waiting_capacity") { // A shared-core waiter of any provider (the only kind written after its cutover). const coreWaiter = await readSubscriptionCoreWaiterInTransaction( tx as unknown as Database, { workspaceId, sessionId, }, ); if (coreWaiter) { return { action: "unclaimed", reason: "no-work" }; } } if (activeTurn.scheduledTaskRunId) { const denial = await validateScheduledTargetExecutionAtClaim( tx as unknown as Database, { accountId: session.accountId, workspaceId, session, runId: activeTurn.scheduledTaskRunId, }, ); if (denial) return await rejectScheduledTurnBeforeNewAttempt(activeTurn, denial); } if (parsedDispatch.generation >= Number.MAX_SAFE_INTEGER) { throw new Error("Turn dispatch generation exhausted; refusing to wrap or reuse it"); } const now = new Date(); const dispatchGeneration = parsedDispatch.generation + 1; await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); const [resumed] = await tx .update(schema.sessionTurns) .set({ status: "running", temporalWorkflowId: workflowId, executionGeneration: sql`${schema.sessionTurns.executionGeneration} + 1`, activeAttemptId: input.attemptId, metadata: metadataWithTurnDispatchAttempt( metadataWithoutSandboxLifecycleWait(activeTurn.metadata), { id: input.dispatchId, generation: dispatchGeneration, triggerEventId: activeTurn.triggerEventId, pendingUpdateBoundarySequence: session.lastSequence, }, ), version: sql`${schema.sessionTurns.version} + 1`, startedAt: now, finishedAt: null, updatedAt: now, }) .where(eq(schema.sessionTurns.id, activeTurn.id)) .returning(); if (!resumed) throw new Error(`Recovering turn not found: ${activeTurn.id}`); await tx .update(schema.sessions) .set({ status: "running", updatedAt: now, }) .where(eq(schema.sessions.id, sessionId)); await registerAttempt(resumed); return { action: "claimed", turn: mapSessionTurnForExecution(resumed), }; } if (activeTurn?.status === "running") { return { action: "unclaimed", reason: "no-work" }; } throw new Error( `Session ${sessionId} has non-runnable active turn ${session.activeTurnId} (${activeTurn?.status ?? "missing"})`, ); } // Row Steer deliberately detaches the superseded logical turn from the // session before its exact executing attempt has acknowledged the // interruption. The first-class live attempt remains the sandbox/write // owner during that short interval. Never let the replacement claim // until settlement closes that owner; otherwise the live-session // uniqueness fence would surface as an opaque database error and, more // importantly, two attempts could contend for the same session state. const [detachedLiveAttemptPreview] = await tx .select({ id: schema.sessionTurnAttempts.id, turnId: schema.sessionTurnAttempts.turnId, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); const detachedLocks = detachedLiveAttemptPreview ? await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [detachedLiveAttemptPreview.turnId], attemptIds: [detachedLiveAttemptPreview.id], }) : null; const detachedLiveAttempt = detachedLocks?.attempts[0]; const detachedTurn = detachedLocks?.turns[0]; if (detachedLiveAttemptPreview) { if ( !detachedLiveAttempt || !detachedTurn || detachedLiveAttempt.accountId !== session.accountId || detachedLiveAttempt.sessionId !== sessionId || detachedLiveAttempt.turnId !== detachedTurn.id || detachedTurn.accountId !== session.accountId || detachedTurn.sessionId !== sessionId ) { throw new Error( `Detached live attempt ${detachedLiveAttemptPreview.id} lost ownership`, ); } return { action: "unclaimed", reason: "control-pending" }; } if (input.trigger.kind === "approval") { return { action: "unclaimed", reason: "stale-approval" }; } const [pendingAgentSteer] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .orderBy( desc(schema.sessionSystemUpdates.createdAt), desc(schema.sessionSystemUpdates.id), ) .limit(1) .for("update"); // A human/API Steer is the newest explicit replacement direction. It // must claim next even when an older Agent Steer is pending; the // internal instruction is delivered as context on that same human turn // instead of manufacturing another system inference ahead of it. // Ordinary queued sends retain the established Agent-Steer priority. const { batch: queuedBatch, waiting: waitingMessages } = await selectQueuedSessionClaimBatch( tx as unknown as Database, session, Boolean(pendingAgentSteer), ); const queuedTurnRow = queuedBatch.at(-1); for (const member of queuedBatch) { await goalSnapshotForAcceptedTurnInTransaction(tx as unknown as Database, member); } const queuedTurn = queuedTurnRow ? { id: queuedTurnRow.id, trigger_event_id: queuedTurnRow.triggerEventId, metadata: queuedTurnRow.metadata, } : undefined; const id = queuedTurn?.id; if (!id) { // Manual compaction is a first-class maintenance execution, never // prompt queue work. A waiting human/API prompt stays ahead because // its normal turn will consume the same durable request before its // first model call. Only an otherwise-idle session creates this // born-running execution so compaction happens immediately without a // fake conversation message, tools, or sandbox work. if (session.compactRequested) { const now = new Date(); const turnId = crypto.randomUUID(); const triggerEventId = crypto.randomUUID(); const dispatchGeneration = 1; const compactionInitiator: FrozenTurnInitiator = { initiator: { kind: "service", subjectId: "compaction", label: "Opengeni compaction", }, context: {}, }; const [{ position } = { position: 1 }] = await tx .select({ position: sql`coalesce(max(${schema.sessionTurns.position}), 0) + 1`, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), ), ); const latestStarted = await latestStartedSessionTurnRow( tx as unknown as Database, workspaceId, sessionId, ); const [effectivePolicy] = await withEffectiveSessionPolicy( tx as unknown as Database, workspaceId, [session], ); const compactionInitiatingHumanSubjectId = latestStarted?.initiatingHumanSubjectId ?? (latestStarted?.initiatorKind === "subject" ? latestStarted.initiatorSubjectId : null); // Compaction continues the turn it compacts after, so it runs with // that person's current connection accounts, resolved like an // internal update continuing the same turn. The request then // carries the same connector and personal tools as the turn before // it and reuses its cached prompt prefix. A carried principal that // is not the turn's person, or not a private session's owner, never // lends personal accounts. A compaction turn cannot carry an // external link's permission ceiling or a credential restriction // forward, so a turn with either gives it no connection accounts // and no intent at all. let compactionPersonalConnectionDelegations: McpPersonalConnectionDelegation[] = []; let compactionMcpAccountBindings: McpConnectionAccountBinding[] = []; let compactionConnectionAccountMetadata: Record = {}; // A stored intent the current schema no longer reads lends nothing // and is not carried forward; it never fails the claim. let compactionConnectionAccountIntent: ConnectionAccountIntent | null = null; try { compactionConnectionAccountIntent = latestStarted ? parseConnectionAccountIntent(latestStarted.connectionAccountIntent) : null; } catch (error) { compactionConnectionAccountMetadata = { connectionAccountsUnresolved: unresolvedConnectionAccountsRecord(error), }; } // In a savepoint, so a failed read lends nothing instead of // failing the claim. const compactedTurnHasNoExternalLink = async (compactedTurnId: string) => { try { const rows = await tx.transaction( async (savepoint) => await savepoint.execute<{ present: number }>(sql` select 1 as present from external_link_turn_authorities where account_id = ${session.accountId} and workspace_id = ${workspaceId} and turn_id = ${compactedTurnId} limit 1 `), ); return rows.length === 0; } catch (error) { compactionConnectionAccountMetadata = { connectionAccountsUnresolved: unresolvedConnectionAccountsRecord(error), }; return false; } }; const compactionAuthorityBorrowable = latestStarted !== null && compactionConnectionAccountIntent !== null && !carriesCredentialRestriction( latestStarted.initiatorContext, latestStarted.metadata, ) && !carriesCredentialRestriction(null, session.metadata) && (await compactedTurnHasNoExternalLink(latestStarted.id)); if ( compactionAuthorityBorrowable && compactionConnectionAccountIntent && input.resolveContinuedConnectionAccounts ) { const resolveContinuedConnectionAccounts = input.resolveContinuedConnectionAccounts; const claimedSession = session; const principal = compactionConnectionAccountIntent.principal; const principalMayLend = principal.kind === "subject" && principal.subjectId === compactionInitiatingHumanSubjectId && (claimedSession.visibility !== "user_private" || principal.subjectId === claimedSession.ownerSubjectId?.trim()); const intent: ConnectionAccountIntent = principal.kind === "subject" && !principalMayLend ? { ...compactionConnectionAccountIntent, principal: { kind: "none" } } : compactionConnectionAccountIntent; const lendingSubjectId = intent.principal.kind === "subject" ? intent.principal.subjectId : null; try { // A savepoint, so a failed resolution leaves the claim usable. // Maintenance is never blocked by connection accounts: without // them it runs as before, with only the session's shared tools. const resolved = await tx.transaction(async (savepoint) => { const connectorMetadata = await sessionMcpServerMetadataForSessions( savepoint as unknown as Database, workspaceId, [sessionId], ); const result = await resolveContinuedConnectionAccounts( savepoint as unknown as Database, { sessionId, session: mapSessionWithoutSkills( claimedSession, serializeEffectiveSessionControl(effectiveControl), connectorMetadata.get(sessionId) ?? [], ), intent, }, ); const delegations = parsedPersonalConnectionDelegations( result.personalConnectionDelegations, `session_turns:${workspaceId}:${sessionId}:${turnId}:compaction`, ); const bindings = parseAcceptedMcpAccountBindings(result.mcpAccountBindings) ?? []; if ( delegations.some( (delegation) => delegation.ownerSubjectId !== lendingSubjectId, ) || bindings.some( (binding) => binding.subjectScope === "subject" && binding.ownerSubjectId !== lendingSubjectId, ) ) { throw new CompactionConnectionAccountRefusal(); } return { delegations, bindings, gaps: (result.gaps ?? []).slice(0, 32) }; }); compactionPersonalConnectionDelegations = resolved.delegations; compactionMcpAccountBindings = resolved.bindings; if (resolved.gaps.length > 0) { compactionConnectionAccountMetadata = { connectionAccountGaps: resolved.gaps }; } } catch (error) { // A lost connection fails the turn insert below instead. The // worker reports this record; it never carries the message. compactionConnectionAccountMetadata = { connectionAccountsUnresolved: unresolvedConnectionAccountsRecord(error), }; } } await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); const sharedCompactionPool = latestStarted ? null : await sharedPoolSubscriptionAuthoritySnapshotsInTransaction( tx as unknown as Database, workspaceId, ); const compactionIntent = compactionAuthorityBorrowable ? compactionConnectionAccountIntent : null; type CompactionAccounts = { delegations: McpPersonalConnectionDelegation[]; bindings: McpConnectionAccountBinding[]; metadata: Record; }; const insertCompactionTurn = async (writer: typeof tx, accounts: CompactionAccounts) => await writer .insert(schema.sessionTurns) .values( withLosslessContentWriteVersion( { id: turnId, accountId: session.accountId, workspaceId, sessionId, triggerEventId, temporalWorkflowId: workflowId, status: "running", executionGeneration: 1, activeAttemptId: input.attemptId, source: "compaction", // Maintenance continues the session's work; keep the // surface of the turn it compacts after. surface: sessionTurnSurfaceOrNull(latestStarted?.surface), position: Number(position), prompt: "", resources: [], tools: [], model: effectivePolicy!.model, reasoningEffort: reasoningEffortForMetadata( { reasoningEffort: effectivePolicy!.reasoningEffort }, session.reasoningEffort as ReasoningEffort, ), latencyMode: latencyModeForMetadata( { latencyMode: effectivePolicy!.latencyMode }, session.latencyMode as LatencyMode, ), sandboxBackend: latestStarted?.sandboxBackend ?? session.sandboxBackend, sandboxOs: latestStarted?.sandboxOs ?? session.sandboxOs, metadata: metadataWithTurnDispatchAttempt( { executionKind: "context_compaction", ...accounts.metadata, }, { id: input.dispatchId, generation: dispatchGeneration, triggerEventId, }, ), ...initiatorColumns(compactionInitiator), initiatingHumanSubjectId: compactionInitiatingHumanSubjectId, personalConnectionDelegations: accounts.delegations, mcpAccountBindings: accounts.bindings, // Only a borrowable turn's intent is carried, so later // work continuing this compaction never resolves accounts // the compacted turn could not lend. connectionAccountIntent: compactionIntent, xaiProviderAccountAuthoritySnapshot: latestStarted?.xaiProviderAccountAuthoritySnapshot ?? sharedCompactionPool!.xai, claudeProviderAccountAuthoritySnapshot: latestStarted?.claudeProviderAccountAuthoritySnapshot ?? sharedCompactionPool!.claude, // The immutable v2 accepted authority of the turn this // compacts after (NULL without a Codex cutover, so the // legacy path is unchanged). A session with no started // turn has none: shared capacity only. subscriptionAuthority: latestStarted?.subscriptionAuthority ?? null, startedAt: now, createdAt: now, updatedAt: now, }, "prompt", "promptCodecVersion", ), ) .returning(); let compactionTurn: | Awaited>[number] | undefined; if ( compactionPersonalConnectionDelegations.length > 0 || compactionMcpAccountBindings.length > 0 ) { try { // Acceptance re-checks live authority in the turn's triggers. // A refusal falls back to no accounts instead of failing the // claim, so the pending request can still run. [compactionTurn] = await tx.transaction(async (savepoint) => { if (compactionPersonalConnectionDelegations.length > 0) { // Transaction-local: released with the savepoint, it stays // set for the rest of the claim (as on the internal-update // path); rolled back with it on refusal. await savepoint.execute(sql` SELECT set_config( 'opengeni.initiating_human_subject_id', ${compactionInitiatingHumanSubjectId}, true ) `); } return await insertCompactionTurn(savepoint as unknown as typeof tx, { delegations: compactionPersonalConnectionDelegations, bindings: compactionMcpAccountBindings, metadata: compactionConnectionAccountMetadata, }); }); } catch (error) { compactionTurn = undefined; compactionConnectionAccountMetadata = { connectionAccountsUnresolved: unresolvedConnectionAccountsRecord( error, "acceptance_refused", ), }; } } compactionTurn ??= ( await insertCompactionTurn(tx, { delegations: [], bindings: [], metadata: compactionConnectionAccountMetadata, }) )[0]; if (!compactionTurn) throw new Error("Failed to create context compaction execution"); await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_turn", workspaceId, id: compactionTurn.id }, ]); await registerAttempt(compactionTurn); const [requestedEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { id: triggerEventId, accountId: session.accountId, workspaceId, sessionId, turnId, turnGeneration: compactionTurn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", sequence: session.lastSequence + 1, type: "session.context.compaction.requested", payload: { // A worker-requested idle checkpoint is labeled // proactive; /compact and older unlabeled requests // remain operator. trigger: session.compactRequestTrigger ?? "operator", initiator: compactionInitiator.initiator, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!requestedEvent) { throw new Error("Failed to create context compaction trigger event"); } await tx .update(schema.sessions) .set({ status: "running", activeTurnId: turnId, lastSequence: session.lastSequence + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ), ); return { action: "claimed", turn: mapSessionTurnForExecution(compactionTurn), }; } // Machine updates that were already pending at a terminal compaction // failure must not turn it into an autonomous retry loop: they stay // held and attach to the next human/API, Steer, explicitly requested // Compact, or newer machine input. Input committed after the failure // is new truth; it makes one attempt and the held backlog rides along. const compactionHoldSequence = pendingAgentSteer ? null : await compactionFailureHoldSequenceTx( tx as unknown as Database, workspaceId, sessionId, ); const commandWait = await sessionInputWaitStateTx(tx, workspaceId, sessionId, session); const wakeClasses = await pendingSystemUpdateWakeClassesTx(tx, workspaceId, sessionId, { pendingAfterSequence: compactionHoldSequence, }); if ( !wakeClasses.immediate && !wakeClasses.deferred && !(wakeClasses.command && commandWait.disposition === "held") ) { return { action: "unclaimed", reason: "no-work" }; } const pendingUpdates = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .limit(1) .for("update"); if (pendingUpdates.length === 0) { return { action: "unclaimed", reason: "no-work" }; } const now = new Date(); const turnId = crypto.randomUUID(); const triggerEventId = crypto.randomUUID(); const [{ position } = { position: 1 }] = await tx .select({ position: sql`coalesce(max(${schema.sessionTurns.position}), 0) + 1`, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), ), ); const delivered = await deliverPendingUpdates( session.accountId, turnId, 1, session.lastSequence + 1, now, triggerEventId, { commandOnlyMayRun: commandWait.disposition === "held" }, ); if (delivered.count === 0) { if (delivered.events.length > 0) { await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( delivered.events, "payload", "payloadCodecVersion", ), ); await tx .update(schema.sessions) .set({ status: "idle", lastSequence: delivered.lastSequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ), ); } return { action: "unclaimed", reason: "no-work" }; } const goalUpdate = delivered.updates.find( (update) => update.payload.type === "goal_continuation", ); const pureGoalUpdate = delivered.updates.length > 0 && delivered.updates.every((update) => update.payload.type === "goal_continuation") ? goalUpdate : undefined; const agentSteerUpdate = delivered.updates.find( (update) => update.kind === "agent_steer_instruction", ); // Goal policy/routing survives unrelated coalesced notices. Only an // Agent Steer is a stronger causal command and therefore suppresses // goal routing for this inference. const routingGoalUpdate = agentSteerUpdate ? undefined : goalUpdate; const agentCommandUpdate = agentSteerUpdate ?? delivered.updates.find((update) => update.kind === "agent_message"); const internalUpdateInitiator = (provenanceError?: string): FrozenTurnInitiator => ({ initiator: { kind: "service", subjectId: "internal-update", label: "Opengeni internal update", }, context: { updateIds: delivered.updates.map((update) => update.id), ...(provenanceError ? { provenanceError } : {}), }, }); let internalInitiator: FrozenTurnInitiator; const receiverContext = delivered.receiverContext; const authorityUpdate = delivered.updates[0]; if (!authorityUpdate) throw new Error("Delivered update batch has no authority source"); const internalPersonalConnectionDelegations = parsedPersonalConnectionDelegations( receiverContext?.personalConnectionDelegations ?? authorityUpdate.personalConnectionDelegations, `session_system_updates:${workspaceId}:${sessionId}:${authorityUpdate.id}`, ); const internalXaiAuthority = receiverContext ? subscriptionExecutionAuthorityFromTurn(receiverContext, "xai") : frozenXaiExecutionAuthority(authorityUpdate); const internalClaudeAuthority = receiverContext ? subscriptionExecutionAuthorityFromTurn(receiverContext, "claude") : frozenClaudeExecutionAuthority(authorityUpdate); // Informational input retains the receiving context. Explicit control // and restricted/foreign requests retain their admitted source. if (receiverContext) { internalInitiator = { initiator: { kind: "service", subjectId: "internal-update", label: "Opengeni internal update", }, initiatingHumanSubjectId: turnHuman(receiverContext), context: contextForCausalTurn( {}, { initiator: initiatorFromStorage( receiverContext.initiatorKind, receiverContext.initiatorSubjectId, receiverContext.initiatorContext, ), context: receiverContext.initiatorContext, }, { sessionId, turnId: receiverContext.id }, ), }; } else if (agentCommandUpdate) { const actor = agentCommandCausalActor(agentCommandUpdate); if (!actor) { // Corrupt/hand-inserted historical rows must not wedge every // recovery claim forever. Fail closed to a named service actor // while retaining a bounded, non-secret diagnostic marker. internalInitiator = internalUpdateInitiator( `${agentCommandUpdate.kind === "agent_message" ? "agent_message" : "agent_steer"}_lineage_incomplete`, ); } else { try { internalInitiator = await frozenInitiatorForCommandActor( tx as unknown as Database, workspaceId, { type: "agent_attempt", sessionId: actor.sessionId, turnId: actor.turnId, attemptId: actor.attemptId, executionGeneration: actor.executionGeneration, }, ); } catch (error) { if ( error instanceof Error && error.message.startsWith("Agent initiator turn not found:") ) { internalInitiator = internalUpdateInitiator( `${agentCommandUpdate.kind === "agent_message" ? "agent_message" : "agent_steer"}_source_turn_missing`, ); } else { throw error; } } } } else if (pureGoalUpdate) { internalInitiator = { initiator: { kind: "service", subjectId: "goal-continuation", label: "Opengeni goal continuation", }, context: { updateIds: delivered.updates.map((update) => update.id), ...(typeof pureGoalUpdate.payload.goalId === "string" ? { goalId: pureGoalUpdate.payload.goalId } : {}), }, }; } else if ( delivered.updates.length > 0 && delivered.updates.every((update) => update.kind === "scheduled_occurrence") ) { internalInitiator = { initiator: { kind: "service", subjectId: "scheduler", label: "OpenGeni scheduler", }, context: { updateIds: delivered.updates.map((update) => update.id), scheduledRunIds: delivered.updates.map((update) => update.sourceId), }, }; } else { internalInitiator = internalUpdateInitiator(); } // Batch identity belongs to this accepted inference, not its sender's // earlier batch. Preserve every other frozen service/agent context key. internalInitiator.context = { ...internalInitiator.context, updateIds: delivered.updates.map((update) => update.id), }; if (delivered.event) { delivered.event.payload = { ...(delivered.event.payload as Record), initiator: internalInitiator.initiator, }; } const goalPolicy = routingGoalUpdate?.payload.policy && typeof routingGoalUpdate.payload.policy === "object" ? (routingGoalUpdate.payload.policy as Record) : null; let frozenTurnExecutionPolicy = goalPolicy?.turnExecutionPolicy ? TurnExecutionPolicyV1.parse(goalPolicy.turnExecutionPolicy) : null; const latestStarted = await latestStartedSessionTurnRow( tx as unknown as Database, workspaceId, sessionId, ); const [effectivePolicy] = await withEffectiveSessionPolicy( tx as unknown as Database, workspaceId, [session], ); let model = typeof goalPolicy?.model === "string" ? goalPolicy.model : effectivePolicy!.model; let reasoningEffort = reasoningEffortForMetadata( { reasoningEffort: goalPolicy?.reasoningEffort ?? effectivePolicy!.reasoningEffort, }, session.reasoningEffort as ReasoningEffort, ); let latencyMode = latencyModeForMetadata( { latencyMode: goalPolicy?.latencyMode ?? effectivePolicy!.latencyMode, }, session.latencyMode as LatencyMode, ); let tools = Array.isArray(goalPolicy?.tools) ? goalPolicy.tools : (receiverContext?.tools ?? latestStarted?.tools ?? session.tools); let sandboxBackend = typeof goalPolicy?.sandboxBackend === "string" ? goalPolicy.sandboxBackend : (latestStarted?.sandboxBackend ?? session.sandboxBackend); const scheduledTaskRunId = delivered.updates[0]?.scheduledTaskRunId ?? null; // A scheduled occurrence or another agent's message is a new request; // any other machine input continues the session's latest surface. const internalSurface: SessionTurnSurface | null = scheduledTaskRunId ? "scheduled" : agentCommandUpdate ? "agent" : sessionTurnSurfaceOrNull(latestStarted?.surface); let scheduledEffectiveMcpServerIds: string[] | null = null; let scheduledFirstPartyMcpTools: FirstPartyMcpToolName[] | null = null; let scheduledConnectionAccountIntent: ConnectionAccountIntent | null = null; let sandboxOs = latestStarted?.sandboxOs ?? session.sandboxOs; if (scheduledTaskRunId) { const [scheduledRun] = await tx .select({ acceptedExecutionSnapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.id, scheduledTaskRunId), eq(schema.scheduledTaskRuns.accountId, session.accountId), eq(schema.scheduledTaskRuns.workspaceId, workspaceId), eq(schema.scheduledTaskRuns.sessionId, sessionId), ), ) .limit(1); if (!scheduledRun?.acceptedExecutionSnapshot) { throw new Error("scheduled turn is missing accepted execution truth"); } const accepted = ScheduledTaskRunAcceptedExecution.parse( scheduledRun.acceptedExecutionSnapshot, ); scheduledConnectionAccountIntent = accepted.connectionAccountIntent ?? null; // A task's accepted service provenance is immutable, just like // its execution policy. Never consult a mutable task or borrow // the session creator's human for this occurrence. if (delivered.updates.every((update) => update.kind === "scheduled_occurrence")) { internalInitiator = frozenScheduledOccurrenceInitiator( accepted.task, internalInitiator, ); if (delivered.event) { delivered.event.payload = { ...(delivered.event.payload as Record), initiator: internalInitiator.initiator, }; } } frozenTurnExecutionPolicy = accepted.turnExecutionPolicy ? TurnExecutionPolicyV1.parse(accepted.turnExecutionPolicy) : null; const targetPolicy = accepted.targetSessionExecution; if (targetPolicy) { scheduledEffectiveMcpServerIds = targetPolicy.effectiveMcpServerIds; scheduledFirstPartyMcpTools = targetPolicy.effectiveFirstPartyMcpTools ?? targetPolicy.firstPartyMcpTools; const targetMcpServers = await tx .select({ id: schema.sessionMcpServers.serverId }) .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionMcpServers.serverId)); if ( targetPolicy.sessionId !== sessionId || (targetPolicy.visibility !== session.visibility && !( targetPolicy.visibility === "user_private" && session.visibility === "workspace_shared" )) || targetPolicy.authorityEpoch < session.executionAuthorityEpoch || targetPolicy.authorityEpoch > session.authorityEpoch || stableJson(targetPolicy.firstPartyMcpTools) !== stableJson(session.firstPartyMcpTools) || stableJson(targetPolicy.firstPartyMcpPermissions) !== stableJson(session.firstPartyMcpPermissions ?? null) || stableJson(targetPolicy.toolPolicy) !== stableJson(session.toolPolicy) || stableJson(targetPolicy.mcpServerIds) !== stableJson(targetMcpServers.map((server) => server.id)) || targetPolicy.toolPolicyVersion !== session.toolPolicyVersion || targetPolicy.rigId !== (session.rigId ?? null) || targetPolicy.rigVersionId !== (session.rigVersionId ?? null) || targetPolicy.maxNestedAgentDepthOverride !== (session.maxNestedAgentDepthOverride ?? null) || targetPolicy.effectiveMaxNestedAgentDepth !== session.effectiveMaxNestedAgentDepth ) { throw new Error("scheduled target execution session authority changed"); } model = targetPolicy.model; reasoningEffort = targetPolicy.reasoningEffort; latencyMode = targetPolicy.latencyMode; tools = targetPolicy.tools; sandboxBackend = targetPolicy.sandboxBackend; sandboxOs = targetPolicy.sandboxOs; } else { model = accepted.resolvedModel; reasoningEffort = accepted.resolvedReasoningEffort; latencyMode = accepted.resolvedLatencyMode; tools = accepted.resolvedTools; sandboxBackend = accepted.resolvedSandboxBackend; sandboxOs = accepted.resolvedSandboxOs; } } const scheduledTaskCausalHuman = scheduledTaskRunId ? await scheduledTaskRunCausalHumanInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, runId: scheduledTaskRunId, }) : null; let initiatingHumanSubjectId = internalInitiator.initiatingHumanSubjectId ?? (internalInitiator.initiator.kind === "subject" ? internalInitiator.initiator.subjectId : null); const connectionAuthoritySubjectValue = !receiverContext && authorityUpdate.lineage && typeof authorityUpdate.lineage === "object" && !Array.isArray(authorityUpdate.lineage) ? (authorityUpdate.lineage as Record).connectionAuthoritySubjectId : null; const connectionAuthoritySubjectId = typeof connectionAuthoritySubjectValue === "string" && connectionAuthoritySubjectValue.trim().length > 0 ? connectionAuthoritySubjectValue : null; if (connectionAuthoritySubjectId) { if ( initiatingHumanSubjectId && initiatingHumanSubjectId !== connectionAuthoritySubjectId ) { throw new Error( "system-update connection authority subject does not match turn provenance", ); } initiatingHumanSubjectId = connectionAuthoritySubjectId; } const causalHumanTurnId = receiverContext?.id ?? delivered.updates .map((update) => systemUpdateCausalHumanTurnId(update)) .find((causalTurnId): causalTurnId is string => causalTurnId !== null); // The account intent this inference continues: the receiving // context's, or the causal turn's in this session. A scheduled // occurrence was resolved at its own admission. Another agent's // message or Steer outside a receiving context acts with its // sender's exact accounts; delivered into this session's receiving // context it runs on that context's authority, so it continues the // context's intent like any other input there. Copying the context's // accounts instead would keep a chat driven by agent messages on the // accounts its person had at their last message, including a // superseded connection generation after a reconnect. let continuedConnectionAccountIntent: ConnectionAccountIntent | null = receiverContext && !scheduledTaskRunId ? parseConnectionAccountIntent(receiverContext.connectionAccountIntent) : null; if (causalHumanTurnId) { // Child lifecycle notices freeze the parent turn that spawned the // child. Resolve that exact row on the receiving parent session; // never substitute the latest human turn, whose authority may be // unrelated by the time the child finishes. const [causalTurn] = await tx .select({ initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, initiatorKind: schema.sessionTurns.initiatorKind, initiatorSubjectId: schema.sessionTurns.initiatorSubjectId, initiatorContext: schema.sessionTurns.initiatorContext, connectionAccountIntent: schema.sessionTurns.connectionAccountIntent, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, causalHumanTurnId), ), ) .limit(1); if (causalTurn && !receiverContext && !scheduledTaskRunId && !agentCommandUpdate) { continuedConnectionAccountIntent = parseConnectionAccountIntent( causalTurn.connectionAccountIntent, ); } if (causalTurn) { internalInitiator.context = contextForCausalTurn( internalInitiator.context, { initiator: initiatorFromStorage( causalTurn.initiatorKind, causalTurn.initiatorSubjectId, causalTurn.initiatorContext, ), context: causalTurn.initiatorContext, }, { sessionId, turnId: causalHumanTurnId }, ); } const causalHumanSubjectId = causalTurn?.initiatingHumanSubjectId ?? (causalTurn?.initiatorKind === "subject" ? causalTurn.initiatorSubjectId : null); if (causalHumanSubjectId) { if (initiatingHumanSubjectId && initiatingHumanSubjectId !== causalHumanSubjectId) { throw new Error("system-update causal human does not match turn provenance"); } initiatingHumanSubjectId = causalHumanSubjectId; } } if (internalXaiAuthority.subjectId) { if ( initiatingHumanSubjectId && initiatingHumanSubjectId !== internalXaiAuthority.subjectId ) { throw new Error("xAI system-update subject does not match turn provenance"); } initiatingHumanSubjectId = internalXaiAuthority.subjectId; } if (internalClaudeAuthority.subjectId) { if ( initiatingHumanSubjectId && initiatingHumanSubjectId !== internalClaudeAuthority.subjectId ) { throw new Error("xAI system-update subject does not match turn provenance"); } initiatingHumanSubjectId = internalClaudeAuthority.subjectId; } if (scheduledTaskCausalHuman) { if (initiatingHumanSubjectId && initiatingHumanSubjectId !== scheduledTaskCausalHuman) { throw new Error("scheduled personal-resource subject does not match turn provenance"); } initiatingHumanSubjectId = scheduledTaskCausalHuman; } if (session.visibility === "user_private") { const privateOwnerSubjectId = session.ownerSubjectId?.trim() ?? ""; if (!privateOwnerSubjectId || !session.ownerOrganizationMembershipId) { throw new Error("Private internal update has incomplete session owner authority"); } if (initiatingHumanSubjectId && initiatingHumanSubjectId !== privateOwnerSubjectId) { throw new Error("Private internal update subject does not match the session owner"); } // This is the immutable owner frozen on the locked target session, // not an ambient request subject. The attempt snapshot below also // freezes the same visibility/owner-membership authority tuple. initiatingHumanSubjectId = privateOwnerSubjectId; } let acceptedPersonalConnectionDelegations = internalPersonalConnectionDelegations; let acceptedMcpAccountBindings = parseAcceptedMcpAccountBindings( receiverContext ? receiverContext.mcpAccountBindings : authorityUpdate.mcpAccountBindings, ); let connectionAccountGaps: Array<{ serverId: string; connectionId: string | null; reason: string; }> = []; if (continuedConnectionAccountIntent && input.resolveContinuedConnectionAccounts) { // Continuing work uses the person's current accounts, resolved // exactly as their next message with the same picks would be. A // carried principal that is not this turn's initiating person // (for example a private session's owner) never lends its personal // accounts: the turn resolves shared accounts only. const principal = continuedConnectionAccountIntent.principal; const connectorMetadata = await sessionMcpServerMetadataForSessions( tx as unknown as Database, workspaceId, [sessionId], ); const resolved = await input.resolveContinuedConnectionAccounts( tx as unknown as Database, { sessionId, session: mapSessionWithoutSkills( session, serializeEffectiveSessionControl(effectiveControl), connectorMetadata.get(sessionId) ?? [], ), intent: principal.kind === "subject" && principal.subjectId !== initiatingHumanSubjectId ? { ...continuedConnectionAccountIntent, principal: { kind: "none" } } : continuedConnectionAccountIntent, }, ); acceptedPersonalConnectionDelegations = parsedPersonalConnectionDelegations( resolved.personalConnectionDelegations, `session_turns:${workspaceId}:${sessionId}:${turnId}:continued`, ); acceptedMcpAccountBindings = parseAcceptedMcpAccountBindings( resolved.mcpAccountBindings, ); connectionAccountGaps = (resolved.gaps ?? []).slice(0, 32); } if (acceptedPersonalConnectionDelegations.length > 0) { if (!initiatingHumanSubjectId) { throw new Error("Personal connection acceptance requires an initiating human"); } if ( acceptedPersonalConnectionDelegations.some( (delegation) => delegation.ownerSubjectId !== initiatingHumanSubjectId, ) ) { throw new Error( "Personal connection owner does not match the causal initiating human", ); } await tx.execute(sql` SELECT set_config( 'opengeni.initiating_human_subject_id', ${initiatingHumanSubjectId}, true ) `); } // Private producer lineage survives source-turn cleanup and every // coalesced message, including a later restricted sender. A frozen // goal/schedule model policy cannot remove this inherited ceiling. const initialCredentialPolicy = readTurnExecutionPolicyV1(session.metadata); const receivingCredentialPolicy = readTurnExecutionPolicyV1(receiverContext?.metadata); internalInitiator.context = contextWithFrozenCredentialRestrictions( internalInitiator.context, [ ...delivered.updates.map((update) => update.lineage), receivingCredentialPolicy.kind === "valid" && receivingCredentialPolicy.policy.credentialRestriction === "developer_setup" ? { credentialRestriction: "developer_setup" } : undefined, initialCredentialPolicy.kind === "valid" && initialCredentialPolicy.policy.credentialRestriction === "developer_setup" ? { credentialRestriction: "developer_setup" } : undefined, ], ); if ( internalInitiator.context.credentialRestriction === "developer_setup" && frozenTurnExecutionPolicy ) { frozenTurnExecutionPolicy = { ...frozenTurnExecutionPolicy, credentialRestriction: "developer_setup", }; } // Internal record of connectors this continued turn runs without // (never model context): their account can no longer be used. const connectionAccountGapMetadata = connectionAccountGaps.length > 0 ? { connectionAccountGaps } : {}; const baseInternalTurnMetadata = frozenTurnExecutionPolicy ? metadataWithTurnExecutionPolicyV1( { internalUpdateCount: delivered.count, ...(routingGoalUpdate ? { goalId: routingGoalUpdate.payload.goalId } : {}), ...(scheduledEffectiveMcpServerIds ? { scheduledEffectiveMcpServerIds } : {}), ...(scheduledFirstPartyMcpTools ? { scheduledFirstPartyMcpTools } : {}), ...connectionAccountGapMetadata, }, frozenTurnExecutionPolicy, ) : { internalUpdateCount: delivered.count, ...(routingGoalUpdate ? { goalId: routingGoalUpdate.payload.goalId } : {}), ...(scheduledEffectiveMcpServerIds ? { scheduledEffectiveMcpServerIds } : {}), ...(scheduledFirstPartyMcpTools ? { scheduledFirstPartyMcpTools } : {}), ...connectionAccountGapMetadata, }; const continuationCodexPolicy = routingGoalUpdate ? readCodexCredentialPolicySnapshotV1(routingGoalUpdate.lineage) : { kind: "absent" as const }; const acceptedInternalTurnMetadata = continuationCodexPolicy.kind === "valid" ? metadataWithCodexCredentialPolicySnapshotV1( baseInternalTurnMetadata, continuationCodexPolicy.policy, ) : baseInternalTurnMetadata; // v2 accepted authority for every provider on the shared core (M3 // PR 2a, 3b; M4 X2b): a pure goal continuation inherits the exact causal turn's frozen value when // that turn's human is this turn's human. Every other delivery // copies, exactly as its v1 pools: the receiving context turn's // value for informational input, otherwise the value frozen on the // delivered update (agent messages and Steer, child results, // background results, scheduled occurrences; a batch only shares a // turn when those values are equal). Nothing is recomputed; once // the cutover is active a missing value is the empty value. const goalCausalTurnId = pureGoalUpdate ? systemUpdateCausalHumanTurnId(pureGoalUpdate) : null; let internalSubscriptionAuthority: SubscriptionPersonalAuthorityV2 | null = null; if (!pureGoalUpdate) { internalSubscriptionAuthority = receiverContext ? (receiverContext.subscriptionAuthority ?? null) : (authorityUpdate.subscriptionAuthority ?? null); } if (goalCausalTurnId && initiatingHumanSubjectId) { const [goalCausalTurn] = await tx .select({ subscriptionAuthority: schema.sessionTurns.subscriptionAuthority, initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, goalCausalTurnId), ), ) .limit(1); if ( goalCausalTurn?.subscriptionAuthority != null && goalCausalTurn.initiatingHumanSubjectId === initiatingHumanSubjectId ) { internalSubscriptionAuthority = goalCausalTurn.subscriptionAuthority; } } internalSubscriptionAuthority = subscriptionAuthorityV2OrEmpty( internalSubscriptionAuthority, ); await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); const [internalTurn] = await tx .insert(schema.sessionTurns) .values( withLosslessContentWriteVersion( { id: turnId, accountId: session.accountId, workspaceId, sessionId, triggerEventId, temporalWorkflowId: workflowId, status: "running", executionGeneration: 1, activeAttemptId: input.attemptId, source: routingGoalUpdate ? "goal" : "system", surface: internalSurface, position: Number(position), prompt: "Process the delivered internal session updates.", resources: [], tools, model, reasoningEffort, latencyMode, sandboxBackend, sandboxOs, metadata: metadataWithTurnDispatchAttempt(acceptedInternalTurnMetadata, { id: input.dispatchId, generation: 1, triggerEventId, }), ...initiatorColumns(internalInitiator), initiatingHumanSubjectId, executionContextTurnId: receiverContext?.id ?? null, personalConnectionDelegations: acceptedPersonalConnectionDelegations, mcpAccountBindings: acceptedMcpAccountBindings, connectionAccountIntent: continuedConnectionAccountIntent ?? scheduledConnectionAccountIntent, scheduledTaskRunId, xaiProviderAccountAuthoritySnapshot: internalXaiAuthority.snapshot, claudeProviderAccountAuthoritySnapshot: internalClaudeAuthority.snapshot, subscriptionAuthority: internalSubscriptionAuthority, startedAt: now, createdAt: now, updatedAt: now, }, "prompt", "promptCodecVersion", ), ) .returning(); if (!internalTurn) throw new Error("Failed to create internal update inference"); // Its delivered updates already name this turn, so the copy // resolves the delivery path's sources. await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_turn", workspaceId, id: internalTurn.id }, ]); const frozenGoalSnapshot = SessionGoalSnapshot.parse(internalTurn.goalSnapshot); let goalContinuationHistoryItem: Record | undefined; if (routingGoalUpdate) { const continuation = SessionSystemUpdatePayload.parse(routingGoalUpdate.payload); if (continuation.type !== "goal_continuation") { throw new Error("Goal-owned turn has no goal continuation payload"); } const contextualUpdates = delivered.updates .filter((update) => update.payload.type !== "goal_continuation") .map((update) => mapSessionSystemUpdate(update)); goalContinuationHistoryItem = durableUserHistoryItem( continuation.prompt, [], [], contextualUpdates.length > 0 ? renderSessionSystemUpdateBatch(contextualUpdates, { deliveredAt: delivered.deliveredAt, selectionNotes: delivered.selectionNotes, }) : undefined, frozenGoalSnapshot, internalTurn.createdAt, ); } const scheduledOccurrenceHistoryItem = !routingGoalUpdate && delivered.updates.length > 0 && delivered.updates.every((update) => update.kind === "scheduled_occurrence") ? sessionSystemUpdateBatchHistoryItem( delivered.updates.map((update) => mapSessionSystemUpdate(update)), frozenGoalSnapshot, { promoteScheduledOccurrenceToUser: true, deliveredAt: delivered.deliveredAt }, ) : undefined; await persistDeliveredUpdateBatch( delivered, session.accountId, internalTurn.id, frozenGoalSnapshot, goalContinuationHistoryItem ?? scheduledOccurrenceHistoryItem, ); if (scheduledTaskRunId) { await captureScheduledExternalLinkTurnAuthority(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId: internalTurn.id, runId: scheduledTaskRunId, }); } else if ( agentCommandUpdate && !receiverContext && agentCommandCausalActor(agentCommandUpdate) ) { await inheritExternalLinkTurnAuthority(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId: internalTurn.id, sourceTurnId: agentCommandCausalActor(agentCommandUpdate)!.turnId, kind: "agent", }); } else if (!receiverContext && causalHumanTurnId && initiatingHumanSubjectId) { await inheritExternalLinkTurnAuthority(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId: internalTurn.id, sourceTurnId: causalHumanTurnId, kind: "causal", }); } // The batch is now durable model memory. Every child it reports on has // been carried to this turn's initiating human, so their read fence on // those children advances with the same commit. await acknowledgeConsumedChildLifecycleNotices(tx as unknown as Database, { workspaceId, sessionId, subjectId: initiatingHumanSubjectId, childSessionIds: delivered.childSessionIds, }); await registerAttempt(internalTurn); if (!delivered.event) throw new Error("Delivered update batch has no durable event"); await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion(delivered.events, "payload", "payloadCodecVersion"), ); if (goalUpdate && typeof goalUpdate.payload.goalId === "string") { // `auto_continuations` counts consecutive continuations that // consumed NO external input. This claim binds the exact batch: // when any other member (child result, agent message, schedule, // Steer) rides along, this goal turn consumed input, so the streak // and the idle backoff start over. A pure continuation keeps the // count the evaluator incremented at materialization. const consumedExternalInput = delivered.updates.some( (update) => update.kind !== "goal_continuation", ); await tx .update(schema.sessionGoals) .set({ lastContinuationTurnId: internalTurn.id, ...(consumedExternalInput ? { autoContinuations: 0, noProgressStreak: 0 } : {}), updatedAt: now, }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), eq(schema.sessionGoals.id, goalUpdate.payload.goalId), eq(schema.sessionGoals.status, "active"), ), ); } await tx .update(schema.sessions) .set({ status: "running", activeTurnId: internalTurn.id, lastSequence: delivered.lastSequence, updatedAt: now, }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); return { action: "claimed", turn: mapSessionTurnForExecution(internalTurn), }; } // The database guard makes this function the only supported // queued-to-running transition. Raw or stale claimers cannot bypass the // generation/active-pointer transaction. const now = new Date(); const queuedDispatch = readTurnDispatchMetadata(queuedTurn?.metadata); if (queuedDispatch.kind === "malformed") { throw new Error(`Malformed turn dispatch metadata: ${queuedDispatch.reason}`); } if (queuedDispatch.generation >= Number.MAX_SAFE_INTEGER) { throw new Error("Turn dispatch generation exhausted; refusing to wrap or reuse it"); } const dispatchGeneration = queuedDispatch.generation + 1; await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); const [row] = await tx .update(schema.sessionTurns) .set({ status: "running", temporalWorkflowId: workflowId, executionGeneration: sql`${schema.sessionTurns.executionGeneration} + 1`, activeAttemptId: input.attemptId, metadata: metadataWithTurnDispatchAttempt(queuedTurn?.metadata, { id: input.dispatchId, generation: dispatchGeneration, triggerEventId: queuedTurn!.trigger_event_id, }), version: sql`${schema.sessionTurns.version} + 1`, startedAt: now, updatedAt: now, }) .where( and(eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.id, id)), ) .returning(); if (!row) { throw new Error(`Session turn not found: ${id}`); } await registerAttempt(row); const [{ historyPosition } = { historyPosition: 0 }] = await tx .select({ historyPosition: sql`coalesce(max(${schema.sessionHistoryItems.position}), -1) + 1`, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, sessionId), ), ); // Messages that waited for this machine's owner come first, in the // order they were sent, marked as such; then the claimed batch. const waitingHistory = waitingMessages.map((waitingTurn) => ({ historyTurn: waitingTurn, modelContext: [WAITED_FOR_MACHINE_OWNER_MODEL_CONTEXT, waitingTurn.modelContext?.trim()] .filter(Boolean) .join("\n\n"), goalSnapshot: undefined, })); const historyTurns = [ ...waitingHistory, ...[...queuedBatch.slice(0, -1), row].map((historyTurn) => ({ historyTurn, modelContext: historyTurn.modelContext, goalSnapshot: SessionGoalSnapshot.parse(historyTurn.goalSnapshot), })), ]; await tx.insert(schema.sessionHistoryItems).values( historyTurns.map(({ historyTurn, modelContext, goalSnapshot }, index) => withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, turnId: historyTurn.id, position: Number(historyPosition) + index, item: omitOutputOnlyHistoryItemFields( durableUserHistoryItem( fromPostgresLosslessText(historyTurn.prompt, historyTurn.promptCodecVersion), Array.isArray(historyTurn.resources) ? (historyTurn.resources as ResourceRef[]) : [], TimelineAnnotations.parse(historyTurn.annotations), modelContext, goalSnapshot, // Acceptance time, not claim time: a queued message keeps the // moment the user sent it. historyTurn.createdAt, humanTurnSenderLabel(historyTurn), // The sender's zone frozen in the turn at acceptance. messageTimeZoneFromTurnMetadata(historyTurn.metadata), ), ), }, "item", "itemCodecVersion", ), ), ); // Both the waiting messages and the batch's earlier members are // delivered with this turn and never run on their own. const consumed = [...waitingMessages, ...queuedBatch.slice(0, -1)]; const consumedEvents: SessionEventInsertWithPayload[] = consumed.map((member, index) => ({ accountId: session.accountId, workspaceId, sessionId, turnId: member.id, sequence: session.lastSequence + index + 1, type: "turn.superseded", payload: { reason: "steer", targetTurnId: row.id, beforeAttempt: true }, occurredAt: now, })); if (consumed.length > 0) { await tx .update(schema.sessionTurns) .set({ status: "superseded", version: sql`${schema.sessionTurns.version} + 1`, finishedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), inArray( schema.sessionTurns.id, consumed.map((member) => member.id), ), ), ); } const providerDelegatedTurn = isSessionRealtimeDelegationTurnMetadata(row.metadata); // Cross-session updates are already projected through // delegation.context.append. Keep them pending instead of consuming // them as hidden context on the provider-delegated ordinary turn. The // exact human delegation still supersedes a pending goal continuation, // just like any other accepted human turn. const delivered = providerDelegatedTurn ? await deliverPendingUpdates( session.accountId, row.id, row.executionGeneration, session.lastSequence + consumed.length + 1, now, undefined, { supersedeGoalContinuations: true, deliverUpdates: false }, ) : await deliverPendingUpdates( session.accountId, row.id, row.executionGeneration, session.lastSequence + consumed.length + 1, now, undefined, { supersedeGoalContinuations: true, receivingTurn: row, }, ); await persistDeliveredUpdateBatch(delivered, session.accountId, row.id); // Same fence advance for a queued human/API turn that coalesced child // lifecycle notices into its own inference. await acknowledgeConsumedChildLifecycleNotices(tx as unknown as Database, { workspaceId, sessionId, subjectId: row.initiatingHumanSubjectId ?? (row.initiatorKind === "subject" ? row.initiatorSubjectId : null), childSessionIds: delivered.childSessionIds, }); if (consumedEvents.length + delivered.events.length > 0) { await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [...consumedEvents, ...delivered.events], "payload", "payloadCodecVersion", ), ); } await tx .update(schema.sessions) .set({ status: "running", activeTurnId: row.id, queueVersion: session.queueVersion + 1, lastSequence: delivered.lastSequence, updatedAt: now, }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); return { action: "claimed", turn: mapSessionTurnForExecution(row) }; }), ); } export type SessionAttemptInterruptionSettlement = { action: "paused" | "continue" | "stale"; events: SessionEvent[]; attemptId: string; turnId: string | null; outcome: SessionTurnAttemptOutcome | null; }; /** * Acknowledge that the exact cancelled attempt reached its final quiescence * boundary: after this transaction it has no inference, user-visible output, * or workspace-persistence authority. Fenced/idempotent cleanup and telemetry * may still finish. This may race the workflow's logical settlement transaction * in either order; both use the canonical control -> workspace -> session -> * exact turn -> exact attempt lock order and require the durable interruption. * Temporal activity cancellation/terminalization is transport state only. The * workflow admits a replacement from this durable receipt, never from the * activity promise. The same boundary also applies when the activity itself * durably requested same-turn recovery (for example during a worker rollout): * that recovery event is the logical settlement cause in place of a * Pause/Steer interruption row. */ export type MarkSessionAttemptQuiescedInput = { accountId?: string; workspaceId: string; sessionId: string; attemptId: string; temporalWorkflowId: string; /** When supplied, both values bind an activity-owned recovery proof to the * exact persisted Temporal dispatch. Legacy v1 replay callers omit them. */ temporalWorkflowRunId?: string; temporalActivityId?: string; /** The dying activity also reaches this boundary for non-control ownership * fences. It may no-op when no Pause/Steer interruption exists; replacement * admission remains strict because only a durable interruption needs this * receipt. */ allowUninterrupted?: boolean; }; export type SessionAttemptQuiescenceCommit = { events: SessionEvent[]; /** The exact still-undelivered outbox fact created by this commit, or found * on an idempotent replay after a post-commit caller failure. Postgres remains * the durable fallback; callers may deliver this fact immediately. */ workflowWake: SessionWorkflowWake | null; }; /** Call only after canonical session/turn/attempt locks and proof eligibility. */ async function recordSessionAttemptQuiescenceInTransaction( db: SessionActivityDatabase, session: Pick< typeof schema.sessions.$inferSelect, "id" | "accountId" | "workspaceId" | "lastSequence" | "queueVersion" >, attempt: Pick< typeof schema.sessionTurnAttempts.$inferSelect, "id" | "turnId" | "executionGeneration" >, now: Date, ): Promise { const queueVersion = session.queueVersion + 1; const [marked] = await db .update(schema.sessionTurnAttempts) .set({ quiescedAt: now, updatedAt: now }) .where( and( eq(schema.sessionTurnAttempts.accountId, session.accountId), eq(schema.sessionTurnAttempts.workspaceId, session.workspaceId), eq(schema.sessionTurnAttempts.sessionId, session.id), eq(schema.sessionTurnAttempts.turnId, attempt.turnId), eq(schema.sessionTurnAttempts.executionGeneration, attempt.executionGeneration), eq(schema.sessionTurnAttempts.id, attempt.id), isNull(schema.sessionTurnAttempts.quiescedAt), ), ) .returning({ id: schema.sessionTurnAttempts.id }); if (!marked) throw new SessionControlInvariantError(`Attempt ${attempt.id} quiescence CAS lost`); const [event] = await db .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: session.workspaceId, sessionId: session.id, sequence: session.lastSequence + 1, type: "session.queue.changed", payload: { operation: "attempt_quiesced", attemptId: attempt.id, queueVersion }, clientEventId: `opengeni:attempt-quiesced:${attempt.id}`, turnId: attempt.turnId, turnGeneration: attempt.executionGeneration, turnAttemptId: attempt.id, turnAssociation: null, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Attempt-quiesced queue event was not inserted"); await db .update(schema.sessions) .set({ queueVersion, lastSequence: event.sequence, updatedAt: now }) .where( and(eq(schema.sessions.workspaceId, session.workspaceId), eq(schema.sessions.id, session.id)), ); return mapEvent(event); } export async function commitSessionAttemptQuiescence( db: Database, input: MarkSessionAttemptQuiescedInput, ): Promise { const persistence = { stage: "session_attempts.mark_quiesced", eventTypes: ["session.queue.changed"], maxAttempts: 3, }; return await retrySessionActivityRls(db, input.workspaceId, persistence, async (scopedDb) => { const prefix = await lockSessionEventWriteRows(scopedDb, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [], }); // The attempt's turn identity is immutable. Read it only to discover the // exact suffix, then lock and revalidate every ownership edge below. const [attemptPreview] = await scopedDb .select({ turnId: schema.sessionTurnAttempts.turnId }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ) .limit(1); const locks = await lockSessionEventWriteRows(scopedDb, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: [input.sessionId], turnIds: attemptPreview ? [attemptPreview.turnId] : [], attemptIds: attemptPreview ? [input.attemptId] : [], }); const session = locks.sessions[0]; const turn = locks.turns[0]; const attempt = locks.attempts[0]; // Revalidate immutable ownership only. Control settlement may already have // advanced the session/turn workflow identity or turn generation while the // exact predecessor attempt is still acknowledging physical quiescence. if ( !session || !turn || !attempt || turn.accountId !== session.accountId || turn.sessionId !== session.id || attempt.accountId !== session.accountId || (input.accountId !== undefined && attempt.accountId !== input.accountId) || attempt.sessionId !== session.id || attempt.turnId !== turn.id || attempt.temporalWorkflowId !== input.temporalWorkflowId || (input.temporalWorkflowRunId !== undefined && attempt.temporalWorkflowRunId !== input.temporalWorkflowRunId) || (input.temporalActivityId !== undefined && attempt.temporalActivityId !== input.temporalActivityId) || (input.temporalWorkflowRunId === undefined) !== (input.temporalActivityId === undefined) ) { throw new SessionControlInvariantError( `Attempt ${input.attemptId} cannot acknowledge quiescence without its session ownership`, ); } const [interruption] = attempt ? await scopedDb .select({ id: schema.sessionAttemptInterruptions.id, state: schema.sessionAttemptInterruptions.state, }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, input.workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, input.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, input.attemptId), ), ) .orderBy(asc(schema.sessionAttemptInterruptions.requestedAt)) .limit(1) : []; const [recoveryRequest] = attempt && !interruption ? await scopedDb .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.accountId, attempt.accountId), eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, attempt.turnId), eq(schema.sessionEvents.turnAttemptId, input.attemptId), eq(schema.sessionEvents.type, "turn.recovery.requested"), ), ) .limit(1) : []; const recoveryQuiescence = !interruption && recoveryRequest !== undefined && attempt.state === "closed" && attempt.outcome === "interrupted_recoverable"; if (!interruption && !recoveryQuiescence) { if (input.allowUninterrupted) return { events: [], workflowWake: null }; throw new SessionControlInvariantError( `Attempt ${input.attemptId} cannot acknowledge quiescence without its interruption or recovery request`, ); } const liveQuiescence = interruption !== undefined && (attempt.state === "claimed" || attempt.state === "running") && (interruption.state === "pending" || interruption.state === "delivered" || interruption.state === "acknowledged"); const settledQuiescence = recoveryQuiescence || (interruption !== undefined && attempt.state === "closed" && (interruption.state === "settled" || interruption.state === "rejected_stale")); if (!liveQuiescence && !settledQuiescence) { throw new SessionControlInvariantError( `Attempt ${input.attemptId} cannot acknowledge quiescence from ${attempt.state}/${interruption?.state ?? "recovery"}`, ); } const projectPausedRecovery = async ( events: SessionEvent[], lastSequence: number, ): Promise<{ events: SessionEvent[]; effectiveControl: Awaited>; }> => { const effectiveControl = await evaluateSessionControl( scopedDb, input.workspaceId, input.sessionId, { workspaceControl: prefix.control ?? undefined }, ); if ( effectiveControl.state !== "paused" || effectiveControl.settlement !== null || !settledQuiescence || attempt.outcome !== "interrupted_recoverable" || session.status !== "recovering" || session.activeTurnId !== turn.id || turn.status !== "recovering" || turn.activeAttemptId !== null ) { return { events, effectiveControl }; } const clientEventId = `opengeni:paused-recovery-settled:${input.attemptId}`; const [existing] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.clientEventId, clientEventId), ), ) .limit(1); if (existing) { // A pre-fix/partially repaired row can retain the old recovering // projection even though the exact idempotent status event exists. // Repair only the projection; the preserved active turn remains the // same recovering logical turn for Resume. await scopedDb .update(schema.sessions) .set({ status: "idle", updatedAt: new Date() }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.status, "recovering"), eq(schema.sessions.activeTurnId, turn.id), ), ); return { events: events.some((event) => event.id === existing.id) ? events : [...events, mapEvent(existing)], effectiveControl, }; } const now = new Date(); const sequence = lastSequence + 1; const [parked] = await scopedDb .update(schema.sessions) .set({ status: "idle", lastSequence: sequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.status, "recovering"), eq(schema.sessions.activeTurnId, turn.id), ), ) .returning({ id: schema.sessions.id }); if (!parked) return { events, effectiveControl }; const [statusEvent] = await scopedDb .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence, type: "session.status.changed", payload: { status: "idle", reason: "paused_recovery_settled" }, clientEventId, turnId: turn.id, turnGeneration: attempt.executionGeneration, turnAttemptId: attempt.id, turnAssociation: null, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!statusEvent) throw new Error("Paused recovery status event was not inserted"); return { events: [...events, mapEvent(statusEvent)], effectiveControl }; }; const clientEventId = `opengeni:attempt-quiesced:${input.attemptId}`; const pendingWorkflowWake = async (): Promise => { const [wake] = await scopedDb .select({ accountId: schema.sessionWorkflowWakeOutbox.accountId, workspaceId: schema.sessionWorkflowWakeOutbox.workspaceId, sessionId: schema.sessionWorkflowWakeOutbox.sessionId, temporalWorkflowId: schema.sessionWorkflowWakeOutbox.temporalWorkflowId, wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision, deliveredRevision: schema.sessionWorkflowWakeOutbox.deliveredRevision, controlRevision: schema.sessionWorkflowWakeOutbox.controlRevision, }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), ), ) .limit(1); if (!wake || wake.wakeRevision <= wake.deliveredRevision) return null; return { accountId: wake.accountId, workspaceId: wake.workspaceId, sessionId: wake.sessionId, temporalWorkflowId: wake.temporalWorkflowId, wakeRevision: wake.wakeRevision, interruptionRequested: wake.controlRevision > wake.deliveredRevision, }; }; if (attempt.quiescedAt) { const [existing] = await scopedDb .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.clientEventId, clientEventId), ), ) .limit(1); // Migration 0065 seeds quiesced_at for interrupted attempts that were // already closed before queue-event receipts existed. A replaying // workflow may still execute this idempotent fallback after rollout. It // has no queue receipt to republish, but paused recovery projection still // converges through the same exact-attempt transaction. const projected = await projectPausedRecovery( existing ? [mapEvent(existing)] : [], session.lastSequence, ); return { events: projected.events, workflowWake: projected.effectiveControl.state === "active" ? await pendingWorkflowWake() : null, }; } const now = new Date(); const event = await recordSessionAttemptQuiescenceInTransaction( scopedDb, session, attempt, now, ); const projected = await projectPausedRecovery([event], event.sequence); const effectiveControl = projected.effectiveControl; let workflowWake: SessionWorkflowWake | null = null; if (effectiveControl.state === "active") { await enqueueSessionWorkflowWakeInTransaction(scopedDb, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: input.temporalWorkflowId, reason: "attempt_quiesced", }); // Derive the transport kind from the coalesced row. An older undelivered // control revision keeps priority even though this producer is an // ordinary queue wake. workflowWake = await pendingWorkflowWake(); if (!workflowWake) { throw new Error(`Attempt-quiescence wake was not pending for session ${input.sessionId}`); } } return { events: projected.events, workflowWake }; }); } /** Compatibility projection for callers that only publish the committed * events. The turn activity uses `commitSessionAttemptQuiescence` so it can * immediately deliver the returned durable wake without waiting for repair. */ export async function markSessionAttemptQuiesced( db: Database, input: MarkSessionAttemptQuiescedInput, ): Promise { return (await commitSessionAttemptQuiescence(db, input)).events; } export type ReconcileSessionAttemptQuiescenceResult = | { action: "quiesced"; events: SessionEvent[] } | { action: "pending"; events: [] } | { action: "stale"; events: [] }; export type SessionAttemptActivityRef = { workflowId: string; workflowRunId: string; activityId: string; quiesced: boolean; }; export async function getSessionAttemptActivityRef( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; temporalWorkflowId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [attempt] = await scopedDb .select({ workflowId: schema.sessionTurnAttempts.temporalWorkflowId, workflowRunId: schema.sessionTurnAttempts.temporalWorkflowRunId, activityId: schema.sessionTurnAttempts.temporalActivityId, quiescedAt: schema.sessionTurnAttempts.quiescedAt, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.accountId, input.accountId), eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.id, input.attemptId), eq(schema.sessionTurnAttempts.temporalWorkflowId, input.temporalWorkflowId), ), ) .limit(1); return attempt ? { workflowId: attempt.workflowId, workflowRunId: attempt.workflowRunId, activityId: attempt.activityId, quiesced: attempt.quiescedAt !== null, } : null; }, ); } /** * Recover the quiescence receipt when the original activity disappeared after * its attempt was durably interrupted. The caller first proves through * Temporal that the exact activity is absent or its server-owned heartbeat * lease expired. The closed attempt then cannot admit another workspace writer, * and every writer it did admit (including retained-process child writes) must * carry a physical settlement before the ordinary receipt transaction is * allowed to run. * * With that proof, every request that the attempt's provably exited worker * left unsettled is settled first (`settleExitedWorkerAdmissions`), and the * session is woken when any was. `workerProcessExitDeadlineMs` is the turn * worker's process-exit deadline after a shutdown signal; without it a crashed * worker's requests keep their gate. */ export async function reconcileSessionAttemptQuiescence( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; activitySettled: boolean; workerProcessExitDeadlineMs?: number; }, ): Promise { if (input.activitySettled && (await settleExitedWorkerAdmissions(db, input)) > 0) { // A worker-death closure needs no receipt, so this reconciliation reports // `stale` below and its workflow run may close; the wake brings it back. await withRlsContext(db, { accountId: input.accountId, workspaceId: input.workspaceId }, (tx) => enqueueSessionWorkflowWakeInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: input.temporalWorkflowId, reason: "exited_worker_admissions_settled", }), ); } const eligibility = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb.execute<{ account_id: string; state: string; outcome: string | null; quiesced_at: Date | string | null; temporal_workflow_id: string; temporal_workflow_run_id: string; temporal_activity_id: string; interruption_settled: boolean; interruption_pending: boolean; recovery_requested: boolean; writer_pending: boolean; }>(sql` select attempt.account_id, attempt.state, attempt.outcome, attempt.quiesced_at, attempt.temporal_workflow_id, attempt.temporal_workflow_run_id, attempt.temporal_activity_id, exists ( select 1 from session_attempt_interruptions interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('settled', 'rejected_stale') ) as interruption_settled, exists ( select 1 from session_attempt_interruptions interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('pending', 'delivered', 'acknowledged') ) as interruption_pending, exists ( select 1 from session_events event where event.account_id = attempt.account_id and event.workspace_id = attempt.workspace_id and event.session_id = attempt.session_id and event.turn_id = attempt.turn_id and event.turn_attempt_id = attempt.id and event.type = 'turn.recovery.requested' ) as recovery_requested, ${sessionAttemptPendingWritersSql(sql`attempt`)} as writer_pending from session_turn_attempts attempt where attempt.account_id = ${input.accountId} and attempt.workspace_id = ${input.workspaceId} and attempt.session_id = ${input.sessionId} and attempt.id = ${input.attemptId} limit 1 `); return rows[0] ?? null; }, ); if ( !eligibility || eligibility.account_id !== input.accountId || eligibility.temporal_workflow_id !== input.temporalWorkflowId || eligibility.temporal_workflow_run_id !== input.temporalWorkflowRunId || eligibility.temporal_activity_id !== input.temporalActivityId || eligibility.state !== "closed" || (!eligibility.writer_pending && !eligibility.interruption_settled && (!eligibility.recovery_requested || eligibility.outcome !== "interrupted_recoverable")) || eligibility.interruption_pending ) { return { action: "stale", events: [] }; } if (eligibility.quiesced_at) { // The receipt may predate the paused-session projection fix. Re-enter the // exact idempotent receipt transaction only when the work peeker proves // this same paused recovery still needs projection. Ordinary idempotent // reconciliations retain their established event-free result. const peek = await peekSessionWork(db, input.workspaceId, input.sessionId); if (peek.kind !== "cancellation-wait" || peek.attemptId !== input.attemptId) { return { action: "quiesced", events: [] }; } const events = await markSessionAttemptQuiesced(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, attemptId: input.attemptId, temporalWorkflowId: input.temporalWorkflowId, temporalWorkflowRunId: input.temporalWorkflowRunId, temporalActivityId: input.temporalActivityId, }); return { action: "quiesced", events: events.filter( (event) => event.clientEventId === `opengeni:paused-recovery-settled:${input.attemptId}`, ), }; } if (!input.activitySettled || eligibility.writer_pending) { if (input.activitySettled && eligibility.writer_pending) { const group = await withRlsContext(db, input, async (tx) => { const [row] = await tx .select({ id: schema.sessions.sandboxGroupId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); return row?.id; }); if (group) await enrollRetainedCommandContainment(db, { accountId: input.accountId, workspaceId: input.workspaceId, sandboxGroupId: group, settledOwner: input, }); } return { action: "pending", events: [] }; } const events = await markSessionAttemptQuiesced(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, attemptId: input.attemptId, temporalWorkflowId: input.temporalWorkflowId, temporalWorkflowRunId: input.temporalWorkflowRunId, temporalActivityId: input.temporalActivityId, }); return { action: "quiesced", events }; } /** * Settle every durable interruption cause for one exact first-class attempt. * Steer wins the logical-turn fate when causes coexist; effective control after * settlement independently decides whether the workflow holds or continues. * The attempt remains the sole write owner until this transaction closes it. */ export async function settleSessionAttemptInterruptions( db: Database, workspaceId: string, sessionId: string, attemptId: string, ): Promise { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => scopedDb.transaction(async (tx) => { const prefix = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const session = prefix.sessions[0]; if (!session) throw new Error(`Session not found: ${sessionId}`); const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, sessionId, { workspaceControl: prefix.control ?? undefined }, ); const interruptionPreview = await tx .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), eq(schema.sessionAttemptInterruptions.attemptId, attemptId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .limit(1); if (interruptionPreview.length === 0) { return { action: "stale", events: [], attemptId, turnId: null, outcome: null, }; } const [attemptPreview] = await tx .select() .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.id, attemptId), ), ) .limit(1); if (!attemptPreview) { throw new Error(`Interruption points to missing attempt: ${attemptId}`); } const exact = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [attemptPreview.turnId], attemptIds: [attemptId], }); const attempt = exact.attempts[0]; const turn = exact.turns[0]; if (!attempt) throw new Error(`Interruption points to missing attempt: ${attemptId}`); const interruptions = await tx .select() .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), eq(schema.sessionAttemptInterruptions.attemptId, attemptId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .orderBy( asc(schema.sessionAttemptInterruptions.requestedAt), asc(schema.sessionAttemptInterruptions.id), ) .for("update"); if (interruptions.length === 0) { return { action: "stale", events: [], attemptId, turnId: null, outcome: null, }; } const now = new Date(); if (attempt.state === "closed") { await tx .update(schema.sessionAttemptInterruptions) .set({ state: "rejected_stale", settledAt: now }) .where( inArray( schema.sessionAttemptInterruptions.id, interruptions.map((interruption) => interruption.id), ), ); await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${sessionId}`, reason: "attempt_interruption_rejected_stale", controlRequested: true, }); return { action: effectiveControl.state === "paused" ? "paused" : "continue", events: [], attemptId, turnId: attempt.turnId, outcome: null, }; } if ( !turn || attempt.accountId !== session.accountId || attempt.sessionId !== sessionId || attempt.turnId !== turn.id || turn.accountId !== session.accountId || turn.sessionId !== sessionId || attempt.executionGeneration !== turn.executionGeneration || turn.activeAttemptId !== attemptId ) { throw new Error(`Live interrupted attempt ${attemptId} lost its exact turn ownership`); } const terminalCancel = session.status === "cancelled"; // Revoked membership, an owner's "make private anyway" stop and a machine // that became someone else's Only me machine (0765) all end the turn: // the authority it was accepted under no longer applies. const membershipAuthorityRevoked = interruptions.some( (interruption) => interruption.kind === "organization_membership_revoked" || interruption.kind === "authority_change", ); const terminalTurnCancel = terminalCancel || membershipAuthorityRevoked; const steer = !terminalTurnCancel && interruptions.some((interruption) => interruption.kind === "steer"); const outcome: SessionTurnAttemptOutcome = terminalTurnCancel ? "cancelled" : steer ? "superseded" : "interrupted_recoverable"; // Logical interruption and physical quiescence can commit in either // order. If quiescence won, park the paused public session projection in // this transaction so both lock orders converge on the same durable state. const pausedRecoveryAlreadyQuiesced = outcome === "interrupted_recoverable" && effectiveControl.state === "paused" && attempt.quiescedAt !== null; const reason = terminalCancel ? "session_cancelled" : membershipAuthorityRevoked ? "authority_changed" : steer ? "steer" : interruptions.some((interruption) => interruption.kind === "workspace_pause") ? "workspace_pause" : interruptions.some((interruption) => interruption.kind === "maintenance") ? "maintenance" : "session_pause"; if (terminalTurnCancel || steer) { await cancelTurnInteractionInterventionsInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId: turn.id, }); } let sequence = session.lastSequence; const closedTools = await closePendingSessionToolCallsInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId: turn.id, reason, sequence, now, preserveInterruptionRows: outcome === "interrupted_recoverable", }, ); sequence = closedTools.sequence; await closeSessionTurnAttemptInTransaction(tx as unknown as Database, { id: attemptId, accountId: session.accountId, workspaceId, sessionId, turnId: turn.id, executionGeneration: turn.executionGeneration, outcome, closedAt: now, }); const eventValues: SessionEventInsertWithPayload[] = terminalTurnCancel ? [ { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "turn.cancelled", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attemptId, turnAssociation: "current", payload: { reason }, occurredAt: now, }, ] : steer ? [ { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "turn.superseded", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attemptId, turnAssociation: "current", payload: { reason: "steer" }, occurredAt: now, }, { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "session.status.changed", payload: { status: "queued" }, occurredAt: now, }, ] : [ { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "turn.recovery.requested", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attemptId, turnAssociation: "current", payload: { reason }, occurredAt: now, }, { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "session.status.changed", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attemptId, turnAssociation: "current", payload: { status: "recovering" }, occurredAt: now, }, ...(pausedRecoveryAlreadyQuiesced ? [ { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "session.status.changed" as const, turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attemptId, turnAssociation: null, payload: { status: "idle", reason: "paused_recovery_settled", }, clientEventId: `opengeni:paused-recovery-settled:${attemptId}`, occurredAt: now, }, ] : []), ]; const eventRows = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(eventValues), "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessionTurns) .set( terminalTurnCancel ? { status: "cancelled", activeAttemptId: null, metadata: metadataWithoutTurnDispatchAttempt(turn.metadata), cancelledBy: terminalCancel ? "system:session_cancelled" : "system:authority_changed", cancelReason: reason, version: turn.version + 1, finishedAt: turn.finishedAt ?? now, updatedAt: now, } : steer ? { status: "superseded", activeAttemptId: null, metadata: metadataWithoutTurnDispatchAttempt(turn.metadata), version: turn.version + 1, finishedAt: turn.finishedAt ?? now, updatedAt: now, } : { status: "recovering", activeAttemptId: null, metadata: metadataWithoutTurnDispatchAttempt(turn.metadata), cancelledBy: null, cancelReason: null, version: turn.version + 1, finishedAt: null, updatedAt: now, }, ) .where(eq(schema.sessionTurns.id, turn.id)); if (membershipAuthorityRevoked && !terminalCancel) { await tx.execute(sql` update sessions session_row set status = case when exists ( select 1 from session_turns queued_turn where queued_turn.account_id = session_row.account_id and queued_turn.workspace_id = session_row.workspace_id and queued_turn.session_id = session_row.id and queued_turn.status = 'queued' ) then 'queued' else 'idle' end, active_turn_id = null, queue_head_position = coalesce(( select min(queued_turn.position) from session_turns queued_turn where queued_turn.account_id = session_row.account_id and queued_turn.workspace_id = session_row.workspace_id and queued_turn.session_id = session_row.id and queued_turn.status = 'queued' ), 0), queue_tail_position = coalesce(( select max(queued_turn.position) from session_turns queued_turn where queued_turn.account_id = session_row.account_id and queued_turn.workspace_id = session_row.workspace_id and queued_turn.session_id = session_row.id and queued_turn.status = 'queued' ), 0), queue_version = session_row.queue_version + 1, last_sequence = ${sequence}, updated_at = clock_timestamp() where session_row.account_id = ${session.accountId} and session_row.workspace_id = ${workspaceId} and session_row.id = ${sessionId} `); } else { await tx .update(schema.sessions) .set({ status: terminalCancel ? "cancelled" : steer ? "queued" : pausedRecoveryAlreadyQuiesced ? "idle" : "recovering", activeTurnId: terminalCancel || steer ? null : turn.id, lastSequence: sequence, updatedAt: now, }) .where(eq(schema.sessions.id, sessionId)); } await tx .update(schema.sessionAttemptInterruptions) .set({ state: "settled", deliveredAt: now, acknowledgedAt: now, settledAt: now, }) .where( inArray( schema.sessionAttemptInterruptions.id, interruptions.map((interruption) => interruption.id), ), ); await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${sessionId}`, reason: "attempt_interruption_settled", controlRequested: true, }); return { action: effectiveControl.state === "paused" ? "paused" : "continue", events: [...closedTools.events, ...eventRows.map(mapEvent)], attemptId, turnId: turn.id, outcome, }; }), ); } export { isSessionDefinitivelyDeleted } from "./session-deletion"; export type SessionWorkPeek = | { kind: "unavailable" } | { kind: "attempt-owned"; turnId: string; attemptId: string; executionGeneration: number; activityRef: SessionAttemptActivityRef; } | { kind: "runnable"; admissionFence?: SessionAdmissionFence; /** Wake revision observed with the fence; a later wake makes a block stale. */ admissionWakeRevision?: number; } | { kind: "admission-blocked"; reason?: | "sandbox_setup_outcome_unknown" | "sandbox_setup_recovery_exhausted" | "recovery_backoff"; ref?: SandboxSetupOutcomeUnknown | SandboxSetupRecoveryExhausted | SessionTurnRecoveryRetry; } | { kind: "sandbox-lifecycle-wait"; ref: SandboxLifecycleWait; } | { kind: "approval-pending"; triggerEventId: string; admissionFence?: SessionAdmissionFence; admissionWakeRevision?: number; } | { kind: "approval-wait"; humanInputRequestId?: string; interactionInterventionId?: string; /** The scheduled run's approval timeout is the earliest deadline. */ scheduledRunTimeout?: { runId: string; turnId: string }; expiresAt?: string; } | { kind: "capacity-wait"; ref: { provider?: "codex" | "xai" | "claude"; waiterId: string; generation: number; nextCheckAt: string; wakeRevision: number; }; } | { kind: "interruption-pending"; attemptId: string } | { kind: "cancellation-wait"; attemptId: string } | { kind: "input-wait"; disposition: "held" | "timeout" | "superseded"; waitTurnId: string; deadlineAt: string; } | { kind: "read-only" } | { kind: "idle" }; /** * Return an exact attempt whose logical interruption or same-turn recovery * request settled but whose physical quiescence receipt is still missing. * Durable Pause/Steer interruptions deliberately search all predecessors: a * recovery race can create a newer generation before their receipt arrives. * A recovery-only row blocks admission only while it is the session's newest * attempt. A later admitted attempt is durable proof that pre-fix code already * crossed that recovery boundary; replaying every historical recovery receipt * on the user's next prompt would add unbounded critical-path work. Historical * rows remain available for the bounded operator cleanup. */ async function nextSessionAttemptAwaitingQuiescence( db: Database, workspaceId: string, sessionId: string, writerMode: "physical" | "inference" = "physical", ): Promise<{ attemptId: string; } | null> { if (!(await sessionMayAwaitQuiescence(db, { workspaceId, sessionId }))) return null; const [row] = await db .select({ attemptId: schema.sessionTurnAttempts.id, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), eq(schema.sessionTurnAttempts.state, "closed"), isNull(schema.sessionTurnAttempts.quiescedAt), // Only rows that can satisfy the predicate below; without this every // closed attempt in the session's history runs its subqueries. sql`${schema.sessionTurnAttempts.id} in ${sessionQuiescenceCandidateAttemptIdsSql({ workspaceId, sessionId, })}`, sql`( ${sessionAttemptPendingWritersSql(sql`${schema.sessionTurnAttempts}`, writerMode)} or exists ( select 1 from session_attempt_interruptions interruption where interruption.workspace_id = ${schema.sessionTurnAttempts.workspaceId} and interruption.session_id = ${schema.sessionTurnAttempts.sessionId} and interruption.attempt_id = ${schema.sessionTurnAttempts.id} and interruption.state in ('settled', 'rejected_stale') ) or ( ${schema.sessionTurnAttempts.outcome} = 'interrupted_recoverable' and not exists ( select 1 from session_turn_attempts successor where successor.account_id = ${schema.sessionTurnAttempts.accountId} and successor.workspace_id = ${schema.sessionTurnAttempts.workspaceId} and successor.session_id = ${schema.sessionTurnAttempts.sessionId} and ( successor.started_at > ${schema.sessionTurnAttempts.startedAt} or ( successor.started_at = ${schema.sessionTurnAttempts.startedAt} and successor.id > ${schema.sessionTurnAttempts.id} ) ) ) and exists ( select 1 from session_events event where event.account_id = ${schema.sessionTurnAttempts.accountId} and event.workspace_id = ${schema.sessionTurnAttempts.workspaceId} and event.session_id = ${schema.sessionTurnAttempts.sessionId} and event.turn_id = ${schema.sessionTurnAttempts.turnId} and event.turn_attempt_id = ${schema.sessionTurnAttempts.id} and event.type = 'turn.recovery.requested' ) ) )`, ), ) .orderBy(asc(schema.sessionTurnAttempts.closedAt), asc(schema.sessionTurnAttempts.id)) .limit(1); return row ?? null; } /** * Return the exact current recovering turn's newest interrupted attempt when * its physical receipt is already durable but a pre-fix/partial workflow left * the paused session projected as recovering. This is DB-only settlement work: * the turn remains recovering for a later Resume and no claim is admitted. */ async function pausedSessionAttemptAwaitingRecoveryProjection( db: Database, workspaceId: string, sessionId: string, activeTurnId: string, ): Promise<{ attemptId: string } | null> { const [row] = await db .select({ attemptId: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessionTurnAttempts.workspaceId), eq(schema.sessionTurns.id, schema.sessionTurnAttempts.turnId), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), eq(schema.sessionTurnAttempts.turnId, activeTurnId), eq(schema.sessionTurnAttempts.state, "closed"), eq(schema.sessionTurnAttempts.outcome, "interrupted_recoverable"), isNotNull(schema.sessionTurnAttempts.quiescedAt), eq(schema.sessionTurns.status, "recovering"), isNull(schema.sessionTurns.activeAttemptId), // Provider recovery closes an attempt through its recovery-request // event, not an interruption row. Match the receipt transaction's two // evidence paths without borrowing an event from another attempt. sql`(exists ( select 1 from session_attempt_interruptions interruption where interruption.workspace_id = ${schema.sessionTurnAttempts.workspaceId} and interruption.session_id = ${schema.sessionTurnAttempts.sessionId} and interruption.attempt_id = ${schema.sessionTurnAttempts.id} and interruption.state in ('settled', 'rejected_stale') ) or exists ( select 1 from session_events event where event.account_id = ${schema.sessionTurnAttempts.accountId} and event.workspace_id = ${schema.sessionTurnAttempts.workspaceId} and event.session_id = ${schema.sessionTurnAttempts.sessionId} and event.turn_id = ${schema.sessionTurnAttempts.turnId} and event.turn_attempt_id = ${schema.sessionTurnAttempts.id} and event.type = 'turn.recovery.requested' ))`, ), ) .orderBy(desc(schema.sessionTurnAttempts.startedAt), desc(schema.sessionTurnAttempts.id)) .limit(1); return row ?? null; } async function latestSessionAttemptInterruption( db: Database, workspaceId: string, sessionId: string, ): Promise<{ attemptId: string; quiescedAt: Date | null; interruptionState: string; } | null> { const [latestAttempt] = await db .select({ attemptId: schema.sessionTurnAttempts.id, quiescedAt: schema.sessionTurnAttempts.quiescedAt, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), ), ) .orderBy(desc(schema.sessionTurnAttempts.startedAt), desc(schema.sessionTurnAttempts.id)) .limit(1); if (!latestAttempt) return null; const [interruption] = await db .select({ state: schema.sessionAttemptInterruptions.state }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), eq(schema.sessionAttemptInterruptions.attemptId, latestAttempt.attemptId), ), ) .orderBy( desc(schema.sessionAttemptInterruptions.requestedAt), desc(schema.sessionAttemptInterruptions.id), ) .limit(1); return interruption ? { ...latestAttempt, interruptionState: interruption.state, } : null; } async function queuedSteerHasUnquiescedPredecessor( db: Database, workspaceId: string, sessionId: string, predecessorAttemptIds: string[], ): Promise { if (predecessorAttemptIds.length === 0) return false; const [row] = await db .select({ attemptId: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .innerJoin( schema.sessionAttemptInterruptions, and( eq(schema.sessionAttemptInterruptions.workspaceId, schema.sessionTurnAttempts.workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, schema.sessionTurnAttempts.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, schema.sessionTurnAttempts.id), ), ) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), inArray(schema.sessionTurnAttempts.id, predecessorAttemptIds), isNull(schema.sessionTurnAttempts.quiescedAt), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", "settled", "rejected_stale", ]), ), ) .limit(1); return row !== undefined; } /** A pending background-command result that reports an idle containment * stop. Nothing used the box, so the notice wakes nothing on its own, not even * a held wait: it rides along with the next turn, which a person, another * input or the wait's timeout starts. */ function passiveCommandNoticeSql() { return sql`(${schema.sessionSystemUpdates.kind} = 'background_command_result' and ${schema.sessionSystemUpdates.payload} ->> 'state' = 'lost' and ${schema.sessionSystemUpdates.payload} ->> 'reason' = ${IDLE_COMMAND_CONTAINMENT_REASON})`; } /** The in-memory twin of `passiveCommandNoticeSql`, for updates already read. */ function isPassiveCommandNotice(update: { kind: string; payload: Record }) { return ( update.kind === "background_command_result" && update.payload.state === "lost" && update.payload.reason === IDLE_COMMAND_CONTAINMENT_REASON ); } async function pendingAgentSteerExistsTx( db: Database, workspaceId: string, sessionId: string, ): Promise { const [row] = await db .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), ), ) .limit(1); return row !== undefined; } /** * Whether the compaction-failure hold (`compactionFailureHoldSequenceTx`) is * what keeps this idle session from running: a hold applies, and neither an * Agent Steer nor any input committed after the failure is pending. */ async function sessionHeldByCompactionFailureTx( db: Database, workspaceId: string, sessionId: string, ): Promise { const holdSequence = await compactionFailureHoldSequenceTx(db, workspaceId, sessionId); if (holdSequence === null) return false; if (await pendingAgentSteerExistsTx(db, workspaceId, sessionId)) return false; const newer = await pendingSystemUpdateWakeClassesTx(db, workspaceId, sessionId, { pendingAfterSequence: holdSequence, }); return !newer.immediate && !newer.deferred && !newer.command; } /** Read durable session state without reserving a turn-worker slot or mutating it. */ /** * Which wake classes are represented among a session's pending machine inputs. * `immediate` kinds make the session runnable even against a current * `wait_for_input` declaration; deferred child notices only do so without one. * Command results are separate: only a current explicit wait lets them wake, * and an idle-containment notice never does (see `passiveCommandNoticeSql`). * `pendingAfterSequence` limits the answer to inputs whose pending event is * newer than a compaction-failure hold (`compactionFailureHoldSequenceTx`). */ async function pendingSystemUpdateWakeClassesTx( db: Database, workspaceId: string, sessionId: string, options: { pendingAfterSequence?: number | null } = {}, ): Promise<{ immediate: boolean; deferred: boolean; command: boolean }> { const pendingAfterSequence = options.pendingAfterSequence ?? null; const rows = await db .selectDistinct({ kind: schema.sessionSystemUpdates.kind, passive: passiveCommandNoticeSql(), }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), pendingAfterSequence === null ? undefined : systemUpdatePendingAfterSequenceSql(db, workspaceId, sessionId, pendingAfterSequence), ), ); let immediate = false; let deferred = false; let command = false; for (const row of rows) { if (row.kind === "background_command_result") { if (!row.passive) command = true; continue; } const wakeClass = SESSION_SYSTEM_UPDATE_WAKE_CLASS[row.kind as SessionSystemUpdateKind] ?? "immediate"; if (wakeClass === "deferred") deferred = true; else immediate = true; } return { immediate, deferred, command }; } /** * Evaluate the durable session-level wait against the newest finished turn * that can decide it (`sessionInputWaitDecidingTurnSql`) and the PostgreSQL * clock. A newer finished turn that a person did not start is input that * supersedes the declaration. A person's turn that does not wait again leaves * the wait held, so a later child result or background command still wakes the * agent; the unchanged deadline bounds it. */ async function sessionInputWaitStateTx( db: Database, workspaceId: string, sessionId: string, wait: { inputWaitTurnId: string | null; inputWaitUntil: Date | null; }, ): Promise<{ disposition: "none" | "held" | "timeout" | "superseded" }> { if (!wait.inputWaitTurnId || !wait.inputWaitUntil) { return { disposition: "none" }; } const [decidingTurn] = await db .select({ id: schema.sessionTurns.id, // now() is stable for this transaction; reading it here retains the // deciding-turn snapshot without another round trip for its clock. transactionTime: sql`now()`, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), sql`${schema.sessionTurns.finishedAt} is not null`, sessionInputWaitDecidingTurnSql(schema.sessionTurns, wait.inputWaitTurnId), ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), ) .limit(1); if (decidingTurn?.id !== wait.inputWaitTurnId) { return { disposition: "superseded" }; } const value = decidingTurn.transactionTime; if (value === undefined) throw new Error("Failed to read the transaction clock"); const dbNow = value instanceof Date ? value : new Date(value); return { disposition: wait.inputWaitUntil.getTime() <= dbNow.getTime() ? "timeout" : "held", }; } /** A keyset cursor lets busy candidates coexist with later eligible sessions. * It is inventory progress only; every target is rechecked and a restart * safely begins another idempotent lap. */ export function repairMissingQuiescenceReceiptWakes( db: Database, limit = 100, after: QuiescenceReceiptWakeRepairCursor | null = null, ) { return repairMissingQuiescenceReceiptWakesWith(peekSessionWork, db, limit, after); } async function sessionRowExists( db: Database, workspaceId: string, sessionId: string, ): Promise { const [row] = await db .select({ id: schema.sessions.id }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return row !== undefined; } export async function peekSessionWork( db: Database, workspaceId: string, sessionId: string, includeAdmissionFence = false, observerAccountId?: string, ): Promise { const observe = async (scopedDb: Database): Promise => { // An observer cannot distinguish absent rows from rows hidden by RLS. // Do not infer deletion or settle business state from either condition. if (observerAccountId) { const [visible] = await scopedDb .select({ id: schema.sessions.id }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!visible) return { kind: "unavailable" }; } let effectiveControl: Awaited>; try { effectiveControl = await evaluateSessionControl(scopedDb, workspaceId, sessionId, { lock: "share", }); } catch (error) { // The shared workspace-control lock waits for a concurrent deletion to // commit, so the session can vanish between the read above and this one. // That is an absent session, observed exactly like the read below // observes it, not a broken invariant (which would fail the activity and // retry until the next attempt saw the deletion). if ( error instanceof SessionControlInvariantError && !(await sessionRowExists(scopedDb, workspaceId, sessionId)) ) { return { kind: observerAccountId ? "unavailable" : "idle" }; } throw error; } // This is an advisory control observation, not a session/configuration // read. Do not transfer frozen prompts, tool catalogs or other payloads // that none of the decisions below consumes. const [session] = await scopedDb .select({ accountId: schema.sessions.accountId, status: schema.sessions.status, activeTurnId: schema.sessions.activeTurnId, lastSequence: schema.sessions.lastSequence, admissionBlock: schema.sessions.admissionBlock, compactRequested: schema.sessions.compactRequested, inputWaitTurnId: schema.sessions.inputWaitTurnId, inputWaitUntil: schema.sessions.inputWaitUntil, contentArchiveState: schema.sessions.contentArchiveState, importedArchiveImportId: schema.sessions.importedArchiveImportId, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!session) return { kind: observerAccountId ? "unavailable" : "idle" }; // An archived (or archiving) or imported session is read-only: the // database refuses every turn, attempt and wake write for it, so there is // no work to admit and no receipt that could still commit. Restoring its // content makes it live again and the next wake peeks it afresh. if (session.contentArchiveState !== null || session.importedArchiveImportId !== null) { return { kind: "read-only" }; } // Pure event appends can leave the wide session projection behind. Admission // settlement fences against the allocation cursor, so observe that same // authority here without taking a writer lock during this advisory peek. let admissionSequence = session.lastSequence; let admissionWakeRevision = 0; if (includeAdmissionFence) { const [cursor] = await scopedDb .select({ lastSequence: schema.sessionEventCursors.lastSequence }) .from(schema.sessionEventCursors) .where( and( eq(schema.sessionEventCursors.accountId, session.accountId), eq(schema.sessionEventCursors.workspaceId, workspaceId), eq(schema.sessionEventCursors.sessionId, sessionId), ), ) .limit(1); if (!cursor || cursor.lastSequence < session.lastSequence) { throw new SessionControlInvariantError( `Session admission cursor is missing or behind projection for session ${sessionId}`, ); } admissionSequence = cursor.lastSequence; const [wake] = await scopedDb .select({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, sessionId), ), ) .limit(1); admissionWakeRevision = wake ? Number(wake.wakeRevision) : 0; } const fence = includeAdmissionFence ? { admissionFence: { lastSequence: admissionSequence, controlVersion: effectiveControl.controlVersion, }, admissionWakeRevision, } : {}; const runnable = { kind: "runnable", ...fence } as const; const [interruption] = await scopedDb .select({ attemptId: schema.sessionAttemptInterruptions.attemptId }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, sessionId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .orderBy( asc(schema.sessionAttemptInterruptions.requestedAt), asc(schema.sessionAttemptInterruptions.id), ) .limit(1); if (interruption) { return { kind: "interruption-pending", attemptId: interruption.attemptId, }; } // Physical quiescence finishes an already-accepted interruption; it is not // new session work. Reconcile the missing receipt even while control stays // paused, otherwise the pause itself can strand this session and every // ancestor behind a permanent `settlement: stopping` projection. const awaitingQuiescence = await nextSessionAttemptAwaitingQuiescence( scopedDb, workspaceId, sessionId, "inference", ); if (awaitingQuiescence) { return { kind: "cancellation-wait", attemptId: awaitingQuiescence.attemptId, }; } if (effectiveControl.state !== "active") { // A receipt may already be durable while an older workflow/image left // the paused session's public status at `recovering`. Route that exact // attempt through the same DB-only reconciliation activity. The activity // skips Temporal inspection for a quiesced receipt, parks only the // session projection, and preserves the logical turn for Resume. if ( effectiveControl.settlement === null && session.status === "recovering" && session.activeTurnId ) { const awaitingProjection = await pausedSessionAttemptAwaitingRecoveryProjection( scopedDb, workspaceId, sessionId, session.activeTurnId, ); if (awaitingProjection) { return { kind: "cancellation-wait", attemptId: awaitingProjection.attemptId, }; } } return { kind: "idle" }; } if (session.admissionBlock) return { kind: "admission-blocked" }; // A core waiter (any provider) is the only waiter written after its // provider's cutover; it keeps that provider's legacy reference shape // (`provider: "xai"` for SuperGrok, `"claude"` for Claude, none for // Codex), so the workflow waits on it exactly as on a legacy waiter. A // row that no longer belongs to the session's active waiting turn // becomes an immediate check, whose reconcile deletes it, rather than a // sleep until its next check. const coreCapacityWait = await readSubscriptionCoreWaiterInTransaction(scopedDb, { workspaceId, sessionId, }); if (coreCapacityWait) { return { kind: "capacity-wait", ref: subscriptionCoreCodexCapacityWaitRef(coreCapacityWait), }; } if (session.activeTurnId) { const [turn] = await scopedDb .select({ id: schema.sessionTurns.id, sessionId: schema.sessionTurns.sessionId, status: schema.sessionTurns.status, metadata: schema.sessionTurns.metadata, triggerEventId: schema.sessionTurns.triggerEventId, executionGeneration: schema.sessionTurns.executionGeneration, activeAttemptId: schema.sessionTurns.activeAttemptId, scheduledTaskRunId: schema.sessionTurns.scheduledTaskRunId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, session.activeTurnId), ), ) .limit(1); if (!turn) { throw new Error( `Session ${sessionId} points to missing active turn ${session.activeTurnId}`, ); } if (turn.status === "recovering" || turn.status === "waiting_capacity") { const setupUnknown = sandboxSetupOutcomeUnknownFromTurnMetadata(turn.metadata); if (turn.status === "recovering" && setupUnknown) { // Existing workflow releases already park this wire kind. Do not // introduce a new peek kind that an older control worker could // mistake for runnable work during a rolling deployment. return { kind: "admission-blocked", reason: "sandbox_setup_outcome_unknown", ref: setupUnknown, }; } const setupExhausted = sandboxSetupRecoveryExhaustedFromTurnMetadata(turn.metadata); if (turn.status === "recovering" && setupExhausted) { return { kind: "admission-blocked", reason: "sandbox_setup_recovery_exhausted", ref: setupExhausted, }; } const lifecycleWait = sandboxLifecycleWaitFromTurnMetadata(turn.metadata); if (turn.status === "recovering" && lifecycleWait) { const [lease] = await scopedDb .select({ leaseEpoch: schema.sandboxLeases.leaseEpoch, liveness: schema.sandboxLeases.liveness, rotationRequestedAt: schema.sandboxLeases.rotationRequestedAt, }) .from(schema.sandboxLeases) .where( and( eq(schema.sandboxLeases.workspaceId, workspaceId), eq(schema.sandboxLeases.sandboxGroupId, lifecycleWait.sandboxGroupId), ), ) .limit(1); if (sandboxLifecycleWaitIsPending(lifecycleWait, lease)) { return { kind: "sandbox-lifecycle-wait", ref: lifecycleWait }; } } const recoveryRetry = turn.status === "recovering" ? sessionTurnRecoveryRetryFromMetadata(turn.metadata) : null; if ( recoveryRetry && (await transactionNow(scopedDb)).getTime() < Date.parse(recoveryRetry.notBefore) ) { // Wakes are hints; this deadline is the authority. A person's new // message is the one thing that ends the backoff early. const [newInput] = await scopedDb .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.type, "user.message"), gt(schema.sessionEvents.sequence, recoveryRetry.afterSequence), ), ) .limit(1); if (!newInput) { // Existing workflow releases close on this kind and rely on the // recovery's delayed wake; current ones wait until the deadline. return { kind: "admission-blocked", reason: "recovery_backoff", ref: recoveryRetry }; } } return runnable; } if (turn.status === "requires_action") { const [currentTrigger] = await scopedDb .select({ sequence: schema.sessionEvents.sequence }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.id, turn.triggerEventId), ), ) .limit(1); if (!currentTrigger) { throw new Error(`Turn ${turn.id} points to missing trigger ${turn.triggerEventId}`); } const [actionResponse] = await scopedDb .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), inArray(schema.sessionEvents.type, [ "user.approvalDecision", "user.humanInputResponse", ]), gt(schema.sessionEvents.sequence, currentTrigger.sequence), ), ) // One question answer is accepted per pause and only the trigger // carries it, so it resumes first. Approval decisions are applied // together by any resume (those up to its trigger), and one recorded // after the trigger resumes the turn again. .orderBy( sql`(${schema.sessionEvents.type} = 'user.humanInputResponse') desc`, desc(schema.sessionEvents.sequence), desc(schema.sessionEvents.id), ) .limit(1); if (actionResponse) { return { kind: "approval-pending", triggerEventId: actionResponse.id, ...fence, }; } const [expiringHumanInput] = await scopedDb .select({ id: schema.sessionHumanInputRequests.id, expiresAt: schema.sessionHumanInputRequests.expiresAt, }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, sessionId), eq(schema.sessionHumanInputRequests.turnId, turn.id), eq(schema.sessionHumanInputRequests.turnGeneration, turn.executionGeneration), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), isNotNull(schema.sessionHumanInputRequests.expiresAt), ), ) .orderBy( sql`${schema.sessionHumanInputRequests.expiresAt} asc nulls last`, asc(schema.sessionHumanInputRequests.id), ) .limit(1); const [expiringInteractionIntervention] = await scopedDb .select({ id: schema.interactionInterventions.id, expiresAt: schema.interactionInterventions.expiresAt, }) .from(schema.interactionInterventions) .where( and( eq(schema.interactionInterventions.workspaceId, workspaceId), eq(schema.interactionInterventions.originatingSessionId, sessionId), eq(schema.interactionInterventions.originatingTurnId, turn.id), eq(schema.interactionInterventions.status, "open"), isNotNull(schema.interactionInterventions.originatingToolCallId), ), ) .orderBy( asc(schema.interactionInterventions.expiresAt), asc(schema.interactionInterventions.id), ) .limit(1); // A scheduled run's frozen approval timeout joins the same earliest- // deadline choice; the workflow sleeps on it with a durable timer. const scheduledDeadline = await scheduledHumanWaitDeadlineInRlsContext( scopedDb, workspaceId, turn, ); const candidates: Array<{ at: number; wait: Extract; }> = []; if (expiringHumanInput?.expiresAt) { candidates.push({ at: expiringHumanInput.expiresAt.getTime(), wait: { kind: "approval-wait", humanInputRequestId: expiringHumanInput.id, expiresAt: expiringHumanInput.expiresAt.toISOString(), }, }); } if (expiringInteractionIntervention) { candidates.push({ at: expiringInteractionIntervention.expiresAt.getTime(), wait: { kind: "approval-wait", interactionInterventionId: expiringInteractionIntervention.id, expiresAt: expiringInteractionIntervention.expiresAt.toISOString(), }, }); } if (scheduledDeadline) { candidates.push({ at: Date.parse(scheduledDeadline.expiresAt), wait: { kind: "approval-wait", scheduledRunTimeout: { runId: scheduledDeadline.runId, turnId: turn.id }, expiresAt: scheduledDeadline.expiresAt, }, }); } // Stable: on a tie, the per-request deadlines keep their precedence. candidates.sort((left, right) => left.at - right.at); return candidates[0]?.wait ?? { kind: "approval-wait" }; } if (turn.status === "running") { if (observerAccountId && turn.activeAttemptId) { const [attempt] = await scopedDb .select({ id: schema.sessionTurnAttempts.id, temporalWorkflowId: schema.sessionTurnAttempts.temporalWorkflowId, temporalWorkflowRunId: schema.sessionTurnAttempts.temporalWorkflowRunId, temporalActivityId: schema.sessionTurnAttempts.temporalActivityId, quiescedAt: schema.sessionTurnAttempts.quiescedAt, }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.accountId, observerAccountId), eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, sessionId), eq(schema.sessionTurnAttempts.turnId, turn.id), eq(schema.sessionTurnAttempts.id, turn.activeAttemptId), eq(schema.sessionTurnAttempts.executionGeneration, turn.executionGeneration), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); if (attempt) return { kind: "attempt-owned", turnId: turn.id, attemptId: attempt.id, executionGeneration: turn.executionGeneration, activityRef: { workflowId: attempt.temporalWorkflowId, workflowRunId: attempt.temporalWorkflowRunId, activityId: attempt.temporalActivityId, quiesced: attempt.quiescedAt !== null, }, }; } throw new Error( `Session workflow reached admission with turn ${turn.id} still owned by attempt ${turn.activeAttemptId ?? "none"}`, ); } throw new Error(`Session ${sessionId} has terminal active turn ${turn.id} (${turn.status})`); } // A message waiting for the personal machine's owner is not work yet. const queued = await runnableQueuedTurnExists(scopedDb, { accountId: session.accountId, workspaceId, sessionId, sources: ["user", "api"], }); if (queued || session.compactRequested) return runnable; const waitState = await sessionInputWaitStateTx(scopedDb, workspaceId, sessionId, session); const inputWaitPeek = session.inputWaitTurnId && session.inputWaitUntil && waitState.disposition !== "none" ? ({ kind: "input-wait", disposition: waitState.disposition, waitTurnId: session.inputWaitTurnId, deadlineAt: session.inputWaitUntil.toISOString(), } as const) : null; const [pendingUpdate] = await scopedDb .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .limit(1); if (!pendingUpdate) return inputWaitPeek ?? { kind: "idle" }; // After a terminal compaction failure, inputs that were already pending // saw the unchanged history and stay held; only an Agent Steer or input // committed after the failure is new truth that may start one attempt. const holdSequence = await compactionFailureHoldSequenceTx(scopedDb, workspaceId, sessionId); if ( holdSequence !== null && (await pendingAgentSteerExistsTx(scopedDb, workspaceId, sessionId)) ) { return runnable; } // Immediate machine input wakes a wait and becomes the next turn. Deferred // child status notices stay parked until the wait times out, is superseded // by newer input, or an immediate input arrives. const wakeClasses = await pendingSystemUpdateWakeClassesTx(scopedDb, workspaceId, sessionId, { pendingAfterSequence: holdSequence, }); if (wakeClasses.immediate || (wakeClasses.command && waitState.disposition === "held")) { return runnable; } return inputWaitPeek ?? (wakeClasses.deferred ? runnable : { kind: "idle" }); }; return observerAccountId ? await withRlsContext(db, { accountId: observerAccountId, workspaceId }, observe) : await withWorkspaceRls(db, workspaceId, observe); } class SessionInputWaitSettlementStaleError extends Error { readonly name = "SessionInputWaitSettlementStaleError"; } export type SettleSessionInputWaitResult = | { action: "held"; events: []; workflowWakeRevision: number } | { action: "timeout"; events: SessionEvent[]; workflowWakeRevision: number | null } | { action: "superseded"; events: SessionEvent[] } | { action: "stale"; events: [] }; /** * Retire one exact durable wait. Timeout settlement atomically appends the wait * audit event, queues typed model input, and registers its workflow wake. * Supersession records only the audit boundary because the newer finished turn * already consumed the waking input. */ async function settleSessionInputWaitInActivity( db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; waitTurnId: string; disposition: "held" | "timeout" | "superseded"; }, ): Promise { if (input.disposition === "timeout") { const [expected] = await db .select({ inputWaitTurnId: schema.sessions.inputWaitTurnId, inputWaitUntil: schema.sessions.inputWaitUntil, inputWaitReason: schema.sessions.inputWaitReason, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if ( !expected || expected.inputWaitTurnId !== input.waitTurnId || !expected.inputWaitUntil || !expected.inputWaitReason ) { return { action: "stale", events: [] }; } const deadlineAt = expected.inputWaitUntil.toISOString(); const reason = expected.inputWaitReason; const causalAuthority = await sameSessionCausalAuthorityTx(db as unknown as Database, { ...input, turnId: input.waitTurnId, }); try { const result = await addSessionSystemUpdateWithSourceMutation( db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: "session_wait_timeout", personalConnectionDelegations: causalAuthority?.personalConnectionDelegations ?? [], mcpAccountBindings: causalAuthority?.mcpAccountBindings ?? null, // Missing causal authority resolves the shared pool on insert. ...(causalAuthority ? { xaiProviderAccountAuthoritySnapshot: causalAuthority.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: causalAuthority.claudeProviderAccountAuthoritySnapshot, subscriptionAuthority: causalAuthority.subscriptionAuthority, } : {}), lineage: causalAuthority?.lineage ?? {}, classification: "info", sourceId: input.waitTurnId, dedupeKey: `session-input-wait-timeout:${input.waitTurnId}`, summary: "The wait_for_input timeout elapsed without newer input.", payload: { type: "session_wait_timeout", waitTurnId: input.waitTurnId, deadlineAt, reason, }, }, async () => undefined, { prepareSource: async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if ( !session || session.inputWaitTurnId !== input.waitTurnId || session.inputWaitUntil?.toISOString() !== deadlineAt || session.inputWaitReason !== reason ) { throw new SessionInputWaitSettlementStaleError(); } const state = await sessionInputWaitStateTx( tx, input.workspaceId, input.sessionId, session, ); if (state.disposition !== "timeout") { throw new SessionInputWaitSettlementStaleError(); } const now = await transactionNow(tx); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.wait.finished", payload: { waitTurnId: input.waitTurnId, outcome: "timeout", deadlineAt, reason, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session.wait.finished event"); await tx .update(schema.sessions) .set({ inputWaitTurnId: null, inputWaitUntil: null, inputWaitReason: null, inputWaitSetAt: null, lastSequence: session.lastSequence + 1, updatedAt: now, }) .where(eq(schema.sessions.id, input.sessionId)); return { lineage: { waitTurnId: input.waitTurnId, deadlineAt }, events: [mapEvent(event)], }; }, }, ); if (!result.added) return { action: "stale", events: [] }; return { action: "timeout", events: result.events, workflowWakeRevision: result.workflowWakeRevision, }; } catch (error) { if (error instanceof SessionInputWaitSettlementStaleError) { return { action: "stale", events: [] }; } throw error; } } return await withSessionActivitySavepoint(db, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session || session.inputWaitTurnId !== input.waitTurnId) { return { action: "stale", events: [] } as const; } const state = await sessionInputWaitStateTx(tx, input.workspaceId, input.sessionId, session); if (state.disposition === "held" && input.disposition === "held") { if (!session.temporalWorkflowId || !session.inputWaitUntil) { throw new SessionControlInvariantError( `Session ${input.sessionId} has no durable input-wait workflow identity`, ); } const wake = await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId, reason: "session_input_wait_deadline", notBefore: session.inputWaitUntil, }); return { action: "held", events: [], workflowWakeRevision: wake, } as const; } if (state.disposition !== "superseded" || input.disposition !== "superseded") { return { action: "stale", events: [] } as const; } const now = await transactionNow(tx); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.wait.finished", payload: { waitTurnId: input.waitTurnId, outcome: "input", deadlineAt: session.inputWaitUntil?.toISOString() ?? null, reason: session.inputWaitReason, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append session.wait.finished event"); await tx .update(schema.sessions) .set({ inputWaitTurnId: null, inputWaitUntil: null, inputWaitReason: null, inputWaitSetAt: null, lastSequence: session.lastSequence + 1, updatedAt: now, }) .where(eq(schema.sessions.id, input.sessionId)); return { action: "superseded", events: [mapEvent(event)] } as const; }); } export async function settleSessionInputWait( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waitTurnId: string; disposition: "held" | "timeout" | "superseded"; }, ): Promise { return await withWorkspaceSessionActivityRls(db, input.workspaceId, (scopedDb) => settleSessionInputWaitInActivity(scopedDb, input), ); } /** Park only the exact pre-dispatch snapshot; late failures cannot block new work. */ export async function blockSessionWorkBeforeAttemptClaim( db: Database, workspaceId: string, input: { accountId: string; sessionId: string; workflowId: string; attemptId: string; fence: SessionAdmissionFence; /** Wake revision observed with the fence. A wake registered since then * (access granted, membership restored, machine changed) may have fixed * what the claim saw, so the work is re-read instead of parked. */ wakeRevision?: number; reason: StoredSessionAdmissionBlock["reason"]; sqlState: string | null; }, ): Promise<{ action: "blocked" | "stale" | "terminal"; events: SessionEvent[] }> { return retrySessionActivityRls( db, workspaceId, { stage: "session_admission.block", eventTypes: ["session.status.changed"], maxAttempts: 3, }, async (scopedDb) => scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if ( !session || session.accountId !== input.accountId || (session.temporalWorkflowId !== null && session.temporalWorkflowId !== input.workflowId) ) { return { action: "stale", events: [] }; } if (session.status === "cancelled" || session.status === "failed") return { action: "terminal", events: [] }; if (session.admissionBlock?.attemptId === input.attemptId) return { action: "blocked", events: [] }; if (session.lastSequence !== input.fence.lastSequence) { return { action: "stale", events: [] }; } const control = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined, }, ); if (control.state !== "active" || control.controlVersion !== input.fence.controlVersion) return { action: "stale", events: [] }; const [live] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); if (live) return { action: "stale", events: [] }; if (input.wakeRevision !== undefined) { const [wake] = await tx .select({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), ), ) .limit(1); if ((wake ? Number(wake.wakeRevision) : 0) !== input.wakeRevision) return { action: "stale", events: [] }; } const now = new Date(); const block = StoredSessionAdmissionBlock.parse({ reason: input.reason, sqlState: input.sqlState, retryPolicy: "explicit_recheck", blockedAt: now.toISOString(), attemptId: input.attemptId, fence: { lastSequence: input.fence.lastSequence, controlVersion: input.fence.controlVersion, }, previousStatus: session.status as SessionStatus, }); const publicBlock = projectSessionAdmissionBlock(block); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.status.changed", payload: { status: "requires_action", code: "admission_blocked", admissionBlock: publicBlock, }, }, "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ admissionBlock: block, status: "requires_action", lastSequence: session.lastSequence + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { action: "blocked", events: [mapEvent(event!)] }; }), ); } /** What changed that may fix a blocked chat's saved message. */ export type SessionAdmissionAccessChange = "personal_resource" | "membership" | "machine"; function admissionBlockFixedBy( block: Pick, change: SessionAdmissionAccessChange, ): boolean { // A bare permission refusal carries no finer cause; any access change may fix it. if (block.reason === "database_claim_rejected") return block.sqlState === "42501"; if (block.reason === "initiator_membership_required") return change === "membership"; return change === "personal_resource" || change === "machine"; } export type ReleaseSessionAdmissionBlocksResult = { released: Array<{ sessionId: string; events: SessionEvent[] }>; nudged: string[]; }; /** * Access changed (a grant was issued, membership restored, the chat moved * machine). Let saved messages held by a matching admission block start by * themselves: clear the block under the session's event-write lock and register * a wake, so the workflow re-reads and claims once. The claim still enforces * access, so a release that did not fix anything parks the work again; a * paused, cancelled or edited chat is left alone. Listed sessions without a * block still get a wake: their claim may be in flight against the old access, * and the wake revision makes that claim's block stale instead of parking it. */ export async function releaseSessionAdmissionBlocksAfterAccessChange( db: Database, input: { accountId: string; workspaceId: string; change: SessionAdmissionAccessChange; sessionIds?: readonly string[]; }, ): Promise { const result: ReleaseSessionAdmissionBlocksResult = { released: [], nudged: [] }; const listed = input.sessionIds ? [...new Set(input.sessionIds)] : null; if (listed && listed.length === 0) return result; // Workspace-wide changes also wake chats whose next message is queued and not // yet claimed: a claim refused just before this change may record its block // after this scan, and the wake makes that block stale so the claim retries. const awaitingClaim = sql`(${schema.sessions.activeTurnId} is null and exists ( select 1 from ${schema.sessionTurns} where ${schema.sessionTurns.workspaceId} = ${schema.sessions.workspaceId} and ${schema.sessionTurns.sessionId} = ${schema.sessions.id} and ${schema.sessionTurns.status} = 'queued'))`; const candidates = await withWorkspaceSessionActivityRls( db, input.workspaceId, async (scopedDb) => scopedDb .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.accountId, input.accountId), listed ? inArray(schema.sessions.id, listed) : sql`(${schema.sessions.admissionBlock} is not null or ${awaitingClaim})`, ), ) .orderBy(sql`(${schema.sessions.admissionBlock} is null)`, asc(schema.sessions.id)) .limit(200), ); for (const candidate of candidates) { const outcome = await retrySessionActivityRls( db, input.workspaceId, { stage: "session_admission.release", eventTypes: ["session.status.changed"], maxAttempts: 3, }, async (scopedDb) => scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [candidate.id], }); const session = locks.sessions[0]; if (!session || session.accountId !== input.accountId) return null; if (session.status === "cancelled" || session.status === "failed") return null; const workflowId = session.temporalWorkflowId ?? `session-${session.id}`; const block = session.admissionBlock; if (!block) { if (session.activeTurnId !== null) return null; const [queued] = await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, session.id), eq(schema.sessionTurns.status, "queued"), ), ) .limit(1); if (!queued) return null; await registerSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: workflowId, reason: "admission_access_changed", }); return { kind: "nudged" as const }; } if (!admissionBlockFixedBy(block, input.change)) return null; // A paused chat keeps its block; Resume releases it when it runs. const control = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, session.id, { workspaceControl: locks.control ?? undefined }, ); if (control.state !== "active") return null; const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: session.lastSequence + 1, type: "session.status.changed", payload: { status: block.previousStatus, code: "admission_access_changed" }, }, "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ admissionBlock: null, status: block.previousStatus, lastSequence: session.lastSequence + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, session.id), ), ); await registerSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: workflowId, reason: "admission_access_changed", }); return { kind: "released" as const, events: [mapEvent(event!)] }; }), ); if (outcome?.kind === "released") result.released.push({ sessionId: candidate.id, events: outcome.events }); else if (outcome?.kind === "nudged") result.nudged.push(candidate.id); } return result; } export type FailSessionWorkBeforeAttemptClaimInput = { accountId: string; sessionId: string; workflowId: string; trigger: SessionWorkTrigger; error: string; /** Already-classified admission facts from the failed worker activity. */ admissionFailure?: { disposition: "retryable" | "permanent"; code: "db_deadlock" | "db_serialization_failure" | "db_failure" | "claim_invariant"; }; }; export type FailSessionWorkBeforeAttemptClaimResult = | { action: "failed"; turnId: string | null; events: SessionEvent[] } | { action: "terminal"; turnId: null; events: [] } | { action: "stale"; turnId: null; events: [] }; /** Maintenance-only authorization, supplied by the migration operator's exact * manifest, never inferred from idle status, Pause, or elapsed time. */ export type InterruptedTurnRetirementProof = { turnId: string; expectedVersion: number; expectedLastSequence: number; operationId: string; }; export type RecoverSessionWorkFailedBeforeAttemptClaimInput = { accountId: string; sessionId: string; workflowId: string; operationId: string; expectedFailureEventSequence: number; expectedLastSequence: number; failedUpdateIds: string[]; }; export type RecoverSessionWorkFailedBeforeAttemptClaimResult = | { action: "recovered"; event: SessionEvent; workflowWakeRevision: number; restoredUpdateIds: string[]; } | { action: "already_recovered"; event: SessionEvent } | { action: "stale"; event: null }; /** * Terminally settle a permanent admission failure that happened before an * attempt row existed. The workflow supplies the exact trigger recorded in * Temporal history; this transaction re-evaluates it under the canonical * control -> workspace -> session -> turn lock order and refuses stale, * paused, capacity-blocked, or concurrently claimed work. No attempt row is * fabricated because provider/tool execution never started. */ export async function failSessionWorkBeforeAttemptClaim( db: Database, workspaceId: string, input: FailSessionWorkBeforeAttemptClaimInput, ): Promise { return await settleSessionWorkBeforeAttemptClaim(db, workspaceId, input); } /** Explicit operator maintenance, not normal admission and never a reaper * age heuristic. Exact manifest fences and physical quiescence are mandatory. */ export async function retireInterruptedSessionTurn( db: Database, workspaceId: string, input: { accountId: string; sessionId: string; workflowId: string; } & InterruptedTurnRetirementProof, ): Promise { return await settleSessionWorkBeforeAttemptClaim( db, workspaceId, { accountId: input.accountId, sessionId: input.sessionId, workflowId: input.workflowId, trigger: { kind: "next" }, error: "Interrupted work was terminally retired by the operator without replay.", }, input, ); } /** Operator retirement is a terminal historical receipt, not fresh execution * intent for the parent. Called only after all manifest fences have passed, * in the same transaction as their retirement. Normal child delivery is not * changed, and neither existing model history nor parent control is touched. */ export async function recordRetiredChildNotice( db: Database, workspaceId: string, input: { accountId: string; sessionId: string } & InterruptedTurnRetirementProof, ): Promise { return await retrySessionActivityRls( db, workspaceId, { stage: "session_lifecycle_outbox.retirement_notice", eventTypes: ["system.update.settled"], maxAttempts: 3, }, async (scoped) => await scoped.transaction(async (tx) => { const locks = await lockChildLifecycleOutboxWriteRowsTx( tx as unknown as Database, workspaceId, { sessionId: input.sessionId, turnId: input.turnId, }, ); const child = locks.session; if (!locks.workspace || child.accountId !== input.accountId || child.status !== "failed") throw new Error("Retired child notice scope or terminal state changed"); if (!child.parentSessionId) return null; const parent = locks.sessions.find((row) => row.id === child.parentSessionId); const turn = locks.turns.find((row) => row.id === input.turnId); if (!parent || !turn || turn.status !== "failed" || turn.sessionId !== child.id) throw new Error("Retired child notice lost its canonical parent or turn"); const [terminal] = await tx .select({ id: schema.sessionEvents.id, payload: schema.sessionEvents.payload, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, child.id), eq(schema.sessionEvents.turnId, turn.id), eq(schema.sessionEvents.type, "turn.failed"), sql`${schema.sessionEvents.payload}->>'code' = 'interrupted_turn_retired'`, sql`${schema.sessionEvents.payload}->>'retirementOperationId' = ${input.operationId}`, sql`${schema.sessionEvents.payload}->>'retiredVersion' = ${String(input.expectedVersion)}`, sql`${schema.sessionEvents.payload}->>'retiredLastSequence' = ${String(input.expectedLastSequence)}`, ), ) .limit(1); if ( !terminal || sessionEventPayloadRecord(terminal.payload, terminal.payloadCodecVersion) .parentNotificationMode !== "timeline_only" ) throw new Error("Retired child notice requires the notification-only retirement receipt"); const [existing] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, parent.id), eq(schema.sessionEvents.type, "system.update.settled"), sql`${schema.sessionEvents.payload}->>'retirementOperationId' = ${input.operationId}`, sql`${schema.sessionEvents.payload}->>'childTerminalEventId' = ${terminal.id}`, ), ) .limit(1); if (existing) return mapEvent(existing); // A terminal historical retirement also supersedes this child's obsolete // nonterminal notices. Preserve earlier terminal answers and all unrelated // senders. Captured outbox retries lose atomically at their source callback. const nonterminalKinds = [ "child_requires_action", "child_requires_action_resolved", "child_paused", "child_waiting_capacity", "child_progress", ]; const obsoleteInput = or( inArray(schema.sessionSystemUpdates.kind, nonterminalKinds), and( eq(schema.sessionSystemUpdates.kind, "child_terminal_result"), sql`${schema.sessionSystemUpdates.payload}->>'turnId' = ${turn.id}`, ), ); const obsoleteOutbox = or( inArray(schema.sessionSystemUpdateOutbox.kind, nonterminalKinds), and( eq(schema.sessionSystemUpdateOutbox.kind, "child_terminal_result"), sql`${schema.sessionSystemUpdateOutbox.payload}->>'turnId' = ${turn.id}`, ), ); const supersededInputs = await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, parent.id), eq(schema.sessionSystemUpdates.sourceId, child.id), eq(schema.sessionSystemUpdates.state, "pending"), obsoleteInput, ), ) .returning({ id: schema.sessionSystemUpdates.id }); const supersededOutbox = await tx .update(schema.sessionSystemUpdateOutbox) .set({ status: "failed", lastError: "Superseded by operator retirement; see the parent timeline receipt.", updatedAt: new Date(), }) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, workspaceId), eq(schema.sessionSystemUpdateOutbox.sourceSessionId, child.id), eq(schema.sessionSystemUpdateOutbox.targetSessionId, parent.id), eq(schema.sessionSystemUpdateOutbox.status, "pending"), obsoleteOutbox, ), ) .returning({ id: schema.sessionSystemUpdateOutbox.id }); const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: parent.accountId, workspaceId, sessionId: parent.id, sequence: parent.lastSequence + 1, type: "system.update.settled", payload: { notificationOnly: true, reason: "operator_retirement", retirementOperationId: input.operationId, childSessionId: child.id, childTurnId: turn.id, childTerminalEventId: terminal.id, supersededUpdateIds: supersededInputs.map((row) => row.id).sort(), supersededOutboxIds: supersededOutbox.map((row) => row.id).sort(), members: [ { id: terminal.id, kind: "child_terminal_result", classification: "failure", sourceId: child.id, summary: "Child work was interrupted and retired without replay.", }, ], }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Retired child notice was not recorded"); await tx .update(schema.sessions) .set({ lastSequence: parent.lastSequence + 1, updatedAt: now }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, parent.id)), ); return mapEvent(event); }), ); } async function settleSessionWorkBeforeAttemptClaim( db: Database, workspaceId: string, input: FailSessionWorkBeforeAttemptClaimInput, retirement?: InterruptedTurnRetirementProof, ): Promise { return await retrySessionActivityRls( db, workspaceId, { stage: "session_lifecycle_outbox.fail_before_attempt_claim", eventTypes: [ "child_terminal_result", "session.status.changed", "turn.failed", "user.humanInputResponse", ], maxAttempts: 3, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const baseLocks = await lockChildLifecycleOutboxWriteRowsTx( tx as unknown as Database, workspaceId, { sessionId: input.sessionId }, ); const session = baseLocks.session; if (session.accountId !== input.accountId) { throw new SessionControlInvariantError( `Session ${input.sessionId} does not belong to account ${input.accountId}`, ); } if (session.status === "failed" || session.status === "cancelled") { if (retirement && session.status === "failed") { const [prior] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, session.id), eq(schema.sessionEvents.turnId, retirement.turnId), eq(schema.sessionEvents.type, "turn.failed"), sql`${schema.sessionEvents.payload}->>'code' = 'interrupted_turn_retired'`, sql`${schema.sessionEvents.payload}->>'retirementOperationId' = ${retirement.operationId}`, sql`${schema.sessionEvents.payload}->>'retiredVersion' = ${String(retirement.expectedVersion)}`, sql`${schema.sessionEvents.payload}->>'retiredLastSequence' = ${String(retirement.expectedLastSequence)}`, ), ) .limit(1); if (prior) return { action: "failed", turnId: retirement.turnId, events: [] } as const; } return { action: "terminal", turnId: null, events: [] } as const; } if ( session.temporalWorkflowId !== null && session.temporalWorkflowId !== input.workflowId ) { return { action: "stale", turnId: null, events: [] } as const; } const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: baseLocks.control ?? undefined }, ); if (!baseLocks.workspace || (!retirement && effectiveControl.state !== "active")) { return { action: "stale", turnId: null, events: [] } as const; } if ( retirement && (session.activeTurnId !== retirement.turnId || session.lastSequence !== retirement.expectedLastSequence) ) { return { action: "stale", turnId: null, events: [] } as const; } // The session lock serializes this check with claim. If another worker // committed ownership while the activity response was ambiguous, its // attempt is authoritative and this terminal path must no-op. const [liveAttempt] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); if (liveAttempt) { return { action: "stale", turnId: null, events: [] } as const; } let turn: typeof schema.sessionTurns.$inferSelect | null = null; if (session.activeTurnId) { const exactLocks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [session.activeTurnId], }); turn = exactLocks.turns[0] ?? null; if (!turn || turn.accountId !== session.accountId || turn.sessionId !== input.sessionId) { // The claim failed on this same locked corrupt pointer. There is no // safe turn identity to settle, but retrying can never repair it; // fail the owning session and its session-level obligations below. turn = null; } if (turn && isTerminalSessionTurnStatus(turn.status as SessionTurnStatus)) { // Repair the corrupt session pointer without writing a second // terminal event onto an already-terminal logical turn. turn = null; } else if (turn && input.trigger.kind === "approval") { if ( turn.status !== "requires_action" || !(await isNewerApprovalTrigger( tx as unknown as Database, workspaceId, input.sessionId, turn.triggerEventId, input.trigger.triggerEventId, )) ) { return { action: "stale", turnId: null, events: [] } as const; } } else if (turn) { if (turn.status === "requires_action") { return { action: "stale", turnId: null, events: [] } as const; } if (turn.status === "waiting_capacity") { // A shared-core waiter of any provider (the only kind written after its cutover). const coreWaiter = await readSubscriptionCoreWaiterInTransaction( tx as unknown as Database, { workspaceId, sessionId: input.sessionId, }, ); if (coreWaiter) { return { action: "stale", turnId: null, events: [] } as const; } } } } else { if (input.trigger.kind === "approval") { return { action: "stale", turnId: null, events: [] } as const; } const [pendingAgentSteer] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .orderBy( desc(schema.sessionSystemUpdates.createdAt), desc(schema.sessionSystemUpdates.id), ) .limit(1); const { batch: queuedBatch } = await selectQueuedSessionClaimBatch( tx as unknown as Database, session, Boolean(pendingAgentSteer), ); if (queuedBatch.length > 0) { turn = queuedBatch.at(-1) ?? null; if ( !turn || turn.accountId !== session.accountId || turn.sessionId !== input.sessionId || turn.status !== "queued" || turn.activeAttemptId !== null ) { return { action: "stale", turnId: null, events: [] } as const; } } else if (!session.compactRequested) { // Mirrors the claim: input held by a terminal compaction failure // is not runnable work unless an Agent Steer or newer input exists. const compactionHoldSequence = pendingAgentSteer ? null : await compactionFailureHoldSequenceTx( tx as unknown as Database, workspaceId, input.sessionId, ); const [pendingUpdate] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "pending"), compactionHoldSequence === null ? undefined : systemUpdatePendingAfterSequenceSql( tx as unknown as Database, workspaceId, input.sessionId, compactionHoldSequence, ), ), ) .limit(1) .for("update"); if (!pendingUpdate) { return { action: "stale", turnId: null, events: [] } as const; } } } if (retirement) { if ( !turn || turn.id !== retirement.turnId || turn.status !== "recovering" || turn.activeAttemptId !== null || turn.version !== retirement.expectedVersion ) return { action: "stale", turnId: null, events: [] } as const; const [proof] = await rawRows<{ safe: boolean }>( tx as unknown as Database, sql` select exists ( select 1 from session_turn_attempts attempt where attempt.workspace_id = ${workspaceId} and attempt.session_id = ${session.id} and attempt.turn_id = ${turn.id} and attempt.state = 'closed' and attempt.outcome = 'interrupted_recoverable' and attempt.quiesced_at is not null and not exists ( select 1 from session_turn_attempts newer where newer.workspace_id = attempt.workspace_id and newer.session_id = attempt.session_id and newer.turn_id = attempt.turn_id and newer.execution_generation > attempt.execution_generation) ) and not exists ( select 1 from session_turn_attempts attempt where attempt.workspace_id = ${workspaceId} and attempt.session_id = ${session.id} and attempt.state in ('claimed', 'running') ) and not exists ( select 1 from session_turn_attempts attempt where attempt.workspace_id = ${workspaceId} and attempt.session_id = ${session.id} and attempt.id in ${sessionPendingWriterAttemptIdsSql({ workspaceId, sessionId: session.id })} and ${sessionAttemptPendingWritersSql(sql`attempt`)} ) and not exists ( select 1 from session_turns sibling where sibling.workspace_id = ${workspaceId} and sibling.session_id = ${session.id} and sibling.id <> ${turn.id} and sibling.status in ('queued', 'running', 'requires_action', 'recovering', 'waiting_capacity') ) as safe`, ); if (!proof?.safe) return { action: "stale", turnId: null, events: [] } as const; } const now = new Date(); let sequence = session.lastSequence; let closedToolEvents: SessionEvent[] = []; let cancelledHumanInputs: Array<{ id: string; questions: HumanInputQuestion[]; turnGeneration: number; }> = []; let failedSystemUpdateIds: string[] = []; if (turn) { await cancelTurnInteractionInterventionsInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, }); const closedTools = await closePendingSessionToolCallsInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, reason: "turn_failed", sequence, now, }, ); sequence = closedTools.sequence; closedToolEvents = closedTools.events; cancelledHumanInputs = await tx .update(schema.sessionHumanInputRequests) .set({ status: "cancelled", response: { outcome: "cancelled" }, respondedBy: "system:turn_failed", respondedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.turnId, turn.id), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), ), ) .returning({ id: schema.sessionHumanInputRequests.id, questions: schema.sessionHumanInputRequests.questions, turnGeneration: schema.sessionHumanInputRequests.turnGeneration, }); // Normal failure resolves each request for the parent. Historical // retirement supersedes obsolete notices in its later passive phase; // never create a fresh resolution input that could wake old work. for (const request of retirement ? [] : cancelledHumanInputs) { await enqueueChildRequiresActionResolvedOutboxTx( tx as unknown as Database, workspaceId, session, { turnId: turn.id, turnGeneration: request.turnGeneration, requestId: request.id, approvalId: null, outcome: "cancelled", respondedByKind: "system", }, ); } } await settleSessionMaintenanceInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, }); if (!turn || retirement) { const failedUpdates = await tx .update(schema.sessionSystemUpdates) .set({ state: "failed" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .returning({ id: schema.sessionSystemUpdates.id, scheduledTaskRunId: schema.sessionSystemUpdates.scheduledTaskRunId, }); failedSystemUpdateIds = failedUpdates.map((update) => update.id).sort(); if (retirement) { // Settle only the exact occurrences whose pending inputs were // retired. Dispatched is accepted source truth, not a running // agent status; use its canonical lifecycle capability, never a // broad session-wide update of dispatch history. const runIds = [ ...new Set(failedUpdates.flatMap((update) => update.scheduledTaskRunId ?? [])), ].sort(); for (const runId of runIds) await markScheduledTaskRunAuthorityRejectedInTransaction(tx as unknown as Database, { workspaceId, sessionId: session.id, runId, error: input.error, }); } } if (retirement && turn) { await tx .update(schema.sessionGoals) .set({ continuationSuppressedTurnId: turn.id, continuationObservedRevision: sql`${schema.sessionGoals.continuationWakeRevision}`, updatedAt: now, }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, session.id), ), ); } const values = [ ...(turn ? cancelledHumanInputs.map((request) => ({ accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "user.humanInputResponse" as const, payload: { requestId: request.id, response: { outcome: "cancelled" as const }, }, turnId: turn.id, turnGeneration: request.turnGeneration, turnAttemptId: null, turnAssociation: "current" as const, occurredAt: now, })) : []), ...(turn ? [ { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "turn.failed" as const, payload: { triggerEventId: turn.triggerEventId, code: retirement ? "interrupted_turn_retired" : "pre_claim_failure", error: input.error, ...(retirement ? { retirementOperationId: retirement.operationId, retiredVersion: retirement.expectedVersion, retiredLastSequence: retirement.expectedLastSequence, parentNotificationMode: "timeline_only", failedSystemUpdateIds, } : {}), }, turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: null, turnAssociation: "current" as const, occurredAt: now, }, ] : []), { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.status.changed" as const, payload: { status: "failed", code: retirement ? "interrupted_turn_retired" : "pre_claim_failure", error: input.error, ...(retirement ? { retirementOperationId: retirement.operationId, retiredVersion: retirement.expectedVersion, retiredLastSequence: retirement.expectedLastSequence, failedSystemUpdateIds, } : {}), ...(input.admissionFailure ? { admissionFailure: input.admissionFailure } : {}), ...(!turn ? { failedSystemUpdateIds } : {}), }, turnId: turn?.id ?? null, turnGeneration: turn?.executionGeneration ?? null, turnAttemptId: null, turnAssociation: turn ? ("current" as const) : null, occurredAt: now, }, ]; const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(); const cancelledHumanInputById = new Map( cancelledHumanInputs.map((request) => [request.id, request]), ); for (const event of inserted) { if (event.type !== "user.humanInputResponse") continue; const payload = sessionEventPayloadRecord(event.payload, event.payloadCodecVersion); const requestId = typeof payload.requestId === "string" ? payload.requestId : null; const request = requestId ? cancelledHumanInputById.get(requestId) : null; if (!request || !turn) continue; await mirrorSessionRealtimeContextInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sourceKind: "human_input_response", sourceId: event.id, turnId: turn.id, channel: null, text: renderRealtimeHumanInputResponseContext({ requestId: request.id, questions: request.questions, response: { outcome: "cancelled" }, }), payload: { requestId: request.id, outcome: "cancelled", sourceEventId: event.id, }, now, }); } if (turn) { const failedEvent = inserted.find((event) => event.type === "turn.failed"); if (!failedEvent) { throw new SessionControlInvariantError( `Pre-claim failure for turn ${turn.id} has no terminal event`, ); } await projectSessionRealtimeDelegationTerminalInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, turnStatus: "failed", terminalEvent: { id: failedEvent.id, type: "turn.failed", // Operator fences and retirement reasons are human audit, not // new model-facing error text. Maintenance uses the existing // generic failure projection without rewriting prior context. payload: retirement ? { status: "failed" } : sessionEventPayloadRecord(failedEvent.payload, failedEvent.payloadCodecVersion), }, now, }); await tx .update(schema.sessionTurns) .set({ status: "failed", activeAttemptId: null, version: turn.version + 1, finishedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, turn.id), ), ); if (!retirement) await enqueueFailedChildOutboxForTurnTx( tx as unknown as Database, workspaceId, session, turn, ); } else { await enqueueFailedChildOutboxWithoutTurnTx( tx as unknown as Database, workspaceId, session, sequence, ); } await tx .update(schema.sessions) .set({ status: "failed", activeTurnId: null, compactRequested: false, compactRequestTrigger: null, ...(retirement ? { inputWaitTurnId: null, inputWaitUntil: null, inputWaitReason: null, inputWaitSetAt: null, } : {}), lastSequence: sequence, queueVersion: session.queueVersion + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { action: "failed", turnId: turn?.id ?? null, events: [...closedToolEvents, ...inserted.map(mapEvent)], } as const; }), ); } /** * Repair the exact terminal shape written by an older worker after a * session-level pre-claim database failure. This is deliberately narrower than * Resume: it accepts only a failed session with no live turn/attempt, an exact * root-session `pre_claim_failure` status event with no turn association, and * the caller-named complete set of undelivered failed child updates durably * tied to that failure epoch whose frozen parent turns still carry human * authority. The restored updates, audit event, runnable session state, and * signal-with-start wake commit atomically. */ export async function recoverSessionWorkFailedBeforeAttemptClaim( db: Database, workspaceId: string, input: RecoverSessionWorkFailedBeforeAttemptClaimInput, ): Promise { const operationId = input.operationId.trim(); if (!operationId || operationId.length > 200) { throw new Error("A bounded recovery operation id is required"); } if ( !Number.isSafeInteger(input.expectedFailureEventSequence) || input.expectedFailureEventSequence <= 0 || !Number.isSafeInteger(input.expectedLastSequence) || input.expectedLastSequence < input.expectedFailureEventSequence ) { throw new Error("Recovery event sequence fences are invalid"); } const expectedUpdateIds = [...input.failedUpdateIds].sort(); if ( expectedUpdateIds.length === 0 || new Set(expectedUpdateIds).size !== expectedUpdateIds.length ) { throw new Error("Recovery requires a non-empty unique failed-update set"); } const expectedUpdateIdsSha256 = createHash("sha256") .update(stableJson(expectedUpdateIds), "utf8") .digest("hex"); return await retrySessionActivityRls( db, workspaceId, { stage: "session_lifecycle_outbox.recover_failed_before_attempt_claim", eventTypes: ["session.status.changed", "system.update.pending"], maxAttempts: 3, }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockChildLifecycleOutboxWriteRowsTx( tx as unknown as Database, workspaceId, { sessionId: input.sessionId }, ); const session = locks.session; if (session.accountId !== input.accountId) { throw new SessionControlInvariantError( `Session ${input.sessionId} does not belong to account ${input.accountId}`, ); } if ( session.temporalWorkflowId !== null && session.temporalWorkflowId !== input.workflowId ) { return { action: "stale", event: null } as const; } const [priorRecovery] = await rawRows<{ id: string; sequence: number; payload: unknown; payload_codec_version: number | null; occurred_at: Date | string; }>( tx as unknown as Database, sql`select id, sequence, payload, payload_codec_version, occurred_at from session_events where workspace_id = ${workspaceId} and session_id = ${input.sessionId} and type = 'session.status.changed' and payload->>'code' = 'pre_claim_failure_recovered' and payload->>'recoveryOperationId' = ${operationId} order by sequence desc limit 1`, ); if (priorRecovery) { const priorRecoveryPayload = sessionEventPayloadRecord( priorRecovery.payload, priorRecovery.payload_codec_version, ); if ( priorRecoveryPayload?.recoveredFailureEventSequence !== input.expectedFailureEventSequence || priorRecoveryPayload.recoveredLastSequence !== input.expectedLastSequence || priorRecoveryPayload.restoredUpdateCount !== expectedUpdateIds.length || priorRecoveryPayload.restoredUpdateIdsSha256 !== expectedUpdateIdsSha256 ) { return { action: "stale", event: null } as const; } return { action: "already_recovered", event: { id: priorRecovery.id, workspaceId, sessionId: input.sessionId, sequence: priorRecovery.sequence, type: "session.status.changed", payload: fromPostgresLosslessJson( priorRecovery.payload, priorRecovery.payload_codec_version, ), occurredAt: priorRecovery.occurred_at instanceof Date ? priorRecovery.occurred_at.toISOString() : new Date(priorRecovery.occurred_at).toISOString(), clientEventId: null, turnId: null, turnGeneration: null, turnAttemptId: null, turnAssociation: null, duplicateOfEventId: null, duplicateReason: null, }, } as const; } if ( session.status !== "failed" || session.activeTurnId !== null || session.parentSessionId !== null || session.lastSequence !== input.expectedLastSequence || !session.temporalWorkflowId ) { return { action: "stale", event: null } as const; } const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); if (!locks.workspace || effectiveControl.state !== "active") { return { action: "stale", event: null } as const; } const [failureEvent] = await tx .select({ sequence: schema.sessionEvents.sequence, payload: schema.sessionEvents.payload, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, turnId: schema.sessionEvents.turnId, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "session.status.changed"), ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); const failurePayload = failureEvent ? sessionEventPayloadRecord(failureEvent.payload, failureEvent.payloadCodecVersion) : null; if ( failureEvent?.sequence !== input.expectedFailureEventSequence || failurePayload?.status !== "failed" || failurePayload.code !== "pre_claim_failure" || failureEvent.turnId !== null ) { return { action: "stale", event: null } as const; } const [liveAttempt] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), ), ) .limit(1); const [liveTurn] = await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), inArray(schema.sessionTurns.status, [ "queued", "running", "recovering", "requires_action", "waiting_capacity", ]), ), ) .limit(1); if (liveAttempt || liveTurn) { return { action: "stale", event: null } as const; } const failedUpdates = await tx .select({ id: schema.sessionSystemUpdates.id, kind: schema.sessionSystemUpdates.kind, sourceId: schema.sessionSystemUpdates.sourceId, dedupeKey: schema.sessionSystemUpdates.dedupeKey, lineage: schema.sessionSystemUpdates.lineage, deliveredTurnId: schema.sessionSystemUpdates.deliveredTurnId, deliveredHistoryItemId: schema.sessionSystemUpdates.deliveredHistoryItemId, deliveredAt: schema.sessionSystemUpdates.deliveredAt, }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "failed"), ), ) .orderBy(schema.sessionSystemUpdates.id) .for("update"); const actualFailedUpdateIds = failedUpdates.map((update) => update.id).sort(); if ( actualFailedUpdateIds.length !== expectedUpdateIds.length || actualFailedUpdateIds.some((updateId, index) => updateId !== expectedUpdateIds[index]) ) { return { action: "stale", event: null } as const; } const failurePayloadUpdateIdsValue = failurePayload.failedSystemUpdateIds; if (failurePayloadUpdateIdsValue !== undefined) { if ( !Array.isArray(failurePayloadUpdateIdsValue) || failurePayloadUpdateIdsValue.some((updateId) => typeof updateId !== "string") ) { return { action: "stale", event: null } as const; } const failurePayloadUpdateIds = [...failurePayloadUpdateIdsValue].sort(); if ( failurePayloadUpdateIds.length !== expectedUpdateIds.length || failurePayloadUpdateIds.some((updateId, index) => updateId !== expectedUpdateIds[index]) ) { return { action: "stale", event: null } as const; } } else { // Older workers did not persist the exact failed set on the status // event. Recover only when durable event history still proves that // every named row entered the pending queue after the previous // pre-claim failure and has no independent lifecycle settlement. const [previousFailure] = await rawRows<{ sequence: number }>( tx as unknown as Database, sql`select sequence from session_events where workspace_id = ${workspaceId} and session_id = ${input.sessionId} and type = 'session.status.changed' and payload->>'code' = 'pre_claim_failure' and sequence < ${input.expectedFailureEventSequence} order by sequence desc limit 1`, ); const expectedUpdateValues = sql.join( expectedUpdateIds.map((updateId) => sql`(${updateId}::text)`), sql`, `, ); const legacyProof = await rawRows<{ update_id: string; pending_count: number; terminal_count: number; }>( tx as unknown as Database, sql`with expected(update_id) as (values ${expectedUpdateValues}) select expected.update_id, count(*) filter ( where event.type = 'system.update.pending' and event.sequence > ${previousFailure?.sequence ?? 0} and event.sequence < ${input.expectedFailureEventSequence} and event.payload->>'updateId' = expected.update_id )::int as pending_count, count(*) filter ( where event.type in ( 'system.update.delivered', 'system.update.cancelled', 'system.update.superseded', 'system.update.settled' ) and ( event.payload->>'updateId' = expected.update_id or event.payload @> jsonb_build_object( 'updateIds', jsonb_build_array(expected.update_id) ) ) )::int as terminal_count from expected left join session_events event on event.workspace_id = ${workspaceId} and event.session_id = ${input.sessionId} and event.sequence <= ${input.expectedLastSequence} group by expected.update_id`, ); if ( legacyProof.length !== expectedUpdateIds.length || legacyProof.some((proof) => proof.pending_count !== 1 || proof.terminal_count !== 0) ) { return { action: "stale", event: null } as const; } } const causalTurnIds = new Set(); const repairedAuthorities = new Map< string, NonNullable>> >(); for (const update of failedUpdates) { let causalTurnId = systemUpdateCausalHumanTurnId(update); const lineage = update.lineage && typeof update.lineage === "object" && !Array.isArray(update.lineage) ? (update.lineage as Record) : null; if ( update.deliveredTurnId !== null || update.deliveredHistoryItemId !== null || update.deliveredAt !== null ) return { action: "stale", event: null } as const; if (isChildLifecycleSystemUpdateKind(update.kind)) { if (!causalTurnId || lineage?.parentSessionId !== input.sessionId) { return { action: "stale", event: null } as const; } } else if (update.kind === "background_command_result") { if ( !update.sourceId || !UUID_PATTERN.test(update.sourceId) || update.dedupeKey !== `background-command-result:${update.sourceId}` ) { return { action: "stale", event: null } as const; } const authority = await backgroundCommandCausalAuthorityTx(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, commandId: update.sourceId, }); if (!authority) return { action: "stale", event: null } as const; repairedAuthorities.set(update.id, authority); causalTurnId = authority.lineage.causalTurnId; } else if (update.kind === "session_wait_timeout") { if ( !update.sourceId || !UUID_PATTERN.test(update.sourceId) || update.dedupeKey !== `session-input-wait-timeout:${update.sourceId}` ) { return { action: "stale", event: null } as const; } const [timeoutProof] = await tx.execute(sql` select id from session_events where workspace_id = ${workspaceId} and session_id = ${input.sessionId} and type = 'session.wait.finished' and payload ->> 'waitTurnId' = ${update.sourceId} and payload ->> 'outcome' = 'timeout' and sequence < ${input.expectedFailureEventSequence} limit 1`); if (!timeoutProof) return { action: "stale", event: null } as const; const authority = await sameSessionCausalAuthorityTx(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: update.sourceId, }); if (!authority) return { action: "stale", event: null } as const; repairedAuthorities.set(update.id, authority); causalTurnId = authority.lineage.causalTurnId; } else return { action: "stale", event: null } as const; if (!causalTurnId) return { action: "stale", event: null } as const; causalTurnIds.add(causalTurnId); } const causalTurns = await tx .select({ id: schema.sessionTurns.id, status: schema.sessionTurns.status, initiatingHumanSubjectId: schema.sessionTurns.initiatingHumanSubjectId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), inArray(schema.sessionTurns.id, [...causalTurnIds]), ), ); if ( causalTurns.length !== causalTurnIds.size || causalTurns.some( (turn) => turn.status !== "completed" || !turn.initiatingHumanSubjectId || !causalTurnIds.has(turn.id), ) ) { return { action: "stale", event: null } as const; } // Only after every exact failed member and causal receipt passes do // we repair typed authority; message/event content is never rewritten. for (const update of failedUpdates) { const authority = repairedAuthorities.get(update.id); if (!authority) continue; await tx .update(schema.sessionSystemUpdates) .set({ personalConnectionDelegations: authority.personalConnectionDelegations, mcpAccountBindings: authority.mcpAccountBindings, xaiProviderAccountAuthoritySnapshot: authority.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: authority.claudeProviderAccountAuthoritySnapshot, lineage: { ...update.lineage, ...authority.lineage }, }) .where( and( eq(schema.sessionSystemUpdates.id, update.id), eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "failed"), ), ); } const restored = await tx .update(schema.sessionSystemUpdates) .set({ state: "pending" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "failed"), inArray(schema.sessionSystemUpdates.id, expectedUpdateIds), ), ) .returning({ id: schema.sessionSystemUpdates.id }); if (restored.length !== expectedUpdateIds.length) { throw new SessionControlInvariantError( `Failed to restore the exact pre-claim update set for session ${input.sessionId}`, ); } const now = new Date(); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.status.changed" as const, payload: { status: "queued", code: "pre_claim_failure_recovered", recoveryOperationId: operationId, recoveredFailureEventSequence: input.expectedFailureEventSequence, recoveredLastSequence: input.expectedLastSequence, restoredUpdateCount: restored.length, restoredUpdateIdsSha256: expectedUpdateIdsSha256, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) { throw new SessionControlInvariantError( `Failed to append pre-claim recovery event for session ${input.sessionId}`, ); } const [updatedSession] = await tx .update(schema.sessions) .set({ status: "queued", lastSequence: session.lastSequence + 1, queueVersion: session.queueVersion + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.status, "failed"), // The semantic event trigger has already advanced this wide // compatibility projection in the same transaction. eq(schema.sessions.lastSequence, input.expectedLastSequence + 1), ), ) .returning({ id: schema.sessions.id }); if (!updatedSession) { throw new SessionControlInvariantError( `Pre-claim recovery lost the session fence for ${input.sessionId}`, ); } const workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId, reason: "pre_claim_failure_recovered", }, ); return { action: "recovered", event: mapEvent(event), workflowWakeRevision, restoredUpdateIds: restored.map((update) => update.id).sort(), } as const; }), ); } /** * Child lifecycle transactions discover immutable parentage only after taking * the control/workspace prefix. They must then lock child and parent together, * UUID ordered, before exact turn/attempt rows or an outbox FK insert. This is * a staged use of the one canonical event-write helper, not a second lock order. */ async function lockChildLifecycleOutboxWriteRowsTx( tx: Database, workspaceId: string, input: { sessionId: string; turnId?: string; attemptId?: string }, ) { const prefix = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "share", sessionIds: [], }); const [preview] = await tx .select({ id: schema.sessions.id, parentSessionId: schema.sessions.parentSessionId, }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId)), ) .limit(1); if (!preview) throw new Error(`Session not found: ${input.sessionId}`); const sessionLocks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: [input.sessionId, ...(preview.parentSessionId ? [preview.parentSessionId] : [])], }); const session = sessionLocks.sessions.find((row) => row.id === input.sessionId); if (!session) throw new Error(`Session not found: ${input.sessionId}`); if (session.parentSessionId !== preview.parentSessionId) { throw new SessionControlInvariantError( `Session ${input.sessionId} parent changed while establishing lifecycle locks`, ); } if ( session.parentSessionId && !sessionLocks.sessions.some((row) => row.id === session.parentSessionId) ) { throw new SessionControlInvariantError( `Parent session ${session.parentSessionId} was not locked with child ${input.sessionId}`, ); } let turnId = input.turnId ?? null; if (!turnId && input.attemptId) { const [attemptPreview] = await tx .select({ turnId: schema.sessionTurnAttempts.turnId }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, workspaceId), eq(schema.sessionTurnAttempts.id, input.attemptId), ), ) .limit(1); turnId = attemptPreview?.turnId ?? null; } const exactLocks = await lockSessionEventWriteRows(tx, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: turnId ? [turnId] : [], attemptIds: turnId && input.attemptId ? [input.attemptId] : [], }); return { control: prefix.control, workspace: prefix.workspace, sessions: sessionLocks.sessions, turns: exactLocks.turns, attempts: exactLocks.attempts, session, }; } /** * Commit the workflow's terminal-for-now idle decision and its parent delivery * source in one transaction. A crash after commit leaves a pending outbox row for * the global reconciler; a normal caller immediately enriches/delivers the same * dedupe identity through notifyParentOfChildIdle. */ export async function settleSessionIdleWithParentOutbox( db: Database, workspaceId: string, sessionId: string, ): Promise< | { action: "settled"; changed: boolean; episodeKey: string; notifyParent: boolean; events: SessionEvent[]; } | { action: "stale"; episodeKey: null; events: [] } > { const persistence = { stage: "session_lifecycle_outbox.settle_idle", eventTypes: ["child_terminal_result", "session.status.changed"], maxAttempts: 3, }; return await retrySessionActivityRls(db, workspaceId, persistence, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const locks = await lockChildLifecycleOutboxWriteRowsTx( tx as unknown as Database, workspaceId, { sessionId }, ); const session = locks.session; const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, sessionId, { workspaceControl: locks.control ?? undefined }, ); if ( !locks.workspace || effectiveControl.state !== "active" || session.activeTurnId !== null ) { return { action: "stale", episodeKey: null, events: [] } as const; } // A message waiting for the personal machine's owner does not keep the // chat busy: it is not work until the owner writes or the chat moves. const queued = await runnableQueuedTurnExists(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, }); if (queued || !["queued", "running", "idle"].includes(session.status)) { return { action: "stale", episodeKey: null, events: [] } as const; } // Immediate machine input has no queued turn until claim. Its producer // takes this same session fence, so a post-peek arrival must win before // we publish the preceding episode's terminal result. Use the wake-class // contract, not every pending row: deferred notices and unwaited command // results do not reopen finished work. A late child notice likewise only // reserves new work when its producer queued the session; active goals // and held/due waits are independently protected below. // After a terminal compaction failure only input committed after that // failure is runnable (`compactionFailureHoldSequenceTx`); the held // backlog does not reopen the episode on its own. const compactionHoldSequence = await compactionFailureHoldSequenceTx( tx as unknown as Database, workspaceId, sessionId, ); const pendingInputs = await tx .selectDistinct({ kind: schema.sessionSystemUpdates.kind, runnable: compactionHoldSequence === null ? sql`true` : sql`${systemUpdatePendingAfterSequenceSql( tx as unknown as Database, workspaceId, sessionId, compactionHoldSequence, )}`, }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ), ); const pendingSteer = pendingInputs.some(({ kind }) => kind === "agent_steer_instruction"); const pendingImmediate = pendingInputs.some( ({ kind, runnable }) => runnable && SESSION_SYSTEM_UPDATE_WAKE_CLASS[kind as SessionSystemUpdateKind] === "immediate" && kind !== "background_command_result" && (!isChildLifecycleSystemUpdateKind(kind as SessionSystemUpdateKind) || session.status === "queued"), ); if (pendingSteer || pendingImmediate) { return { action: "stale", episodeKey: null, events: [] } as const; } const [{ episodeSequence } = { episodeSequence: 0 }] = await tx .select({ episodeSequence: sql`coalesce(max(${schema.sessionEvents.sequence}), 0)::int`, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), ne(schema.sessionEvents.type, "session.status.changed"), ), ); const now = new Date(); let sequence = session.lastSequence; const events: SessionEvent[] = []; if (session.status === "queued" || session.status === "running") { const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "session.status.changed", payload: { status: "idle" }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (event) events.push(mapEvent(event)); await tx .update(schema.sessions) .set({ status: "idle", activeTurnId: null, lastSequence: sequence, updatedAt: now, }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); } // Status-only idle churn is not a new work episode. Key the parent // notification to the newest non-status event, not to the idle status // event this settlement just appended (or a prior identical idle event). const episodeKey = String(Number(episodeSequence)); // Workflow closure is not work completion. Input waits (including a // due timeout not yet materialized) and active goals retain obligations // even while their workflow run truthfully parks the session as idle. const waitState = await sessionInputWaitStateTx(tx, workspaceId, sessionId, session); const [goal] = await tx .select({ status: schema.sessionGoals.status }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, sessionId), ), ) .limit(1); const ongoingWork = waitState.disposition === "held" || waitState.disposition === "timeout" || goal?.status === "active"; if (!session.parentSessionId || ongoingWork) { return { action: "settled", changed: events.length > 0, episodeKey, notifyParent: false, events, } as const; } const dedupeKey = `child-completion:${session.id}:${episodeKey}`; // Freeze the child's answer with the boundary that reports it, so the // parent's wake is the result itself and a reaper-delivered row carries // the same content as an immediately delivered one. const finalAnswer = await childFinalAnswerTx( tx as unknown as Database, workspaceId, session.id, ); await enqueueChildLifecycleNoticeOutboxTx(tx as unknown as Database, workspaceId, session, { dedupeKey, kind: "child_terminal_result", classification: "success", summary: "Child session reached a terminal idle boundary.", payload: { type: "child_terminal_result", childSessionId: session.id, status: "idle", ...(finalAnswer ? { finalAnswer } : {}), }, }); return { action: "settled", changed: events.length > 0, episodeKey, notifyParent: true, events, } as const; }); }); } /** How many of the child's newest turn outcomes the final answer may walk * back through past goal-continuation turns before giving up. */ const CHILD_FINAL_ANSWER_OUTCOME_WINDOW = 16; /** * The child's current final answer for its idle terminal result. Null when its * newest turn ended without an answer (including one that stopped at a segment * limit), when it has no answer text, or when a stored answer row is itself * only a retained preview: the parent then reads the child's events instead of * receiving an older answer or a partial copy presented as the result. * * A turn claimed only to continue the child's goal (typically to confirm and * complete it after the answer) does not replace the answer. The walk goes * back past such turns to the newest outcome that had any other input and * reports that answer, followed by the continuation output. It also stops, as * at such a turn, at an earlier outcome that is not a readable answer (a * failure, a cancellation, a segment limit) and at the child's newest goal * activation, so it never reaches output an earlier result reported. When the * window holds only continuations, the result is the newest answer alone, as * if no walk were made. A copy that cannot fit whole is the newest part, * marked truncated, pointing at every part (see * `childTerminalResultFinalAnswerWithGoalContinuations`). */ async function childFinalAnswerTx( tx: Database, workspaceId: string, childSessionId: string, ): Promise { const outcomes = await rawRows<{ sequence: number; type: string; payload: unknown; payloadCodecVersion: number | null; goalContinuationOnly: boolean; goalActivatedAt: number | string; }>( tx, childRecentTurnOutcomesSql( sql`${workspaceId}::uuid`, sql`${childSessionId}::uuid`, CHILD_FINAL_ANSWER_OUTCOME_WINDOW, ), ); const readable = (outcome: (typeof outcomes)[number]) => outcome.type === "turn.completed" ? completedTurnAnswerOutput(outcome) : null; const [newest] = outcomes; const newestOutput = newest ? readable(newest) : null; if (!newest || newestOutput === null) return null; const goalActivatedAt = Number(newest.goalActivatedAt); // Newest first; reversed into oldest-first parts below. const parts: { sequence: number; output: string }[] = []; let started = false; for (const [index, outcome] of outcomes.entries()) { const output = readable(outcome); // The run's first turn is behind this one: a non-answer outcome, or the // goal (re)activation that began the goal-continuation run. if (output === null || (index > 0 && Number(outcome.sequence) < goalActivatedAt)) { started = true; break; } if (output.length > 0) parts.push({ sequence: Number(outcome.sequence), output }); if (!outcome.goalContinuationOnly) { started = true; break; } } // Fewer outcomes than the window: the walk reached the child's first turn. if (outcomes.length < CHILD_FINAL_ANSWER_OUTCOME_WINDOW) started = true; if (!started) { // Only goal continuations in the window: the run's first answer is not // proven here, so report the newest answer alone. return newestOutput.length > 0 ? childTerminalResultFinalAnswer({ childSessionId, sequence: Number(newest.sequence), output: newestOutput, }) : null; } const [answer, ...goalContinuations] = parts.reverse(); if (!answer) return null; return childTerminalResultFinalAnswerWithGoalContinuations({ childSessionId, sequence: answer.sequence, output: answer.output, goalContinuations, }); } /** The whole answer a `turn.completed` carries ("" when it has none), or null * when the stored row cannot stand in for that turn's result: a retained * preview, or a turn that stopped at a segment limit. */ function completedTurnAnswerOutput(outcome: { payload: unknown; payloadCodecVersion: number | null; }): string | null { const payload = logicalChildReadEvent(outcome).payload; if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return null; const record = payload as Record; const truncation = record.truncation as { truncated?: unknown } | null | undefined; if (truncation?.truncated === true || record.sourceOmitted === true) return null; if (Object.hasOwn(record, "segmentLimit")) return null; if (typeof record.output === "string") return record.output; // No output at all is "no answer"; any other shape is not a readable copy. return (record.output ?? null) === null && (record.result ?? null) === null ? "" : null; } export async function setTemporalWorkflowId( db: Database, workspaceId: string, sessionId: string, workflowId: string, ): Promise { await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { await scopedDb .update(schema.sessions) .set({ temporalWorkflowId: workflowId, updatedAt: new Date(), }) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))); }); } const TURN_DISPATCH_ATTEMPT_METADATA_KEY = "dispatchAttempt"; const TURN_DISPATCH_GENERATION_METADATA_KEY = "dispatchGeneration"; type TurnDispatchAttempt = { id: string; generation: number; triggerEventId: string; pendingUpdateBoundarySequence?: number; }; type TurnDispatchMetadata = | { kind: "absent"; generation: 0; attempt: null } | { kind: "valid"; generation: number; attempt: TurnDispatchAttempt | null } | { kind: "malformed"; reason: string }; function readTurnDispatchMetadata(metadata: unknown): TurnDispatchMetadata { if (metadata === null || metadata === undefined) { return { kind: "absent", generation: 0, attempt: null }; } if (typeof metadata !== "object" || Array.isArray(metadata)) { return { kind: "malformed", reason: "turn metadata is not an object" }; } const record = metadata as Record; const hasAttempt = Object.prototype.hasOwnProperty.call( record, TURN_DISPATCH_ATTEMPT_METADATA_KEY, ); const hasGeneration = Object.prototype.hasOwnProperty.call( record, TURN_DISPATCH_GENERATION_METADATA_KEY, ); if (!hasAttempt && !hasGeneration) { return { kind: "absent", generation: 0, attempt: null }; } const rawGeneration = record[TURN_DISPATCH_GENERATION_METADATA_KEY]; if ( hasGeneration && (typeof rawGeneration !== "number" || !Number.isSafeInteger(rawGeneration) || rawGeneration < 0) ) { return { kind: "malformed", reason: "dispatchGeneration is not a safe non-negative integer", }; } const generation = hasGeneration ? (rawGeneration as number) : null; if (!hasAttempt) { return { kind: "valid", generation: generation ?? 0, attempt: null, }; } const value = record[TURN_DISPATCH_ATTEMPT_METADATA_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) { return { kind: "malformed", reason: "dispatchAttempt is not an object" }; } const attempt = value as Record; const pendingUpdateBoundarySequence = attempt.pendingUpdateBoundarySequence; if ( typeof attempt.id !== "string" || attempt.id.length === 0 || typeof attempt.generation !== "number" || !Number.isSafeInteger(attempt.generation) || attempt.generation < 1 || typeof attempt.triggerEventId !== "string" || attempt.triggerEventId.length === 0 || (pendingUpdateBoundarySequence !== undefined && (typeof pendingUpdateBoundarySequence !== "number" || !Number.isSafeInteger(pendingUpdateBoundarySequence) || pendingUpdateBoundarySequence < 0)) ) { return { kind: "malformed", reason: "dispatchAttempt has an invalid shape", }; } if (generation === null || generation !== attempt.generation) { return { kind: "malformed", reason: "dispatchGeneration does not match dispatchAttempt", }; } return { kind: "valid", generation: attempt.generation, attempt: { id: attempt.id, generation: attempt.generation, triggerEventId: attempt.triggerEventId, ...(pendingUpdateBoundarySequence === undefined ? {} : { pendingUpdateBoundarySequence }), }, }; } function metadataWithTurnDispatchAttempt( metadata: Record | null | undefined, attempt: TurnDispatchAttempt, ): Record { return { ...(metadata ?? {}), [TURN_DISPATCH_GENERATION_METADATA_KEY]: attempt.generation, [TURN_DISPATCH_ATTEMPT_METADATA_KEY]: attempt, }; } function metadataWithoutTurnDispatchAttempt( metadata: Record | null | undefined, ): Record { const next = { ...(metadata ?? {}) }; delete next[TURN_DISPATCH_ATTEMPT_METADATA_KEY]; return next; } async function wakeSandboxLifecycleWaitersTx( tx: Database, input: { workspaceId: string; sandboxGroupId: string; expectedEpoch: number }, ): Promise { const lifecycleWaitJson = JSON.stringify({ [SANDBOX_LIFECYCLE_WAIT_METADATA_KEY]: { version: 1, sandboxGroupId: input.sandboxGroupId, leaseEpoch: input.expectedEpoch, reason: "rotation_in_progress", } satisfies SandboxLifecycleWait, }); const waiters = await tx .select({ accountId: schema.sessions.accountId, sessionId: schema.sessions.id, temporalWorkflowId: schema.sessions.temporalWorkflowId, }) .from(schema.sessions) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessions.workspaceId), eq(schema.sessionTurns.sessionId, schema.sessions.id), eq(schema.sessionTurns.id, schema.sessions.activeTurnId), ), ) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.sandboxGroupId, input.sandboxGroupId), eq(schema.sessions.status, "recovering"), eq(schema.sessionTurns.status, "recovering"), sql`${schema.sessionTurns.metadata} @> ${lifecycleWaitJson}::jsonb`, ), ) .orderBy(asc(schema.sessions.id)); for (const waiter of waiters) { await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: waiter.accountId, workspaceId: input.workspaceId, sessionId: waiter.sessionId, temporalWorkflowId: waiter.temporalWorkflowId ?? `session-${waiter.sessionId}`, reason: "sandbox_lifecycle_advanced", }); } } const SANDBOX_LIFECYCLE_WAIT_METADATA_KEY = "sandboxLifecycleWait"; const SANDBOX_SETUP_OUTCOME_UNKNOWN_METADATA_KEY = "sandboxSetupOutcomeUnknown"; const SANDBOX_SETUP_RECOVERY_EXHAUSTED_METADATA_KEY = "sandboxSetupRecoveryExhausted"; /** Version-one pre-dispatch setup recovery has exactly five automatic retries. */ export const SANDBOX_SETUP_RECOVERY_LIMIT = 5; /** Proven not started, but its finite automatic recovery budget is exhausted. * Wakes, time, and lease changes cannot replenish this accepted turn's budget. */ export type SandboxSetupRecoveryExhausted = { version: 1; turnId: string; attemptId: string; reason: "sandbox_command_start_recovery_exhausted"; setupOutcome: "not_started"; providerRecoveryCount: typeof SANDBOX_SETUP_RECOVERY_LIMIT; }; function sandboxSetupRecoveryExhaustedFromTurnMetadata( metadata: Record | null | undefined, ): SandboxSetupRecoveryExhausted | null { const value = metadata?.[SANDBOX_SETUP_RECOVERY_EXHAUSTED_METADATA_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const marker = value as Partial; if ( marker.version !== 1 || typeof marker.turnId !== "string" || marker.turnId.length === 0 || typeof marker.attemptId !== "string" || marker.attemptId.length === 0 || marker.reason !== "sandbox_command_start_recovery_exhausted" || marker.setupOutcome !== "not_started" || marker.providerRecoveryCount !== SANDBOX_SETUP_RECOVERY_LIMIT ) { return null; } return marker as SandboxSetupRecoveryExhausted; } /** Setup may be retried after every invocation of its exact unwound attempt * has positively settled. Time or missing provider state is never exit proof. */ export type SandboxSetupOutcomeUnknown = { version: 1; turnId: string; attemptId: string; reason: "sandbox_command_start_outcome_unknown"; }; function sandboxSetupOutcomeUnknownFromTurnMetadata( metadata: Record | null | undefined, ): SandboxSetupOutcomeUnknown | null { const value = metadata?.[SANDBOX_SETUP_OUTCOME_UNKNOWN_METADATA_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const marker = value as Partial; if ( marker.version !== 1 || typeof marker.turnId !== "string" || marker.turnId.length === 0 || typeof marker.attemptId !== "string" || marker.attemptId.length === 0 || marker.reason !== "sandbox_command_start_outcome_unknown" ) { return null; } return marker as SandboxSetupOutcomeUnknown; } /** Completion may arrive after the attempt quiesced. Both a process exit and * its last child admission must wake the exact setup waiter. */ async function hasWaitingSandboxSetupForWriterTx( tx: Database, workspaceId: string, sessionId: string, actorKind: string, actorId: string, ): Promise { const [row] = await tx.execute<{ waiting: boolean }>(sql` select exists ( select 1 from sessions s join session_turns t on t.workspace_id=s.workspace_id and t.session_id=s.id and t.id=s.active_turn_id left join sandbox_retained_processes p on p.workspace_id=s.workspace_id and p.session_id=s.id and p.id=${actorId}::uuid where s.workspace_id=${workspaceId} and s.id=${sessionId} and s.status='recovering' and t.status='recovering' and t.metadata->'sandboxSetupOutcomeUnknown' @> jsonb_build_object( 'version',1,'turnId',t.id::text,'reason','sandbox_command_start_outcome_unknown', 'attemptId',${actorKind === "process" ? sql`p.owner_attempt_id::text` : sql`${actorId}::text`}) ) as waiting `); return row?.waiting === true; } /** The exact provider box every setup request of an uncertain attempt ran on, * observed terminated by the provider after its lease moved to a later epoch. */ export type TerminatedSandboxSetupBox = { leaseId: string; leaseEpoch: number; providerBackend: "modal"; providerInstanceId: string; }; /** Retire an uncertainty marker after physical completion, not after a timeout. * Setup reruns its idempotent preparation; this does not declare setup successful * or replay an uncertain provider command. Peek itself remains read-only. * * Physical completion is either the exit of the setup's retained process, or a * caller's terminated observation of the exact box every setup request of the * attempt ran on (`terminatedBox`): nothing can still run on a terminated box, * including a start whose process was never recorded. Missing provider state, * NotFound, lease succession or time alone is never proof. */ export async function reconcileCompletedSandboxSetup( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; terminatedBox?: TerminatedSandboxSetupBox; }, ): Promise<{ reconciled: boolean; events: SessionEvent[] }> { const box = input.terminatedBox ?? null; if ( box && (box.providerBackend !== "modal" || !Number.isSafeInteger(box.leaseEpoch) || box.leaseEpoch < 0 || box.providerInstanceId.length === 0) ) { throw new Error("Terminated sandbox setup box is invalid"); } return withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); const session = locks.sessions[0], turn = locks.turns[0], attempt = locks.attempts[0]; const marker = sandboxSetupOutcomeUnknownFromTurnMetadata(turn?.metadata); if ( !session || !turn || !attempt || session.accountId !== input.accountId || session.activeTurnId !== turn.id || turn.sessionId !== session.id || turn.status !== "recovering" || turn.activeAttemptId !== null || marker?.turnId !== turn.id || marker.attemptId !== attempt.id || attempt.sessionId !== session.id || attempt.turnId !== turn.id || attempt.executionGeneration !== turn.executionGeneration || attempt.state !== "closed" || !attempt.quiescedAt || sandboxSetupRecoveryExhaustedFromTurnMetadata(turn.metadata) ) return { reconciled: false, events: [] }; const control = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); if (control.state !== "active") return { reconciled: false, events: [] }; // Closed attempt + canonical session/attempt locks prevent new admissions. // Terminal rows cannot revert to active, so no provider or lease I/O is needed. // A terminated box is the caller's provider observation; the lease row // only confirms the box is no longer current (epochs never go back). const setupAdmission = sql` a.account_id = ${input.accountId} and a.workspace_id = ${input.workspaceId} and a.session_id = ${input.sessionId} and a.attempt_id = ${attempt.id} and a.turn_id = ${turn.id} and a.execution_generation = ${turn.executionGeneration} and a.actor_kind = 'turn' and a.actor_id = ${attempt.id} and a.operation in ('lazyOwnedSandboxSetup', 'eagerOwnedSandboxSetup') and a.route_kind = 'home' and a.route_target_id is null`; const onTerminatedBox = (alias: "a" | "p") => box ? sql`${sql.raw(alias)}.lease_id = ${box.leaseId} and ${sql.raw(alias)}.lease_epoch = ${box.leaseEpoch} and ${sql.raw(alias)}.provider_backend = ${box.providerBackend} and ${sql.raw(alias)}.provider_instance_id = ${box.providerInstanceId}` : sql`false`; const setupPhysicallyEnded = box ? sql`( exists ( select 1 from sandbox_workspace_mutation_admissions a where ${setupAdmission} and ${onTerminatedBox("a")} ) and not exists ( select 1 from sandbox_workspace_mutation_admissions a where ${setupAdmission} and not (${onTerminatedBox("a")}) ) and exists ( select 1 from sandbox_leases l where l.id = ${box.leaseId} and l.workspace_id = ${input.workspaceId} and l.backend = ${box.providerBackend} and l.lease_epoch > ${box.leaseEpoch} and l.instance_id is distinct from ${box.providerInstanceId} ) )` : sql`false`; const [proof] = await tx.execute<{ completed: boolean }>(sql` select (exists ( select 1 from sandbox_workspace_mutation_admissions a where ${setupAdmission} and exists ( select 1 from sandbox_retained_processes p where p.parent_admission_id = a.id and p.owner_attempt_id = ${attempt.id} and p.session_id = a.session_id and p.lease_id = a.lease_id and p.lease_epoch = a.lease_epoch and p.provider_instance_id = a.provider_instance_id and p.state = 'exited' and p.exit_code is not null ) ) or ${setupPhysicallyEnded}) and not exists ( select 1 from sandbox_workspace_mutation_admissions a where a.workspace_id = ${input.workspaceId} and a.session_id = ${input.sessionId} and (a.attempt_id = ${attempt.id} or (a.actor_kind = 'process' and exists ( select 1 from sandbox_retained_processes p where p.id = a.actor_id and p.owner_attempt_id = ${attempt.id} ))) and (a.settled_at is null or a.provider_outcome is null or a.provider_outcome not in ('resolved', 'rejected')) ) and not exists ( select 1 from sandbox_retained_processes p where p.workspace_id = ${input.workspaceId} and p.session_id = ${input.sessionId} and p.owner_attempt_id = ${attempt.id} and (p.state <> 'exited' or p.exit_code is null) -- A process recorded as lost on the terminated box cannot run. and not (p.state = 'lost' and ${onTerminatedBox("p")}) ) as completed `); if (!proof?.completed) return { reconciled: false, events: [] }; const metadata = { ...(turn.metadata ?? {}) }; delete metadata[SANDBOX_SETUP_OUTCOME_UNKNOWN_METADATA_KEY]; const now = new Date(); await tx .update(schema.sessionTurns) .set({ metadata, version: turn.version + 1, updatedAt: now }) .where(eq(schema.sessionTurns.id, turn.id)); const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "turn.recovery.requested" as const, payload: { reason: "sandbox_setup_physically_settled", retryable: true, }, turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: attempt.id, turnAssociation: "current" as const, occurredAt: now, }, ], "payload", "payloadCodecVersion", ), ) .returning(); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, session.id)); await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, reason: "sandbox_setup_physically_settled", }); return { reconciled: true, events: inserted.map(mapEvent) }; }), ); } export type SandboxLifecycleWait = { version: 1; sandboxGroupId: string; leaseEpoch: number; reason: "rotation_in_progress"; }; function sandboxLifecycleWaitFromTurnMetadata( metadata: Record | null | undefined, ): SandboxLifecycleWait | null { const value = metadata?.[SANDBOX_LIFECYCLE_WAIT_METADATA_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const wait = value as Partial; if ( wait.version !== 1 || typeof wait.sandboxGroupId !== "string" || wait.sandboxGroupId.length === 0 || !Number.isSafeInteger(wait.leaseEpoch) || (wait.leaseEpoch ?? -1) < 0 || wait.reason !== "rotation_in_progress" ) { return null; } return wait as SandboxLifecycleWait; } function sandboxLifecycleWaitIsPending( wait: SandboxLifecycleWait, lease: | { leaseEpoch: number; liveness: SandboxLeaseLiveness; rotationRequestedAt: Date | null; } | undefined, ): boolean { return Boolean( lease && Number(lease.leaseEpoch) === wait.leaseEpoch && lease.liveness !== "cold" && lease.rotationRequestedAt !== null, ); } function metadataWithoutSandboxLifecycleWait( metadata: Record | null | undefined, ): Record { const next = { ...(metadata ?? {}) }; delete next[SANDBOX_LIFECYCLE_WAIT_METADATA_KEY]; return next; } function recoveryTurnMetadata( metadata: Record | null | undefined, lifecycleWait: SandboxLifecycleWait | undefined, ): Record { const next = metadataWithoutSandboxLifecycleWait(metadataWithoutTurnDispatchAttempt(metadata)); delete next[RECOVERY_RETRY_METADATA_KEY]; if (lifecycleWait) { next[SANDBOX_LIFECYCLE_WAIT_METADATA_KEY] = lifecycleWait; } return next; } /** * The earliest moment a recovering turn may dispatch its replacement attempt. * Durable on the turn so that every wake (the session's own receipts and * outbox retries included) re-reads the same deadline instead of cutting the * backoff short. Only new user input after `afterSequence` ends it early. */ const RECOVERY_RETRY_METADATA_KEY = "recoveryRetry"; export type SessionTurnRecoveryRetry = { version: 1; notBefore: string; afterSequence: number; }; export function sessionTurnRecoveryRetryFromMetadata( metadata: Record | null | undefined, ): SessionTurnRecoveryRetry | null { const value = metadata?.[RECOVERY_RETRY_METADATA_KEY]; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const retry = value as Record; if ( retry.version !== 1 || typeof retry.notBefore !== "string" || !Number.isFinite(Date.parse(retry.notBefore)) || !Number.isSafeInteger(retry.afterSequence) ) { return null; } return { version: 1, notBefore: retry.notBefore, afterSequence: retry.afterSequence as number, }; } /** Longest backoff a recovery may request; anything longer is a caller bug. */ export const SESSION_TURN_RECOVERY_RETRY_MAX_MS = 15 * 60_000; function providerRecoveryCountFromTurnMetadata( metadata: Record | null | undefined, ): number { const value = metadata?.providerRecoveryCount; return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0; } function metadataWithoutProviderRecoveryCount( metadata: Record | null | undefined, ): Record { const next = { ...(metadata ?? {}) }; delete next.providerRecoveryCount; delete next.providerRecoveryStartedAt; delete next.providerRecoveryReason; delete next[PROVIDER_RECOVERY_SUSPENDED_AT]; return next; } function hasCompletedCurrentModelRequest( events: ReadonlyArray< Pick< typeof schema.sessionEvents.$inferSelect, "type" | "payload" | "payloadCodecVersion" | "turnAssociation" > >, requireMeaningfulOutput = false, ): boolean { return events.some( (event) => event.turnAssociation === "current" && event.type === "agent.model.request" && sessionEventPayloadRecord(event.payload, event.payloadCodecVersion).phase === "completed" && (!requireMeaningfulOutput || sessionEventPayloadRecord(event.payload, event.payloadCodecVersion).meaningfulOutput === true), ); } type WorkerDeathRedispatchMetadata = | { kind: "valid"; count: number } | { kind: "malformed"; reason: string }; function readWorkerDeathRedispatchMetadata(metadata: unknown): WorkerDeathRedispatchMetadata { if (metadata === null || metadata === undefined) { return { kind: "valid", count: 0 }; } if (typeof metadata !== "object" || Array.isArray(metadata)) { return { kind: "malformed", reason: "turn metadata is not an object" }; } const raw = (metadata as Record).workerDeathRedispatches; if (raw === undefined) { return { kind: "valid", count: 0 }; } if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) { return { kind: "malformed", reason: "workerDeathRedispatches is not a safe non-negative integer", }; } return { kind: "valid", count: raw }; } async function isNewerApprovalTrigger( tx: Database, workspaceId: string, sessionId: string, currentTriggerEventId: string, candidateTriggerEventId: string, ): Promise { const rows = await tx .select({ id: schema.sessionEvents.id, type: schema.sessionEvents.type, sequence: schema.sessionEvents.sequence, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.sessionId, sessionId), inArray(schema.sessionEvents.id, [currentTriggerEventId, candidateTriggerEventId]), ), ); const current = rows.find((row) => row.id === currentTriggerEventId); const candidate = rows.find((row) => row.id === candidateTriggerEventId); return Boolean( current && candidate && ["user.approvalDecision", "user.humanInputResponse"].includes(candidate.type) && candidate.sequence > current.sequence, ); } type SessionTurnRecordingSettlementBase = { recordingId: string; producerId?: string | null; producerSeq?: number | null; occurredAt?: Date; }; export type SessionTurnRecordingSettlement = | (SessionTurnRecordingSettlementBase & { action: "available"; storageKey: string; sizeBytes: number; durationSeconds: number; }) | (SessionTurnRecordingSettlementBase & { action: "failed"; reason: string; detail: string | null; }) | (SessionTurnRecordingSettlementBase & { action: "discard" }); export type ApplySessionTurnSettlementInput = { sessionId: string; turnId: string; triggerEventId: string; attemptId: string; fromStatuses?: SessionTurnStatus[]; turnStatus: SessionTurnStatus; sessionStatus: SessionStatus; activeTurnId: string | null; /** * Finish this terminal turn without arming the active goal's autonomous * continuation. The goal remains active so explicit later work can proceed, * but this exact settlement cannot synthesize another turn from unchanged * input after a bounded terminal condition. */ suppressGoalContinuation?: boolean; /** * Pause an active goal atomically with a recoverable non-failure stop: an * allowance stop (default reason `allowance`) or a reached per-task usage * limit (`session_usage_limit`). */ allowanceGoalPause?: { rationale: string; reason?: "allowance" | "session_usage_limit" }; events: AppendEventInput[]; /** * Apply this settlement only while a Steer is still waiting for the turn * (see `hasPendingSteerForTurn`), checked under the session lock. Otherwise * nothing is written and the result is `pending_steer_withdrawn`, so the * caller keeps running the turn. */ requirePendingSteer?: boolean; /** * A mid-turn requires_action freeze. Human-input rows and interaction * interventions are public protocol; ordinary approvals remain in * pendingApprovals. Pause attaches the bounded open suffix on * `session_pending_tool_calls` and stores the open-suffix sentinel here. * Resume uses the suffix plus paired history and must not call * `RunState.fromString`. */ runState?: { serializedRunState: string; pendingApprovals: unknown[]; humanInputRequests?: Array<{ id: string; toolCallId: string; questions: HumanInputQuestion[]; allowSkip: boolean; expiresAt?: Date | null; }>; interactionInterventionRequests?: Array<{ id: string; operationId: string; toolCallId: string; input: RequestHumanInteractionToolInput; /** The target as read at this pause, or why it could not be read. */ currentTarget?: InteractionRequestCurrentTarget | string; }>; }; recording?: SessionTurnRecordingSettlement; /** * Atomically consume an operator /compact request and record why it could * not install a replacement. This lives on the terminal turn settlement so * a worker crash can never clear the request without also publishing the * attempt-owned failure truth. */ compactionRequestFailure?: { reason: "summarization_failed"; producerId?: string | null; producerSeq?: number | null; occurredAt?: Date; }; /** * A standalone maintenance compaction deferred for subscription capacity. * An automatic `proactive` request is dropped here, in the same * attempt-fenced transaction, and settled with a `capacity_unavailable` * skipped landmark: kept, it would win every later claim ahead of pending * machine input and goal continuations without any capacity waiter to wake * it. The person's next turn compacts at its ordinary threshold check * instead. An operator request is kept, as before. Decided from the label * read under the session lock; a `turn.cancelled` event's * `requestPreserved` flag is rewritten to match. */ dropProactiveCompactionRequest?: { producerId?: string | null; producerSeq?: number | null; }; /** In-flight calls with call-scoped proof that their command never started. */ notStartedToolCallIds?: readonly string[]; }; export type ApplySessionTurnSettlementResult = | { action: "settled"; events: SessionEvent[]; canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[]; recordingMutationApplied: boolean; } | { action: "stale"; events: []; turnStatus: SessionTurnStatus | null; activeTurnId: string | null; } | { /** `requirePendingSteer` found no waiting Steer; nothing was written. */ action: "pending_steer_withdrawn"; events: []; }; export type ApplySessionTurnSettlementHooks = { /** Test-only failure injection after terminal projection but before commit. */ afterRealtimeDelegationProjection?: | ((projection: { entryId: string; turnId: string }) => void | Promise) | undefined; }; function attemptOutcomeForTurnStatus(status: SessionTurnStatus): SessionTurnAttemptOutcome | null { switch (status) { case "completed": case "failed": case "cancelled": case "superseded": case "requires_action": return status; default: return null; } } type TerminalSessionTurnStatus = "completed" | "failed" | "cancelled" | "superseded"; type TerminalSessionTurnEventType = | "turn.completed" | "turn.failed" | "turn.cancelled" | "turn.superseded"; function terminalSessionTurnEventType( status: TerminalSessionTurnStatus, ): TerminalSessionTurnEventType { switch (status) { case "completed": return "turn.completed"; case "failed": return "turn.failed"; case "cancelled": return "turn.cancelled"; case "superseded": return "turn.superseded"; } } function isTerminalSessionTurnStatus( status: SessionTurnStatus, ): status is TerminalSessionTurnStatus { return ["completed", "failed", "cancelled", "superseded"].includes(status); } function sessionEventPayloadRecord( payload: unknown, payloadCodecVersion: number | null, ): Record { const logicalPayload = fromPostgresLosslessJson(payload, payloadCodecVersion); return logicalPayload && typeof logicalPayload === "object" && !Array.isArray(logicalPayload) ? (logicalPayload as Record) : {}; } export type CanonicalTurnStartupMilestoneReceipt = { milestone: "queue" | "provider_dispatch" | "first_byte"; outcome: "completed" | "failed"; eventId: string; durationMs: number; }; const TURN_STARTUP_CHECKPOINTS = [ { milestone: "queue", outcome: "completed" }, { milestone: "provider_dispatch", outcome: "completed" }, { milestone: "first_byte", outcome: "completed" }, { milestone: "first_byte", outcome: "failed" }, ] as const satisfies ReadonlyArray< Pick >; function startupCheckpointKey( checkpoint: Pick, ): string { return `${checkpoint.milestone}:${checkpoint.outcome}`; } function startupMilestoneForEvent( event: Pick< typeof schema.sessionEvents.$inferSelect, "type" | "payload" | "payloadCodecVersion" | "turnAssociation" >, ): Pick | null { if (event.turnAssociation !== "current") return null; if (event.type === "turn.started") return { milestone: "queue", outcome: "completed" }; if (event.type === "turn.failed") return { milestone: "first_byte", outcome: "failed" }; if (event.type !== "agent.model.request") return null; const phase = sessionEventPayloadRecord(event.payload, event.payloadCodecVersion).phase; if (phase === "started") return { milestone: "provider_dispatch", outcome: "completed" }; if (phase === "first_byte" || phase === "first_event") { return { milestone: "first_byte", outcome: "completed" }; } return null; } type TurnStartupCheckpoint = Pick; type TurnStartupLedgerScope = { accountId: string; workspaceId: string; sessionId: string; turnId: string; }; /** * Claim one startup checkpoint for the turn in `session_turn_startup_milestones`. * Returns true only when this transaction inserted the row, i.e. it is the * canonical inserter of that checkpoint. A durable row from an earlier * transaction (or a pre-ledger sentinel) conflicts, so recovery and replay are * no-ops. The exclusive terminal-failed first_byte outcome is additionally * fenced on ledger state: a provider_dispatch row must exist for the turn and * no completed first_byte row may exist, mirroring the former exists/not-exists * scan over the turn's events. Every probe is a primary-key lookup; the turn's * session_events rows are never re-read. */ async function claimTurnStartupMilestone( tx: Database, input: TurnStartupLedgerScope & { checkpoint: TurnStartupCheckpoint; event: { id: string; occurredAt: Date }; }, ): Promise { const { milestone, outcome } = input.checkpoint; const ledger = schema.sessionTurnStartupMilestones; const terminalFailedFence = outcome === "failed" ? sql` exists ( select 1 from ${ledger} where ${ledger.workspaceId} = ${input.workspaceId} and ${ledger.turnId} = ${input.turnId} and ${ledger.milestone} = 'provider_dispatch' and ${ledger.outcome} = 'completed' ) and not exists ( select 1 from ${ledger} where ${ledger.workspaceId} = ${input.workspaceId} and ${ledger.turnId} = ${input.turnId} and ${ledger.milestone} = 'first_byte' and ${ledger.outcome} = 'completed' )` : sql`true`; const claimed = await tx.execute<{ event_id: string }>(sql` insert into ${ledger} ( ${sql.identifier("account_id")}, ${sql.identifier("workspace_id")}, ${sql.identifier("session_id")}, ${sql.identifier("turn_id")}, ${sql.identifier("milestone")}, ${sql.identifier("outcome")}, ${sql.identifier("canonical_source")}, ${sql.identifier("event_id")}, ${sql.identifier("occurred_at")} ) select ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${milestone}::text, ${outcome}::text, 'inserted_event', ${input.event.id}::uuid, ${input.event.occurredAt.toISOString()}::timestamptz where ${terminalFailedFence} on conflict do nothing returning ${sql.identifier("event_id")} as event_id `); return claimed.length > 0; } /** * A turn whose canonical `turn.started` was durable before any ledger-aware * writer touched it (in flight across the ledger rollout, or claimed by a * pre-ledger worker during the rolling window) already observed, or may have * observed, its startup checkpoints through the former event scan. Re-claiming * them through the ledger would re-observe each checkpoint with a duration equal * to the turn's age, so the turn is sealed once: its queue row becomes a * `pre_ledger_history` sentinel and the remaining completed checkpoints receive * sentinels, after which every later claim conflicts and the terminal-failed * fence stays closed. The check is one bounded index probe for an earlier * current-association `turn.started` row, performed only by the transaction * that first claimed the queue checkpoint, never per model request. */ async function sealPreLedgerTurnStartupHistory( tx: Database, input: TurnStartupLedgerScope & { queueEvent: { id: string; sequence: number }; }, ): Promise { const [earlier] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.type, "turn.started"), eq(schema.sessionEvents.turnAssociation, "current"), lt(schema.sessionEvents.sequence, input.queueEvent.sequence), ), ) .limit(1); if (!earlier) return false; const ledger = schema.sessionTurnStartupMilestones; await tx .update(ledger) .set({ canonicalSource: "pre_ledger_history", eventId: null, occurredAt: null, }) .where( and( eq(ledger.workspaceId, input.workspaceId), eq(ledger.turnId, input.turnId), eq(ledger.milestone, "queue"), eq(ledger.outcome, "completed"), eq(ledger.eventId, input.queueEvent.id), ), ); await tx .insert(ledger) .values( (["provider_dispatch", "first_byte"] as const).map((milestone) => ({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, milestone, outcome: "completed", canonicalSource: "pre_ledger_history", eventId: null, occurredAt: null, })), ) .onConflictDoNothing(); return true; } async function canonicalTurnStartupMilestonesForInsertedEvents( tx: Database, input: TurnStartupLedgerScope & { turnCreatedAt: Date; inserted: Array; terminalTurnFailed: boolean; }, ): Promise { // The lowest-sequence inserted event per checkpoint is this transaction's // candidate; a second same-kind event in one batch can never be canonical. const candidates = new Map(); for (const event of [...input.inserted].sort((a, b) => a.sequence - b.sequence)) { const checkpoint = startupMilestoneForEvent(event); if (!checkpoint) continue; // A request-local transport terminal is not a logical startup failure: it // may recover, or it may follow a byte during a later tool loop. Only the // atomic terminal failed-turn settlement may project the exclusive failed // outcome; ordinary append/replay paths keep this flag false. if (checkpoint.outcome === "failed" && !input.terminalTurnFailed) continue; const key = startupCheckpointKey(checkpoint); if (!candidates.has(key)) candidates.set(key, event); } if (candidates.size === 0) return []; const scope = { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, }; const receipts: CanonicalTurnStartupMilestoneReceipt[] = []; // Checkpoint order matters: completed checkpoints first so the terminal // failed fence observes every completed row of this transaction, and queue // first so a pre-ledger turn is sealed before its later checkpoints claim. for (const checkpoint of TURN_STARTUP_CHECKPOINTS) { const { milestone, outcome } = checkpoint; const candidate = candidates.get(startupCheckpointKey(checkpoint)); if (!candidate) continue; // A durable ledger row from an earlier transaction means that checkpoint is // already canonical. Only the transaction that first inserts the checkpoint // may return a metric receipt, which makes ordinary recovery and callback // replay no-ops. The consumer's in-memory Prometheus observation happens // after COMMIT and remains explicitly at-most-once across a process crash. const claimed = await claimTurnStartupMilestone(tx, { ...scope, checkpoint, event: { id: candidate.id, occurredAt: candidate.occurredAt }, }); if (!claimed) continue; if ( milestone === "queue" && (await sealPreLedgerTurnStartupHistory(tx, { ...scope, queueEvent: { id: candidate.id, sequence: candidate.sequence }, })) ) { continue; } receipts.push({ milestone, outcome, eventId: candidate.id, durationMs: Math.max(0, candidate.occurredAt.getTime() - input.turnCreatedAt.getTime()), }); } return receipts; } /** * Atomically append terminal/requires-action truth, update the exact turn, and * transition the owning session. A superseded dispatch or closed control gate * is an event-free stale result. This prevents a zombie * from appending a terminal event before losing a later turn/session CAS. */ export async function applySessionTurnSettlement( db: Database, workspaceId: string, input: ApplySessionTurnSettlementInput, hooks: ApplySessionTurnSettlementHooks = {}, ): Promise { if ( input.suppressGoalContinuation && (!isTerminalSessionTurnStatus(input.turnStatus) || input.activeTurnId !== null) ) { throw new Error( "Goal continuation suppression requires a terminal turn with no active turn pointer", ); } const fromStatuses = input.fromStatuses ?? ["running", "requires_action"]; const eventTypes = [ ...input.events.map((event) => event.type), ...(input.recording?.action === "available" ? ["recording.available"] : input.recording?.action === "failed" ? ["recording.failed"] : []), ...(input.compactionRequestFailure || input.dropProactiveCompactionRequest ? ["session.context.compaction.skipped"] : []), ...(input.turnStatus === "failed" ? ["child_terminal_result"] : []), ...(input.turnStatus === "requires_action" ? ["child_requires_action"] : []), ]; const persistence = { stage: "session_lifecycle_outbox.settle_turn", eventTypes, maxAttempts: 3, }; const terminalTurn = isTerminalSessionTurnStatus(input.turnStatus); // Measured once, before the transaction and its retries, so no lock is held // while it runs. Stale and superseded attempts still settle as before. const runStateViolation = input.runState ? approvalRunStateSaveViolation( input.runState.serializedRunState, input.runState.pendingApprovals, ) : null; return await retrySessionActivityRls(db, workspaceId, persistence, async (scopedDb) => { // A terminal settlement cancels the turn's still-pending human-input rows. // Their parent resolution notices need the parent locked with the child, // so peek (unlocked) for such rows first; they are created only by this // same turn's earlier requires_action settlement, which the session lock // serialized before this attempt. const terminalHumanInputNotices = terminalTurn && input.turnStatus !== "failed" && childLifecycleNoticesEnabled() && ( await scopedDb .select({ id: schema.sessionHumanInputRequests.id }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.turnId, input.turnId), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), ), ) .limit(1) ).length > 0; return await scopedDb.transaction(async (tx) => { const locks = input.turnStatus === "failed" || input.turnStatus === "requires_action" || terminalHumanInputNotices ? await lockChildLifecycleOutboxWriteRowsTx(tx as unknown as Database, workspaceId, { sessionId: input.sessionId, turnId: input.turnId, attemptId: input.attemptId, }) : await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); const session = locks.sessions.find((row) => row.id === input.sessionId); const turn = locks.turns.find((row) => row.id === input.turnId); const attempt = locks.attempts.find((row) => row.id === input.attemptId); if (!session) { throw new Error(`Session not found: ${input.sessionId}`); } const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); const turnStatus = (turn?.status as SessionTurnStatus | undefined) ?? null; const [pendingInterruption] = turn ? await tx .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, input.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, input.attemptId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .limit(1) : []; if ( !turn || !attempt || !locks.workspace || turn.accountId !== session.accountId || turn.sessionId !== input.sessionId || attempt.accountId !== session.accountId || attempt.sessionId !== input.sessionId || attempt.turnId !== input.turnId || attempt.executionGeneration !== turn.executionGeneration || effectiveControl.state !== "active" || pendingInterruption !== undefined || session.activeTurnId !== input.turnId || !fromStatuses.includes(turnStatus as SessionTurnStatus) || turn.activeAttemptId !== input.attemptId || (input.compactionRequestFailure !== undefined && !session.compactRequested) ) { return { action: "stale" as const, events: [] as [], turnStatus, activeTurnId: session.activeTurnId, }; } if ( input.requirePendingSteer && !(await pendingSteerExists(tx, workspaceId, input.sessionId, input.turnId)) ) { // The session row lock serializes this with queue edits, deletes, // claims and Agent Steer replacement, so the Steer this settlement // yields to is still waiting. return { action: "pending_steer_withdrawn" as const, events: [] as [] }; } // Secret approval cards are Opengeni's own (origin secret_use_approval), // never an agent's request: the runtime refuses to ask with one. const humanInputRequests = (input.runState?.humanInputRequests ?? []).map((request) => ({ ...request, questions: request.questions.map((question) => { const parsed = HumanInputQuestionContract.parse(question); if (parsed.skillReview) { const canonical = canonicalSkillReviewQuestion(question); if (!canonical || request.questions.length !== 1 || request.allowSkip) { throw new Error("Skill review requires the exact dedicated confirmation contract"); } return canonical; } return parsed.kind === "text" || parsed.allowOther ? parsed : { ...parsed, allowOther: true }; }), })); const interactionInterventionRequests = input.runState?.interactionInterventionRequests ?? []; let interactionRefusalEvent: AppendEventInput | null = null; // Decisions recorded while this attempt resumed (after its trigger) are // applied by the next resume. Their approvals stay in the frozen run // state for it, but are never shown or announced as waiting again. // When every approval was decided that way, the pause is still written // as requires_action with nothing shown; the workflow's immediate // re-peek resumes it from those decisions. const decidedSinceTrigger = input.runState && input.turnStatus === "requires_action" ? await approvalDecisionsAfterTriggerTx(tx as unknown as Database, { workspaceId, sessionId: input.sessionId, turnId: input.turnId, triggerEventId: input.triggerEventId, }) : null; const undecided = (approval: unknown) => !decidedSinceTrigger?.has( approvalDecisionKey(approvalIdentifier(approval), pendingApprovalRound(approval)), ); if (input.runState) { if (input.turnStatus !== "requires_action" || input.sessionStatus !== "requires_action") { throw new Error("A frozen run state requires a requires_action settlement"); } for (const request of humanInputRequests) { if (Buffer.byteLength(JSON.stringify(request.questions)) > 49_152) { throw new Error("Human-input request questions exceed the durable payload limit"); } if ( Buffer.byteLength(request.toolCallId) < 1 || Buffer.byteLength(request.toolCallId) > 1024 ) { throw new Error("Human-input tool call id exceeds the durable payload limit"); } } for (const request of interactionInterventionRequests) { RequestHumanInteractionToolInput.parse(request.input); if ( Buffer.byteLength(request.toolCallId) < 1 || Buffer.byteLength(request.toolCallId) > 1_024 ) { throw new Error( "Interaction intervention tool call id exceeds the durable payload limit", ); } } const [{ maxVersion } = { maxVersion: 0 }] = await tx .select({ maxVersion: sql`coalesce(max(${schema.agentRunStates.stateVersion}), 0)`, }) .from(schema.agentRunStates) .where( and( eq(schema.agentRunStates.workspaceId, workspaceId), eq(schema.agentRunStates.sessionId, input.sessionId), ), ); if (runStateViolation) throw runStateViolation; await tx.insert(schema.agentRunStates).values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, stateVersion: Number(maxVersion) + 1, serializedRunState: input.runState.serializedRunState, pendingApprovals: input.runState.pendingApprovals, }, "serializedRunState", "serializedRunStateCodecVersion", ), "pendingApprovals", "pendingApprovalsCodecVersion", ), ); const newHumanInputRequestIds: string[] = []; if (humanInputRequests.length > 0) { for (const request of humanInputRequests) { if (request.questions.length === 1 && request.questions[0]!.skillReview) { const [existing] = await tx .select() .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.accountId, session.accountId), eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.turnId, input.turnId), eq(schema.sessionHumanInputRequests.toolCallId, request.toolCallId), ), ) .for("update"); if (existing) { const canonical = existing.questions.length === 1 ? canonicalSkillReviewQuestion(existing.questions[0]!) : null; if ( existing.id !== request.id || !canonical || stableJson(canonical) !== stableJson(request.questions[0]) ) { throw new Error( `Human-input request ${request.id} changed contract before re-freeze`, ); } // Preserve immutable displayed/audited bytes. The unchanged // UPSERT predicate below still fences pending status, skip and // exact deadline; only generation ownership can advance. request.questions = existing.questions; } } const [persistedRequest] = await tx .insert(schema.sessionHumanInputRequests) .values({ id: request.id, accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnGeneration: turn.executionGeneration, creationAttemptId: input.attemptId, toolCallId: request.toolCallId, questions: request.questions, allowSkip: request.allowSkip, expiresAt: request.expiresAt ?? null, }) .onConflictDoUpdate({ target: [ schema.sessionHumanInputRequests.workspaceId, schema.sessionHumanInputRequests.sessionId, schema.sessionHumanInputRequests.turnId, schema.sessionHumanInputRequests.toolCallId, ], set: { // A different interruption may be answered first. The same // tool call then re-freezes under the turn's next execution // generation; preserve its stable request id/deadline and // advance only the ownership generation. turnGeneration: turn.executionGeneration, updatedAt: new Date(), }, setWhere: sql` ${schema.sessionHumanInputRequests.status} = 'pending' and ${schema.sessionHumanInputRequests.allowSkip} = ${request.allowSkip} and ${schema.sessionHumanInputRequests.questions} = ${JSON.stringify(request.questions)}::jsonb and ${schema.sessionHumanInputRequests.expiresAt} is not distinct from ${request.expiresAt?.toISOString() ?? null}::timestamptz `, }) .returning({ id: schema.sessionHumanInputRequests.id, inserted: sql`(xmax = 0)`, }); if (!persistedRequest) { throw new Error( `Human-input request ${request.id} changed contract or settled before re-freeze`, ); } if (persistedRequest.inserted) newHumanInputRequestIds.push(persistedRequest.id); } } for (const request of interactionInterventionRequests) { try { // A savepoint, so a refused request leaves nothing behind. await tx.transaction(async (savepoint) => { await persistAttemptInteractionInterventionInTransaction( savepoint as unknown as Database, { ...request, accountId: session.accountId, workspaceId, originatingSessionId: input.sessionId, originatingTurnId: input.turnId, originatingAttemptId: input.attemptId, }, ); }); } catch (error) { if (!(error instanceof InteractionRequestRefusedError)) throw error; // The agent learns why as this call's result: the pause records // a system rejection, so the turn resumes at once instead of // failing. Only one refusal is recorded per pause, so a second // refused call stays pending; a later resume's re-freeze passes // it here again and it is refused the same way. interactionRefusalEvent ??= { type: "user.approvalDecision", payload: { approvalId: request.toolCallId, decision: "reject", refusal: error.refusal, }, clientEventId: `system:interaction-request-refused:${request.id}:${turn.executionGeneration}`, }; } } // The child is now blocked on a human. Tell its parent through the // durable outbox (the worker delivers it): one row per exact // (child, turn, generation), so a same-generation re-freeze after an // activity retry dedupes and a later generation is a new notice. // A refused request resumes the turn at once, so nobody is waited on. if (!interactionRefusalEvent) { await enqueueChildRequiresActionOutboxTx( tx as unknown as Database, workspaceId, session, { turnId: input.turnId, turnGeneration: turn.executionGeneration, humanInputRequests, newHumanInputRequestIds, pendingApprovals: input.runState.pendingApprovals.filter(undecided), }, ); } } let recordingEvent: AppendEventInput | null = null; let recordingMutationApplied = false; if (input.recording) { const [recording] = await tx .select() .from(schema.sessionRecordings) .where( and( eq(schema.sessionRecordings.accountId, session.accountId), eq(schema.sessionRecordings.workspaceId, workspaceId), eq(schema.sessionRecordings.sessionId, input.sessionId), eq(schema.sessionRecordings.turnId, input.turnId), eq(schema.sessionRecordings.id, input.recording.recordingId), eq(schema.sessionRecordings.mode, "on-turn"), inArray(schema.sessionRecordings.state, ["recording", "finalizing"]), ), ) .for("update") .limit(1); if (recording) { const recordingInput = input.recording; if (recordingInput.action === "discard") { await tx .delete(schema.sessionRecordings) .where(eq(schema.sessionRecordings.id, recording.id)); } else if (recordingInput.action === "available") { await tx .update(schema.sessionRecordings) .set( withLosslessContentWriteVersion( { state: "available", storageKey: recordingInput.storageKey, sizeBytes: recordingInput.sizeBytes, durationSeconds: recordingInput.durationSeconds, reason: null, finalizedAt: new Date(), }, "reason", "reasonCodecVersion", ), ) .where(eq(schema.sessionRecordings.id, recording.id)); recordingEvent = { type: "recording.available", payload: { recordingId: recording.id, turnId: input.turnId, codec: recording.codec, contentType: recording.codec === "vp9-webm" ? "video/webm" : "video/mp4", storageKey: recordingInput.storageKey, durationSeconds: recordingInput.durationSeconds, sizeBytes: recordingInput.sizeBytes, dimensions: [recording.width, recording.height], }, ...(recordingInput.producerId != null ? { producerId: recordingInput.producerId } : {}), ...(recordingInput.producerSeq != null ? { producerSeq: recordingInput.producerSeq } : {}), ...(recordingInput.occurredAt ? { occurredAt: recordingInput.occurredAt } : {}), }; } else { await tx .update(schema.sessionRecordings) .set( withLosslessContentWriteVersion( { state: "failed", reason: recordingInput.detail, finalizedAt: new Date(), }, "reason", "reasonCodecVersion", ), ) .where(eq(schema.sessionRecordings.id, recording.id)); recordingEvent = { type: "recording.failed", payload: { recordingId: recording.id, turnId: input.turnId, reason: recordingInput.reason, detail: recordingInput.detail, }, ...(recordingInput.producerId != null ? { producerId: recordingInput.producerId } : {}), ...(recordingInput.producerSeq != null ? { producerSeq: recordingInput.producerSeq } : {}), ...(recordingInput.occurredAt ? { occurredAt: recordingInput.occurredAt } : {}), }; } recordingMutationApplied = true; } } let effectiveSessionStatus = input.sessionStatus; if (input.sessionStatus === "idle" && input.activeTurnId === null) { // Messages waiting for the personal machine's owner leave it idle. const waitingPrompt = await runnableQueuedTurnExists(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sources: ["user", "api"], }); if (waitingPrompt) effectiveSessionStatus = "queued"; } const now = new Date(); const terminal = isTerminalSessionTurnStatus(input.turnStatus); const attemptOutcome = attemptOutcomeForTurnStatus(input.turnStatus); if (attemptOutcome) { await closeSessionTurnAttemptInTransaction(tx as unknown as Database, { id: input.attemptId, accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: turn.executionGeneration, outcome: attemptOutcome, closedAt: now, }); } if (terminal) { await cancelTurnInteractionInterventionsInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, }); if (["idle", "failed", "cancelled"].includes(effectiveSessionStatus)) { await settleSessionMaintenanceInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, }); } } let sequence = session.lastSequence; const closesAttempt = ["failed", "cancelled", "superseded"].includes(input.turnStatus); const closedTools = closesAttempt ? await closePendingSessionToolCallsInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, reason: `turn_${input.turnStatus}`, sequence, now, ...(input.notStartedToolCallIds?.length ? { notStartedCallIds: input.notStartedToolCallIds } : {}), }) : { sequence, events: [] as SessionEvent[], closed: 0, interrupted: 0 }; sequence = closedTools.sequence; const compactionRequestEvent: AppendEventInput | null = input.compactionRequestFailure ? { type: "session.context.compaction.skipped", payload: { reason: input.compactionRequestFailure.reason }, ...(input.compactionRequestFailure.producerId != null ? { producerId: input.compactionRequestFailure.producerId } : {}), ...(input.compactionRequestFailure.producerSeq != null ? { producerSeq: input.compactionRequestFailure.producerSeq } : {}), ...(input.compactionRequestFailure.occurredAt ? { occurredAt: input.compactionRequestFailure.occurredAt } : {}), } : null; const dropProactiveCompaction = input.dropProactiveCompactionRequest !== undefined && input.compactionRequestFailure === undefined && session.compactRequested && session.compactRequestTrigger === "proactive"; const proactiveCompactionDropEvent: AppendEventInput | null = dropProactiveCompaction ? { type: "session.context.compaction.skipped", payload: { reason: "capacity_unavailable", trigger: "proactive" }, ...(input.dropProactiveCompactionRequest?.producerId != null ? { producerId: input.dropProactiveCompactionRequest.producerId } : {}), ...(input.dropProactiveCompactionRequest?.producerSeq != null ? { producerSeq: input.dropProactiveCompactionRequest.producerSeq } : {}), } : null; const projectedInputEvents = input.dropProactiveCompactionRequest === undefined ? input.events : input.events.map((event) => event.type === "turn.cancelled" && event.payload && typeof event.payload === "object" && "requestPreserved" in event.payload ? { ...event, payload: { ...event.payload, requestPreserved: !dropProactiveCompaction }, } : event, ); const inputEvents = decidedSinceTrigger && decidedSinceTrigger.size > 0 ? projectedInputEvents.flatMap((event) => { if (event.type !== "session.requiresAction") return [event]; const payload = event.payload && typeof event.payload === "object" ? (event.payload as Record) : {}; const approvals = Array.isArray(payload.approvals) ? payload.approvals : []; const waiting = approvals.filter(undecided); if (waiting.length === approvals.length) return [event]; return waiting.length > 0 ? [{ ...event, payload: { ...payload, approvals: waiting } }] : []; }) : projectedInputEvents; if (input.turnStatus === "completed") { await settleInterruptedCodemodeCallsInTransaction(tx as unknown as Database, { workspaceId, sessionId: input.sessionId, turnId: input.turnId, reason: "turn_completed", now, }); await consumeSettledPendingToolCallsForCompletedTurnInTransaction( tx as unknown as Database, { workspaceId, sessionId: input.sessionId, turnId: input.turnId, }, ); } const terminalHumanInputRows = ["completed", "failed", "cancelled", "superseded"].includes( input.turnStatus, ) ? await tx .update(schema.sessionHumanInputRequests) .set({ status: "cancelled", response: { outcome: "cancelled" }, respondedBy: `system:turn_${input.turnStatus}`, respondedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.turnId, input.turnId), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), ), ) .returning({ id: schema.sessionHumanInputRequests.id, questions: schema.sessionHumanInputRequests.questions, turnGeneration: schema.sessionHumanInputRequests.turnGeneration, }) : []; for (const request of terminalHumanInputRows) { // The child's blocked boundary is gone with the turn: its parent's // still-pending child_requires_action notice is stale. Lock prefix: // the terminal peek above already chose the child-lifecycle lock. await enqueueChildRequiresActionResolvedOutboxTx( tx as unknown as Database, workspaceId, session, { turnId: input.turnId, turnGeneration: request.turnGeneration, requestId: request.id, approvalId: null, outcome: "cancelled", respondedByKind: "system", }, ); } const terminalHumanInputEvents: AppendEventInput[] = terminalHumanInputRows.map( (request) => ({ type: "user.humanInputResponse", payload: { requestId: request.id, response: { outcome: "cancelled" }, }, }), ); const settledMachineInputs = ["completed", "failed", "cancelled", "superseded"].includes( input.turnStatus, ) ? await tx .select({ id: schema.sessionSystemUpdates.id, historyItemId: schema.sessionSystemUpdates.deliveredHistoryItemId, }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.deliveredTurnId, input.turnId), eq(schema.sessionSystemUpdates.state, "delivered"), ), ) .orderBy( asc(schema.sessionSystemUpdates.createdAt), asc(schema.sessionSystemUpdates.id), ) : []; const machineInputSettlementEvent: AppendEventInput | null = settledMachineInputs.length > 0 ? { type: "system.update.settled", payload: { updateIds: settledMachineInputs.map((update) => update.id), count: settledMachineInputs.length, historyItemId: settledMachineInputs[0]!.historyItemId, outcome: input.turnStatus, }, } : null; // The model now durably holds each child answer this attempt returned // to it whole. A pending result repeating only those answers would start // an inference that repeats them, so it is superseded before any claim. const consumedChildResultIds = input.turnStatus === "completed" ? await supersedeChildResultsConsumedByCompletedAttemptTx(tx as unknown as Database, { workspaceId, sessionId: input.sessionId, turnId: input.turnId, attemptId: input.attemptId, turnMetadata: turn.metadata, }) : []; const consumedChildResultEvent: AppendEventInput | null = consumedChildResultIds.length > 0 ? { type: "system.update.cancelled", payload: { updateIds: consumedChildResultIds, count: consumedChildResultIds.length, reason: "consumed_by_parent_read", }, } : null; let allowanceGoalEvent: AppendEventInput | null = null; if (input.allowanceGoalPause && input.turnStatus === "completed") { const [pausedGoal] = await tx .update(schema.sessionGoals) .set({ status: "paused", pausedReason: input.allowanceGoalPause.reason ?? "allowance", rationale: input.allowanceGoalPause.rationale, continuationObservedRevision: sql`${schema.sessionGoals.continuationWakeRevision}`, version: sql`${schema.sessionGoals.version} + 1`, updatedAt: now, }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), eq(schema.sessionGoals.status, "active"), ), ) .returning({ id: schema.sessionGoals.id, autoContinuations: schema.sessionGoals.autoContinuations, noProgressStreak: schema.sessionGoals.noProgressStreak, }); if (pausedGoal) { allowanceGoalEvent = { type: "goal.paused", payload: { goalId: pausedGoal.id, actor: "system", reason: input.allowanceGoalPause.reason ?? "allowance", rationale: input.allowanceGoalPause.rationale, autoContinuations: pausedGoal.autoContinuations, noProgressStreak: pausedGoal.noProgressStreak, }, }; } } const settlementEvents = [ ...(recordingEvent ? [recordingEvent] : []), ...(compactionRequestEvent ? [compactionRequestEvent] : []), ...(proactiveCompactionDropEvent ? [proactiveCompactionDropEvent] : []), ...terminalHumanInputEvents, ...(machineInputSettlementEvent ? [machineInputSettlementEvent] : []), ...(consumedChildResultEvent ? [consumedChildResultEvent] : []), ...inputEvents, ...(interactionRefusalEvent ? [interactionRefusalEvent] : []), ...(allowanceGoalEvent ? [allowanceGoalEvent] : []), ]; const values = settlementEvents.map((event) => { const payload = event.payload && typeof event.payload === "object" ? (event.payload as Record) : {}; return { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: event.type, payload: event.type === "session.status.changed" && payload.status === input.sessionStatus && effectiveSessionStatus !== input.sessionStatus ? { ...payload, status: effectiveSessionStatus } : payload, clientEventId: event.clientEventId ?? null, turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current" as const, producerId: event.producerId ?? null, producerSeq: event.producerSeq ?? null, occurredAt: event.occurredAt ?? now, }; }); const inserted = values.length > 0 ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning() : []; const canonicalStartupMilestones = await canonicalTurnStartupMilestonesForInsertedEvents( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnCreatedAt: turn.createdAt, inserted, terminalTurnFailed: input.turnStatus === "failed", }, ); const requestedEvents = inserted.filter( (event) => event.type === "session.humanInput.requested", ); if (requestedEvents.length > 0) { const requestedIds = new Set( requestedEvents.flatMap((event) => { const request = sessionEventPayloadRecord( event.payload, event.payloadCodecVersion, ).request; if (!request || typeof request !== "object" || Array.isArray(request)) return []; const id = (request as Record).id; return typeof id === "string" ? [id] : []; }), ); const requests = humanInputRequests.filter((request) => requestedIds.has(request.id)); if (requests.length !== requestedIds.size) { throw new Error("Human-input realtime projection lost its durable request contract"); } await mirrorSessionRealtimeContextInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sourceKind: "human_input_request", sourceId: requestedEvents.map((event) => event.id).join(":"), turnId: input.turnId, channel: "speakable", text: renderRealtimeHumanInputRequestContext({ requests }), payload: { status: "waiting_for_user", requestIds: requests.map((request) => request.id), sourceEventIds: requestedEvents.map((event) => event.id), }, now, }); } const terminalHumanInputById = new Map( terminalHumanInputRows.map((request) => [request.id, request]), ); for (const event of inserted) { if (event.type !== "user.humanInputResponse") continue; const payload = sessionEventPayloadRecord(event.payload, event.payloadCodecVersion); const requestId = typeof payload.requestId === "string" ? payload.requestId : null; const request = requestId ? terminalHumanInputById.get(requestId) : null; if (!request) continue; await mirrorSessionRealtimeContextInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sourceKind: "human_input_response", sourceId: event.id, turnId: input.turnId, channel: null, text: renderRealtimeHumanInputResponseContext({ requestId: request.id, questions: request.questions, response: { outcome: "cancelled" }, }), payload: { requestId: request.id, outcome: "cancelled", sourceEventId: event.id, }, now, }); } if (isTerminalSessionTurnStatus(input.turnStatus)) { const terminalType = terminalSessionTurnEventType(input.turnStatus); const terminalEventIndex = settlementEvents.findIndex( (event) => event.type === terminalType, ); const persistedTerminal = terminalEventIndex >= 0 ? inserted[terminalEventIndex] : undefined; const terminalInput = terminalEventIndex >= 0 ? settlementEvents[terminalEventIndex] : undefined; const projection = await projectSessionRealtimeDelegationTerminalInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnStatus: input.turnStatus, terminalEvent: { id: persistedTerminal?.id ?? null, type: terminalType, payload: persistedTerminal ? sessionEventPayloadRecord( persistedTerminal.payload, persistedTerminal.payloadCodecVersion, ) : { code: "delegation_terminal_event_missing", error: `Delegated turn reached ${input.turnStatus} without its canonical terminal event.`, }, }, retainedOutputEvidence: terminalInput?.retainedOutputEvidence, now, }, ); if (projection) { await hooks.afterRealtimeDelegationProjection?.({ entryId: projection.entry.id, turnId: input.turnId, }); } } if (input.turnStatus === "running") { // Approval resume re-enters the same logical turn after a new fenced // dispatch has advanced its trigger. It is an authorized inference // transition, just like the initial claim, and must pass the database // guard without opening a second mutation path. await tx.execute(sql`set local opengeni.session_inference_claim = '1'`); } await tx .update(schema.sessionTurns) .set({ status: input.turnStatus, activeAttemptId: terminal || input.turnStatus === "requires_action" ? null : turn.activeAttemptId, version: turn.version + 1, // A requires_action result is a completed activity attempt. Keep the // generation for monotonic fencing, but remove the old activity id so // a later typed SCHEDULE_TO_START timeout can recover an approval // dispatch that never registered without taking over a newer one. ...(input.turnStatus === "requires_action" || input.turnStatus === "superseded" ? { metadata: metadataWithoutTurnDispatchAttempt(turn.metadata) } : {}), finishedAt: input.turnStatus === "queued" || input.turnStatus === "running" || input.turnStatus === "requires_action" ? null : now, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), ), ); if (input.turnStatus === "failed") { await enqueueFailedChildOutboxForTurnTx( tx as unknown as Database, workspaceId, session, turn, ); } await tx .update(schema.sessions) .set({ status: effectiveSessionStatus, activeTurnId: input.activeTurnId, ...(input.compactionRequestFailure || dropProactiveCompaction ? { compactRequested: false, compactRequestTrigger: null } : {}), lastSequence: sequence, queueVersion: session.queueVersion + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); // Supersession already has newer human/Agent direction waiting. It must // not also arm or suppress an autonomous goal continuation behind that // Steer. if ( terminal && input.turnStatus !== "superseded" && input.activeTurnId === null && input.suppressGoalContinuation ) { await tx .update(schema.sessionGoals) .set({ continuationSuppressedTurnId: input.turnId, updatedAt: now }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), eq(schema.sessionGoals.status, "active"), ), ); } if ( terminal && input.turnStatus !== "superseded" && input.activeTurnId === null && !input.suppressGoalContinuation ) { const [armedGoal] = await tx .update(schema.sessionGoals) .set({ continuationWakeRevision: sql`${schema.sessionGoals.continuationWakeRevision} + 1`, ...SESSION_GOAL_SUPPRESSION_CLEARED, updatedAt: now, }) .where( and( eq(schema.sessionGoals.workspaceId, workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), eq(schema.sessionGoals.status, "active"), ), ) .returning({ id: schema.sessionGoals.id }); if (armedGoal) { // The obligation and its repairable Temporal nudge commit with the // terminal turn/session boundary. A worker death or lost activity // response after COMMIT therefore cannot strand an active idle goal. await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${input.sessionId}`, reason: "goal_turn_settled", }); } } return { action: "settled" as const, events: [...closedTools.events, ...inserted.map(mapEvent)], canonicalStartupMilestones, recordingMutationApplied, }; }); }); } import { stageSubscriptionCorePendingServingPolicyTx } from "./subscription-core/serving-policy"; import { assertSubscriptionServingRecoverySettledTx } from "./subscription-core/serving-runtime"; export type RequestSessionTurnRecoveryInput = { /** Route selection only: keep this logical turn on HTTP after socket refusal/exhaustion. */ persistentModelTransportHttpOnly?: true; /** C2 only: proposal is persisted atomically with recovery, never placement. */ subscriptionServingTarget?: { crossProviderFailoverEnabled: true; executionGeneration: number; policy: import("@opengeni/contracts").TurnServingPolicyV1["policy"]; connectionId: string; reason: import("@opengeni/contracts").TurnServingPolicyV1["reason"]; }; sessionId: string; turnId: string; triggerEventId: string; attemptId: string; reason: string; detail?: Record; sandboxLifecycleWait?: SandboxLifecycleWait; /** Park incomplete setup; this never authorizes a replacement setup attempt. */ sandboxSetupOutcomeUnknown?: true; /** Park proven non-dispatch after the existing five-recovery budget. */ sandboxSetupRecoveryExhausted?: true; providerRecoveryCount?: number; /** * Backoff before the replacement attempt may dispatch, measured on the * database clock. Stored on the turn and armed as a delayed workflow wake, * so the session's own wakes cannot shorten it; new user input can. */ retryAfterMs?: number; /** In-flight calls with call-scoped proof that their command never started. */ notStartedToolCallIds?: readonly string[]; /** * The consecutive shared-core lease-busy chain this recovery continues: when * it started and the execution generation that recorded it. The worker * bounds the chain; the database only stores it on the turn. */ subscriptionLeaseBusy?: { startedAt: string; executionGeneration: number }; fromStatuses?: SessionTurnStatus[]; providerArtifactInvalidation?: { historyItemIds: string[]; runStateId?: string; reason: "encrypted_content_rejected"; }; }; export type RequestSessionTurnRecoveryResult = | { action: "recovering"; events: SessionEvent[]; providerArtifactsInvalidated?: number; } | { action: "not_recoverable"; events: []; providerArtifactsInvalidated: 0; } | { action: "stale"; events: []; turnStatus: SessionTurnStatus | null; activeTurnId: string | null; }; export type SessionTurnToolProgressRecoveryState = { /** The turn has a model tool call whose execution has no recorded result. */ toolCallInFlight: boolean; /** * Budgeted recoveries that interrupted a tool call since the turn's last * tool progress (a recorded tool result) or explicit human Retry. */ toolInterruptedRecoveries: number; }; /** * Evidence for bounding recoveries that interrupt tool execution. Those * recoveries are followed by a successful model response before the tool runs * again, so the model-response reset alone would never exhaust their budget. */ export async function readSessionTurnToolProgressRecoveryState( db: Database, workspaceId: string, input: { sessionId: string; turnId: string }, ): Promise { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ in_flight: boolean; recoveries: number | string }>( scopedDb as unknown as Database, sql`select exists ( select 1 from session_pending_tool_calls pending where pending.workspace_id = ${workspaceId} and pending.session_id = ${input.sessionId} and pending.turn_id = ${input.turnId} and pending.result_item_ordered is null and pending.interruption_kind is null ) as in_flight, ( select count(*) from session_events recovery where recovery.workspace_id = ${workspaceId} and recovery.session_id = ${input.sessionId} and recovery.turn_id = ${input.turnId} and recovery.type = 'turn.recovery.requested' and recovery.payload->>'toolCallInterrupted' = 'true' and recovery.sequence > coalesce(( select max(progress.sequence) from session_events progress where progress.workspace_id = ${workspaceId} and progress.session_id = ${input.sessionId} and progress.turn_id = ${input.turnId} and ( (progress.type = 'agent.toolCall.output' and coalesce(progress.payload->'recovery'->>'outcome', 'durable_result_found') = 'durable_result_found') or (progress.type = 'turn.recovery.requested' and progress.payload->>'reason' = 'human_retry') ) ), 0) ) as recoveries`, ); return { toolCallInFlight: row?.in_flight === true, toolInterruptedRecoveries: Number(row?.recoveries ?? 0), }; }); } /** The `sandbox.operation.*` name a worker records when it restarts a turn's * sandbox because the sandbox could no longer start programs. */ export const SANDBOX_PROCESS_START_RESTART_OPERATION = "sandbox.process_start_restart"; /** * How many times this turn already restarted its sandbox because it could not * start programs, since the person last asked to retry it: restarts begun * (recorded before the restart call, so a crash still counts) and restarts * that completed. The worker begins at most one per turn, so a box that stays * broken fails the turn instead of restarting in a loop; a human Retry is a * new request and may restart again. */ export async function countSessionTurnSandboxProcessStartRestarts( db: Database, workspaceId: string, input: { sessionId: string; turnId: string }, ): Promise<{ started: number; completed: number }> { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ started: number | string; completed: number | string }>( scopedDb as unknown as Database, sql`select count(*) filter (where restart.type = 'sandbox.operation.started') as started, count(*) filter (where restart.type = 'sandbox.operation.completed') as completed from session_events restart where restart.workspace_id = ${workspaceId} and restart.session_id = ${input.sessionId} and restart.turn_id = ${input.turnId} and restart.type in ('sandbox.operation.started', 'sandbox.operation.completed') and restart.payload->>'name' = ${SANDBOX_PROCESS_START_RESTART_OPERATION} and restart.sequence > coalesce(( select max(retry.sequence) from session_events retry where retry.workspace_id = ${workspaceId} and retry.session_id = ${input.sessionId} and retry.turn_id = ${input.turnId} and retry.type = 'turn.recovery.requested' and retry.payload->>'reason' = 'human_retry' ), 0)`, ); return { started: Number(row?.started ?? 0), completed: Number(row?.completed ?? 0) }; }); } /** * Ask the lease to replace one exact live box whose programs cannot start * (Modal: its /bin/sh is gone). The same operator rotation an image conflict * requests: new arrivals are fenced instead of reusing the box, the drain * grace is zero once its last holder leaves, and the reaper saves /workspace * with the provider's own snapshot before ending the box, so the next acquire * restores a fresh one. A box whose save fails stays draining under the * existing capture policy, and arrivals keep waiting instead of reusing it. * Null when the lease no longer names this box (another epoch or instance, or * not live): nothing is changed. */ export async function requestSandboxProcessStartReplacement( db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; leaseEpoch: number; instanceId: string; }, ): Promise<{ sandboxGroupId: string; leaseEpoch: number; instanceId: string; liveness: "warm" | "draining"; } | null> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await rawRows<{ lease_epoch: number | string; instance_id: string; liveness: "warm" | "draining"; }>( scopedDb as unknown as Database, sql`update sandbox_leases set rotation_requested_at = coalesce(rotation_requested_at, now()), rotation_reason = coalesce(rotation_reason, 'operator'), expires_at = least(expires_at, now()), updated_at = now() where account_id = ${input.accountId} and workspace_id = ${input.workspaceId} and sandbox_group_id = ${input.sandboxGroupId} and lease_epoch = ${input.leaseEpoch} and instance_id = ${input.instanceId} and liveness in ('warm', 'draining') returning lease_epoch, instance_id, liveness`, ); const row = rows[0]; return row ? { sandboxGroupId: input.sandboxGroupId, leaseEpoch: Number(row.lease_epoch), instanceId: row.instance_id, liveness: row.liveness, } : null; }, ); } /** The box a turn asked to replace because it could not start programs. */ export type SandboxProcessStartReplacementTarget = { sandboxGroupId: string; leaseEpoch: number; }; /** Turn metadata naming a box that could not start programs and whose save * failed while the turn waited on its replacement. */ export const SANDBOX_BOX_NOT_SAVED_METADATA_KEY = "sandboxBoxNotSaved"; /** * The box a drain could not save while this turn waited on its replacement * (it could not start programs), as recorded by * {@link releaseSandboxProcessStartReplacementWaiters}. It holds across a * person's retry: a retry fenced by the same unsaved box stops at once. Null * when no such save failed while the turn waited. */ export async function readSessionTurnSandboxBoxNotSaved( db: Database, workspaceId: string, input: { sessionId: string; turnId: string }, ): Promise { return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { const [row] = await rawRows<{ sandbox_group_id: string | null; lease_epoch: string | null }>( scopedDb as unknown as Database, sql`select turn.metadata->${SANDBOX_BOX_NOT_SAVED_METADATA_KEY}->>'sandboxGroupId' as sandbox_group_id, turn.metadata->${SANDBOX_BOX_NOT_SAVED_METADATA_KEY}->>'leaseEpoch' as lease_epoch from session_turns turn where turn.workspace_id = ${workspaceId} and turn.session_id = ${input.sessionId} and turn.id = ${input.turnId} limit 1`, ); const leaseEpoch = Number(row?.lease_epoch); return row?.sandbox_group_id && Number.isSafeInteger(leaseEpoch) && leaseEpoch >= 0 ? { sandboxGroupId: row.sandbox_group_id, leaseEpoch } : null; }); } /** * A drain could not save a box that a turn asked to replace because it could * not start programs. No turn should wait, possibly until the provider's * lifetime limit, on a save that keeps failing: every turn waiting on that * box's rotation has its wait cleared, is marked with the unsaved box, and is * woken, so its next attempt stops with clear copy (failure settlement). The * box stays fenced and its drain keeps retrying under the existing policy. * Only a rotation some turn requested for this exact box (its process-start * restart event names the group and epoch) releases anyone. Returns how many * turns were released. The waiting sessions and turns are locked in the * canonical event-write order (sessions, then turns, each in id order) before * the waits are cleared, and the waiters are woken in session-id order. The * turn update's archive guard locks the parent session, so locking a turn first * would invert that order and could deadlock with any ordinary writer. */ export async function releaseSandboxProcessStartReplacementWaiters( db: Database, input: { workspaceId: string; sandboxGroupId: string; leaseEpoch: number }, ): Promise { const waitJson = JSON.stringify({ [SANDBOX_LIFECYCLE_WAIT_METADATA_KEY]: { version: 1, sandboxGroupId: input.sandboxGroupId, leaseEpoch: input.leaseEpoch, reason: "rotation_in_progress", } satisfies SandboxLifecycleWait, }); const notSavedJson = JSON.stringify({ [SANDBOX_BOX_NOT_SAVED_METADATA_KEY]: { version: 1, sandboxGroupId: input.sandboxGroupId, leaseEpoch: input.leaseEpoch, }, }); const waitingOnThisBox = sql`session.workspace_id = ${input.workspaceId} and session.sandbox_group_id = ${input.sandboxGroupId} and session.status = 'recovering' and turn.workspace_id = session.workspace_id and turn.session_id = session.id and turn.id = session.active_turn_id and turn.status = 'recovering' and turn.metadata @> ${waitJson}::jsonb`; return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scopedDb) => scopedDb.transaction(async (txRaw) => { const tx = txRaw as unknown as Database; // Find the waiters without locking anything. const candidates = await rawRows<{ session_id: string; turn_id: string }>( tx, sql`select session.id as session_id, turn.id as turn_id from sessions session, session_turns turn where ${waitingOnThisBox} and exists ( select 1 from sessions requester join session_events restart on restart.workspace_id = requester.workspace_id and restart.session_id = requester.id where requester.workspace_id = ${input.workspaceId} and requester.sandbox_group_id = ${input.sandboxGroupId} and restart.type = 'sandbox.operation.started' and restart.payload->>'name' = ${SANDBOX_PROCESS_START_RESTART_OPERATION} and restart.payload->>'sandboxGroupId' = ${input.sandboxGroupId} and restart.payload->>'leaseEpoch' = ${String(input.leaseEpoch)} )`, ); if (candidates.length === 0) return 0; const turnIds = [...new Set(candidates.map((row) => row.turn_id))].sort(); await lockSessionEventWriteRows(tx, { workspaceId: input.workspaceId, controlLock: "share", rowProjection: "event", sessionIds: candidates.map((row) => row.session_id), turnIds, }); // Re-check under the locks: a waiter may have moved on meanwhile. const released = await rawRows<{ account_id: string; session_id: string; temporal_workflow_id: string | null; }>( tx, sql`update session_turns turn set metadata = (turn.metadata - ${SANDBOX_LIFECYCLE_WAIT_METADATA_KEY}) || ${notSavedJson}::jsonb, version = turn.version + 1, updated_at = now() from sessions session where ${waitingOnThisBox} and turn.id = any(${`{${turnIds.join(",")}}`}::uuid[]) returning session.account_id, session.id as session_id, session.temporal_workflow_id`, ); released.sort((left, right) => (left.session_id < right.session_id ? -1 : 1)); for (const waiter of released) { await enqueueSessionWorkflowWakeInTransaction(tx, { accountId: waiter.account_id, workspaceId: input.workspaceId, sessionId: waiter.session_id, temporalWorkflowId: waiter.temporal_workflow_id ?? `session-${waiter.session_id}`, reason: "sandbox_lifecycle_advanced", }); } return released.length; }), ); } export async function requestSessionTurnRecovery( db: Database, workspaceId: string, input: RequestSessionTurnRecoveryInput, ): Promise { if ( input.subscriptionLeaseBusy && (!Number.isFinite(Date.parse(input.subscriptionLeaseBusy.startedAt)) || !Number.isSafeInteger(input.subscriptionLeaseBusy.executionGeneration) || input.subscriptionLeaseBusy.executionGeneration < 1) ) throw new Error("Invalid subscription lease-busy recovery chain"); const fromStatuses = input.fromStatuses ?? ["running", "requires_action"]; return await withWorkspaceSessionActivityRls(db, workspaceId, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [input.sessionId], turnIds: [input.turnId], attemptIds: [input.attemptId], }); const session = locks.sessions[0]; const turn = locks.turns[0]; const attempt = locks.attempts[0]; if (!session) { throw new Error(`Session not found: ${input.sessionId}`); } const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); const turnStatus = (turn?.status as SessionTurnStatus | undefined) ?? null; const [pendingInterruption] = attempt ? await tx .select({ id: schema.sessionAttemptInterruptions.id }) .from(schema.sessionAttemptInterruptions) .where( and( eq(schema.sessionAttemptInterruptions.workspaceId, workspaceId), eq(schema.sessionAttemptInterruptions.sessionId, input.sessionId), eq(schema.sessionAttemptInterruptions.attemptId, input.attemptId), inArray(schema.sessionAttemptInterruptions.state, [ "pending", "delivered", "acknowledged", ]), ), ) .limit(1) .for("update") : []; if ( !locks.workspace || !turn || !attempt || turn.accountId !== session.accountId || turn.sessionId !== input.sessionId || attempt.accountId !== session.accountId || attempt.sessionId !== input.sessionId || attempt.turnId !== input.turnId || attempt.executionGeneration !== turn.executionGeneration || effectiveControl.state !== "active" || session.activeTurnId !== input.turnId || !fromStatuses.includes(turnStatus as SessionTurnStatus) || turn.activeAttemptId !== input.attemptId || pendingInterruption !== undefined ) { return { action: "stale" as const, events: [] as [], turnStatus, activeTurnId: session.activeTurnId, }; } const now = new Date(); if ( input.sandboxSetupRecoveryExhausted && (input.sandboxSetupOutcomeUnknown || input.providerRecoveryCount !== undefined || input.sandboxLifecycleWait || input.providerArtifactInvalidation || input.triggerEventId !== turn.triggerEventId || turn.metadata?.providerRecoveryCount !== SANDBOX_SETUP_RECOVERY_LIMIT || sandboxSetupOutcomeUnknownFromTurnMetadata(turn.metadata)) ) { throw new Error( "sandbox setup exhaustion requires the unchanged exhausted recovery budget", ); } if ( input.providerRecoveryCount !== undefined && (!Number.isSafeInteger(input.providerRecoveryCount) || input.providerRecoveryCount <= 0) ) { throw new Error("providerRecoveryCount must be a positive safe integer"); } if ( input.retryAfterMs !== undefined && (!Number.isFinite(input.retryAfterMs) || input.retryAfterMs < 0) ) { throw new Error("retryAfterMs must be a non-negative number of milliseconds"); } // Database clock, like every other wake deadline: the outbox dispatcher // and the admission peek both compare against DB `now()`. The bound // keeps a miscomputed delay from parking a turn indefinitely. const retryAfterMs = Math.min( Math.ceil(input.retryAfterMs ?? 0), SESSION_TURN_RECOVERY_RETRY_MAX_MS, ); const retryNotBefore = retryAfterMs > 0 ? new Date((await transactionNow(tx as unknown as Database)).getTime() + retryAfterMs) : null; if ( input.sandboxLifecycleWait && (!sandboxLifecycleWaitFromTurnMetadata({ [SANDBOX_LIFECYCLE_WAIT_METADATA_KEY]: input.sandboxLifecycleWait, }) || input.sandboxLifecycleWait.sandboxGroupId !== session.sandboxGroupId) ) { throw new Error("sandboxLifecycleWait is invalid for this session"); } let providerArtifactsInvalidated = 0; if (input.providerArtifactInvalidation) { const historyItemIds = [...new Set(input.providerArtifactInvalidation.historyItemIds)]; const invalidatedHistory = historyItemIds.length > 0 ? await tx .update(schema.sessionHistoryItems) .set({ providerArtifactInvalidatedAt: now, providerArtifactInvalidationReason: input.providerArtifactInvalidation.reason, providerArtifactInvalidatedByAttemptId: input.attemptId, }) .where( and( eq(schema.sessionHistoryItems.accountId, session.accountId), eq(schema.sessionHistoryItems.workspaceId, workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), eq(schema.sessionHistoryItems.active, true), inArray(schema.sessionHistoryItems.id, historyItemIds), isNull(schema.sessionHistoryItems.providerArtifactInvalidatedAt), sql`${schema.sessionHistoryItems.item} ->> 'type' in ('reasoning', 'compaction')`, sql`( nullif(${schema.sessionHistoryItems.item} ->> 'encrypted_content', '') is not null or nullif(${schema.sessionHistoryItems.item} ->> 'encryptedContent', '') is not null or nullif(${schema.sessionHistoryItems.item} -> 'providerData' ->> 'encrypted_content', '') is not null or nullif(${schema.sessionHistoryItems.item} -> 'providerData' ->> 'encryptedContent', '') is not null )`, ), ) .returning({ id: schema.sessionHistoryItems.id }) : []; const invalidatedRunState = input.providerArtifactInvalidation.runStateId ? await tx .update(schema.agentRunStates) .set({ providerArtifactInvalidatedAt: now, providerArtifactInvalidationReason: input.providerArtifactInvalidation.reason, providerArtifactInvalidatedByAttemptId: input.attemptId, }) .where( and( eq(schema.agentRunStates.accountId, session.accountId), eq(schema.agentRunStates.workspaceId, workspaceId), eq(schema.agentRunStates.sessionId, input.sessionId), eq(schema.agentRunStates.turnId, input.turnId), eq(schema.agentRunStates.id, input.providerArtifactInvalidation.runStateId), isNull(schema.agentRunStates.providerArtifactInvalidatedAt), sql`${schema.agentRunStates.stateVersion} = ( select max(latest.state_version) from agent_run_states latest where latest.account_id = ${session.accountId} and latest.workspace_id = ${workspaceId} and latest.session_id = ${input.sessionId} and latest.turn_id = ${input.turnId} )`, ), ) .returning({ id: schema.agentRunStates.id }) : []; providerArtifactsInvalidated = invalidatedHistory.length + invalidatedRunState.length; // A precise provider-artifact rejection is recoverable only when this // attempt durably removed at least one opaque artifact from the next // model input. Otherwise retrying would send an equivalent request and // create a recovery loop. if (providerArtifactsInvalidated === 0) { return { action: "not_recoverable" as const, events: [] as [], providerArtifactsInvalidated: 0 as const, }; } } let servingTarget: import("@opengeni/contracts").TurnPendingServingPolicyV1 | null = null; if (input.subscriptionServingTarget) { const target = input.subscriptionServingTarget; if ( target.crossProviderFailoverEnabled !== true || session.codexCompactionMode !== "portable" ) throw new Error("Serving recovery requires enabled failover and portable history"); const scope = { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, }; const fence = await lockTurnAttemptWriteFenceTx(tx as unknown as Database, { ...scope, attemptId: input.attemptId, executionGeneration: target.executionGeneration, }); if (!fence.allowed) throw new Error(`Serving recovery fenced: ${fence.reason}`); await assertSubscriptionServingRecoverySettledTx(tx as unknown as Database, scope); servingTarget = await stageSubscriptionCorePendingServingPolicyTx( tx as unknown as Database, { ...scope, ...target, attemptId: input.attemptId }, fence, ); } await closeSessionTurnAttemptInTransaction(tx as unknown as Database, { id: input.attemptId, accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, executionGeneration: turn.executionGeneration, outcome: "interrupted_recoverable", closedAt: now, }); let sequence = session.lastSequence; const closedTools = await closePendingSessionToolCallsInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: input.turnId, reason: input.reason, sequence, now, preserveInterruptionRows: true, ...(input.notStartedToolCallIds?.length ? { notStartedCallIds: input.notStartedToolCallIds } : {}), }, ); sequence = closedTools.sequence; const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "turn.recovery.requested", turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: turn.activeAttemptId, turnAssociation: "current", payload: { ...(input.detail ?? {}), triggerEventId: input.triggerEventId, reason: input.reason, // Durable fact for the tool-progress recovery bound: this // budgeted recovery interrupted an in-flight tool call. ...(input.providerRecoveryCount !== undefined && closedTools.interrupted > 0 ? { toolCallInterrupted: true } : {}), ...(providerArtifactsInvalidated > 0 ? { providerArtifactsInvalidated } : {}), }, occurredAt: now, }, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.status.changed", turnId: input.turnId, turnGeneration: turn.executionGeneration, turnAttemptId: turn.activeAttemptId, turnAssociation: "current", payload: { status: "recovering" }, occurredAt: now, }, ], "payload", "payloadCodecVersion", ), ) .returning(); const recoveryMetadata = recoverProviderClockAfterDependencyWait( recoveryTurnMetadata(turn.metadata, input.sandboxLifecycleWait), input.reason, now, ); const [updatedTurn] = await tx .update(schema.sessionTurns) .set({ status: "recovering", triggerEventId: turn.triggerEventId, finishedAt: null, activeAttemptId: null, cancelledBy: null, cancelReason: null, version: turn.version + 1, metadata: { ...recoveryMetadata, ...(input.persistentModelTransportHttpOnly ? { persistentModelTransportHttpOnly: true } : {}), ...(retryNotBefore ? { [RECOVERY_RETRY_METADATA_KEY]: { version: 1, notBefore: retryNotBefore.toISOString(), afterSequence: sequence, } satisfies SessionTurnRecoveryRetry, } : {}), ...(servingTarget ? { turnPendingServingPolicyV1: servingTarget } : {}), ...(input.subscriptionLeaseBusy ? { subscriptionLeaseBusy: { startedAt: input.subscriptionLeaseBusy.startedAt, executionGeneration: input.subscriptionLeaseBusy.executionGeneration, }, } : {}), ...(input.sandboxSetupOutcomeUnknown ? { [SANDBOX_SETUP_OUTCOME_UNKNOWN_METADATA_KEY]: { version: 1, turnId: input.turnId, attemptId: input.attemptId, reason: "sandbox_command_start_outcome_unknown", } satisfies SandboxSetupOutcomeUnknown, } : {}), ...(input.sandboxSetupRecoveryExhausted ? { [SANDBOX_SETUP_RECOVERY_EXHAUSTED_METADATA_KEY]: { version: 1, turnId: input.turnId, attemptId: input.attemptId, reason: "sandbox_command_start_recovery_exhausted", setupOutcome: "not_started", providerRecoveryCount: SANDBOX_SETUP_RECOVERY_LIMIT, } satisfies SandboxSetupRecoveryExhausted, } : {}), ...(input.providerRecoveryCount !== undefined ? { providerRecoveryCount: input.providerRecoveryCount, providerRecoveryStartedAt: providerRecoveryCountFromTurnMetadata(turn.metadata) > 0 && typeof recoveryMetadata.providerRecoveryStartedAt === "string" ? recoveryMetadata.providerRecoveryStartedAt : now.toISOString(), providerRecoveryReason: input.reason, } : {}), }, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), inArray(schema.sessionTurns.status, fromStatuses), ), ) .returning({ id: schema.sessionTurns.id }); if (!updatedTurn) { // The row is locked, so this is an invariant failure rather than a // legitimate race. Throwing rolls the events back too. throw new Error(`Recoverable session turn changed while locked: ${input.turnId}`); } const [updatedSession] = await tx .update(schema.sessions) .set({ status: "recovering", activeTurnId: input.turnId, lastSequence: sequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), eq(schema.sessions.activeTurnId, input.turnId), ), ) .returning({ id: schema.sessions.id }); if (!updatedSession) { throw new Error(`Active session turn changed while locked: ${input.turnId}`); } await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, temporalWorkflowId: session.temporalWorkflowId ?? `session-${input.sessionId}`, reason: "turn_recovery_requested", // The backstop wake fires when the backoff ends, not immediately: an // immediate wake would end the workflow's backoff hold seconds after // it began and spend the whole recovery budget within a minute. ...(retryNotBefore ? { notBefore: retryNotBefore } : {}), }); return { action: "recovering" as const, events: [...closedTools.events, ...inserted.map(mapEvent)], ...(input.providerArtifactInvalidation ? { providerArtifactsInvalidated } : {}), }; }); }); } export type RecoverSessionDispatchInput = { sessionId: string; attemptId: string; timeoutType: "HEARTBEAT" | "SCHEDULE_TO_START"; maxRedispatches: number; }; export type ReconcileSettledSessionAttemptInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; /** Server-authenticated inspection of this exact stored dispatch, not age. */ activitySettled: boolean; maxRedispatches: number; }; function sessionDispatchExpiryProducer(attemptId: string): string { return `opengeni:dispatch-retired:${attemptId}`; } type SessionDispatchExpiryIdentity = { accountId: string; workspaceId: string; sessionId: string; attemptId: string; }; const SessionDispatchExpiryPayload = z.strictObject({ attemptId: z.string().uuid(), timeoutType: z.enum(["HEARTBEAT", "SCHEDULE_TO_START"]), }); async function findSessionDispatchExpiryReceiptTx( tx: Database, identity: SessionDispatchExpiryIdentity, ) { const [receipt] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.accountId, identity.accountId), eq(schema.sessionEvents.workspaceId, identity.workspaceId), eq(schema.sessionEvents.sessionId, identity.sessionId), eq(schema.sessionEvents.producerId, sessionDispatchExpiryProducer(identity.attemptId)), eq(schema.sessionEvents.producerSeq, 1), ), ) .limit(1); return receipt; } function isSessionDispatchExpiryReceipt( receipt: typeof schema.sessionEvents.$inferSelect | undefined, identity: SessionDispatchExpiryIdentity, ): boolean { if ( !receipt || receipt.accountId !== identity.accountId || receipt.workspaceId !== identity.workspaceId || receipt.sessionId !== identity.sessionId || receipt.type !== "turn.dispatch.expired" || receipt.producerId !== sessionDispatchExpiryProducer(identity.attemptId) || receipt.producerSeq !== 1 || receipt.clientEventId !== null || receipt.turnId !== null || receipt.turnGeneration !== null || receipt.turnAttemptId !== null || receipt.turnAssociation !== null || receipt.duplicateOfEventId !== null || receipt.duplicateReason !== null ) { return false; } const payload = SessionDispatchExpiryPayload.safeParse( fromPostgresLosslessJson(receipt.payload, receipt.payloadCodecVersion), ); return payload.success && payload.data.attemptId === identity.attemptId; } export type RecoverSessionDispatchResult = | { action: "unclaimed"; events: [] } | { action: "recovering"; turnId: string; redispatches: number; events: SessionEvent[]; } | { action: "exceeded"; turnId: string; redispatches: number; events: SessionEvent[]; } | { action: "stale"; events: []; turnStatus: SessionTurnStatus | null; activeTurnId: string | null; }; export type ReconcileSettledSessionAttemptResult = | Exclude | { action: "pending"; events: [] }; /** Separate proof-bearing live-owner close; the generic observer never writes. */ export async function reconcileSettledSessionAttempt( db: Database, input: ReconcileSettledSessionAttemptInput, ): Promise { const scopedSession = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [visible] = await scopedDb .select({ activeTurnId: schema.sessions.activeTurnId }) .from(schema.sessions) .where( and( eq(schema.sessions.accountId, input.accountId), eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); return visible; }, ); if (!scopedSession) return { action: "stale", events: [], turnStatus: null, activeTurnId: null }; // The activity commit gate must own the outer transaction, not a savepoint // in the read-only scope check. Recovery revalidates scope and every proof // and current-owner edge under its own canonical locks. const result = await recoverSessionOwner(db, input.workspaceId, input); if (result.action === "unclaimed") throw new SessionControlInvariantError( "Settled owner recovery cannot expire an unclaimed dispatch", ); return result; } /** * Atomically recover the exact attempt that owned a running turn. If timeout * wins before its claim, persist an expiry receipt so a delayed activity cannot * create an owner afterward. This does not consume the crash-loop budget. */ export async function recoverSessionDispatch( db: Database, workspaceId: string, input: RecoverSessionDispatchInput, ): Promise { const result = await recoverSessionOwner(db, workspaceId, input); if (result.action === "pending") throw new SessionControlInvariantError("Timeout recovery cannot use settled-owner proof"); return result; } async function recoverSessionOwner( db: Database, workspaceId: string, input: RecoverSessionDispatchInput | ReconcileSettledSessionAttemptInput, ): Promise { const proof = "activitySettled" in input ? input : null; const timeoutType = "timeoutType" in input ? input.timeoutType : null; const persistence = { stage: "session_lifecycle_outbox.recover_dispatch", eventTypes: [ "child_terminal_result", "session.status.changed", "turn.failed", "turn.recovery.requested", "turn.dispatch.expired", "session.queue.changed", ], maxAttempts: 3, }; return await retrySessionActivityRls(db, workspaceId, persistence, async (scopedDb) => { return await withSessionActivitySavepoint(scopedDb, async (tx) => { const locks = await lockChildLifecycleOutboxWriteRowsTx( tx as unknown as Database, workspaceId, { sessionId: input.sessionId, attemptId: input.attemptId }, ); const session = locks.session; const effectiveControl = await evaluateSessionControl( tx as unknown as Database, workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); const attempt = locks.attempts.find((row) => row.id === input.attemptId); if (!attempt) { if (proof) return { action: "stale", events: [], turnStatus: null, activeTurnId: session.activeTurnId, }; const expiryIdentity = { accountId: session.accountId, workspaceId, sessionId: input.sessionId, attemptId: input.attemptId, }; const existing = await findSessionDispatchExpiryReceiptTx( tx as unknown as Database, expiryIdentity, ); if (existing && !isSessionDispatchExpiryReceipt(existing, expiryIdentity)) { throw new SessionControlInvariantError("Conflicting session dispatch expiry receipt"); } if (!existing) { const now = new Date(); const [inserted] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "turn.dispatch.expired", payload: { attemptId: input.attemptId, timeoutType }, clientEventId: null, producerId: sessionDispatchExpiryProducer(input.attemptId), producerSeq: 1, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionEvents.workspaceId, schema.sessionEvents.sessionId, schema.sessionEvents.producerId, schema.sessionEvents.producerSeq, ], where: sql`${schema.sessionEvents.producerId} is not null and ${schema.sessionEvents.producerSeq} is not null`, }) .returning(); if (!inserted) { const duplicate = await findSessionDispatchExpiryReceiptTx( tx as unknown as Database, expiryIdentity, ); if (!isSessionDispatchExpiryReceipt(duplicate, expiryIdentity)) { throw new SessionControlInvariantError("Conflicting session dispatch expiry receipt"); } } else { await tx .update(schema.sessions) .set({ lastSequence: inserted.sequence, updatedAt: now }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); } } return timeoutType === "SCHEDULE_TO_START" ? { action: "unclaimed", events: [] } : { action: "stale", events: [], turnStatus: null, activeTurnId: session.activeTurnId, }; } const turn = locks.turns.find((row) => row.id === attempt.turnId); const turnStatus = (turn?.status as SessionTurnStatus | undefined) ?? null; const parsedMetadata = readTurnDispatchMetadata(turn?.metadata); if ( !locks.workspace || !turn || turn.accountId !== session.accountId || turn.sessionId !== input.sessionId || attempt.accountId !== session.accountId || attempt.sessionId !== input.sessionId || attempt.turnId !== turn.id || attempt.executionGeneration !== turn.executionGeneration || parsedMetadata.kind === "malformed" || parsedMetadata.attempt === null || effectiveControl.state !== "active" || session.activeTurnId !== turn.id || turnStatus !== "running" || turn.activeAttemptId !== input.attemptId ) { return { action: "stale" as const, events: [] as [], turnStatus, activeTurnId: session.activeTurnId, }; } if (proof) { if ( session.accountId !== proof.accountId || locks.workspace.accountId !== proof.accountId || turn.workspaceId !== proof.workspaceId || attempt.workspaceId !== proof.workspaceId || turn.id !== proof.turnId || attempt.executionGeneration !== proof.executionGeneration || attempt.temporalWorkflowId !== proof.temporalWorkflowId || attempt.temporalWorkflowRunId !== proof.temporalWorkflowRunId || attempt.temporalActivityId !== proof.temporalActivityId || (attempt.state !== "claimed" && attempt.state !== "running") || session.admissionBlock !== null || turn.metadata?.[SANDBOX_SETUP_OUTCOME_UNKNOWN_METADATA_KEY] !== undefined || turn.metadata?.[SANDBOX_SETUP_RECOVERY_EXHAUSTED_METADATA_KEY] !== undefined || turn.metadata?.[SANDBOX_LIFECYCLE_WAIT_METADATA_KEY] !== undefined || effectiveControl.settlement !== null ) return { action: "stale", events: [], turnStatus, activeTurnId: session.activeTurnId }; if (!proof.activitySettled) return { action: "pending", events: [] }; // The same prefix/exact owner locks serialize all writer admissions // and lifecycle/control changes. Recheck BOTH canonical predicates // while the owner is still live; never use a closed-owner inference // exception as physical proof or synthesize an exit/unknown outcome. const [writers] = await tx.execute<{ physical: boolean; inference: boolean; interrupted: boolean; }>(sql` select ${sessionAttemptPendingWritersSql(sql`attempt`, "physical")} as physical, ${sessionAttemptPendingWritersSql(sql`attempt`, "inference")} as inference, exists (select 1 from session_attempt_interruptions interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('pending', 'delivered', 'acknowledged')) as interrupted from session_turn_attempts attempt where attempt.account_id = ${proof.accountId} and attempt.workspace_id = ${proof.workspaceId} and attempt.session_id = ${proof.sessionId} and attempt.id = ${proof.attemptId} and attempt.turn_id = ${proof.turnId} and attempt.execution_generation = ${proof.executionGeneration} `); if (!writers || writers.physical || writers.inference || writers.interrupted) return { action: "pending", events: [] }; } const redispatchMetadata = readWorkerDeathRedispatchMetadata(turn.metadata); if (redispatchMetadata.kind === "malformed") { return { action: "stale" as const, events: [] as [], turnStatus, activeTurnId: session.activeTurnId, }; } if (redispatchMetadata.count >= Number.MAX_SAFE_INTEGER) { return { action: "stale" as const, events: [] as [], turnStatus, activeTurnId: session.activeTurnId, }; } const metadata = { ...(turn.metadata ?? {}) } as Record; const redispatches = redispatchMetadata.count + 1; metadata.workerDeathRedispatches = redispatches; const now = new Date(); await closeSessionTurnAttemptInTransaction(tx as unknown as Database, { id: input.attemptId, accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, executionGeneration: turn.executionGeneration, outcome: redispatches > input.maxRedispatches ? "failed" : "lease_lost_recoverable", closedAt: now, }); let sequence = session.lastSequence; const closedTools = await closePendingSessionToolCallsInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, reason: "worker_death", sequence, now, preserveInterruptionRows: redispatches <= input.maxRedispatches, }, ); sequence = closedTools.sequence; const quiescenceEvents: SessionEvent[] = []; if (proof && !attempt.quiescedAt) { const receipt = await recordSessionAttemptQuiescenceInTransaction( tx, { ...session, lastSequence: sequence }, attempt, now, ); sequence = receipt.sequence; quiescenceEvents.push(receipt); } if (redispatches > input.maxRedispatches) { const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "turn.failed", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", payload: { triggerEventId: turn.triggerEventId, code: "worker_death_redispatch_exhausted", error: `Worker ownership was lost ${redispatches} times while running this turn (${proof ? "settled activity" : "heartbeat timeout"}); giving up after ${input.maxRedispatches} re-dispatches.`, redispatches: input.maxRedispatches, }, occurredAt: now, }, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.status.changed", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", payload: { status: "failed" }, occurredAt: now, }, ], "payload", "payloadCodecVersion", ), ) .returning(); const failedEvent = inserted.find((event) => event.type === "turn.failed"); if (!failedEvent) { throw new Error("Worker-death exhaustion did not persist its terminal event"); } await projectSessionRealtimeDelegationTerminalInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, turnId: turn.id, turnStatus: "failed", terminalEvent: { id: failedEvent.id, type: "turn.failed", payload: sessionEventPayloadRecord( failedEvent.payload, failedEvent.payloadCodecVersion, ), }, now, }); await tx .update(schema.sessionTurns) .set({ status: "failed", activeAttemptId: null, metadata, version: turn.version + 1, finishedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, turn.id), ), ); await enqueueFailedChildOutboxForTurnTx( tx as unknown as Database, workspaceId, session, turn, ); await tx .update(schema.sessions) .set({ status: "failed", activeTurnId: null, lastSequence: sequence, queueVersion: session.queueVersion + 1, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); return { action: "exceeded" as const, turnId: turn.id, redispatches: input.maxRedispatches, events: [...closedTools.events, ...quiescenceEvents, ...inserted.map(mapEvent)], }; } const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( [ { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "turn.recovery.requested", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", payload: { triggerEventId: turn.triggerEventId, reason: proof ? "settled_activity" : "worker_death", redispatches, }, occurredAt: now, }, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "session.status.changed", turnId: turn.id, turnGeneration: turn.executionGeneration, turnAttemptId: input.attemptId, turnAssociation: "current", payload: { status: "recovering" }, occurredAt: now, }, ], "payload", "payloadCodecVersion", ), ) .returning(); const requeuedMetadata = metadataWithoutTurnDispatchAttempt(metadata); await tx .update(schema.sessionTurns) .set({ status: "recovering", triggerEventId: turn.triggerEventId, metadata: requeuedMetadata, activeAttemptId: null, cancelledBy: null, cancelReason: null, version: turn.version + 1, finishedAt: null, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, turn.id), ), ); await tx .update(schema.sessions) .set({ status: "recovering", activeTurnId: turn.id, lastSequence: sequence, updatedAt: now, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, input.sessionId), ), ); // Recovery must survive an observer crash/continue-as-new or lost ACK. // The outbox coalesces any prior debt without acknowledging it here. await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId: input.sessionId, temporalWorkflowId: attempt.temporalWorkflowId, reason: "turn_recovery_requested", }); return { action: "recovering" as const, turnId: turn.id, redispatches, events: [...closedTools.events, ...quiescenceEvents, ...inserted.map(mapEvent)], }; }); }); } export async function getSessionTurn( db: Database, workspaceId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionTurns) .where( and(eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.id, turnId)), ) .limit(1); return row ? mapSessionTurn(row) : null; }); } /** How many of a session's newest finished turns the message-zone lookup reads. */ const LATEST_MESSAGE_TIME_ZONE_TURN_WINDOW = 64; /** * The time zone of the newest finished turn in a session whose message * carried one, among its latest {@link LATEST_MESSAGE_TIME_ZONE_TURN_WINDOW} * finished turns. Walks the newest-finished-first index and stops there, so a * long session costs one bounded index range. */ export async function getLatestSessionMessageTimeZone( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const recent = scopedDb .select({ metadata: schema.sessionTurns.metadata, finishedAt: schema.sessionTurns.finishedAt, position: schema.sessionTurns.position, createdAt: schema.sessionTurns.createdAt, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), isNotNull(schema.sessionTurns.finishedAt), ), ) .orderBy( desc(schema.sessionTurns.finishedAt), desc(schema.sessionTurns.position), desc(schema.sessionTurns.createdAt), ) .limit(LATEST_MESSAGE_TIME_ZONE_TURN_WINDOW) .as("recent"); const rows = await scopedDb .select({ metadata: recent.metadata }) .from(recent) .where(sql`${recent.metadata} ? ${MESSAGE_TIME_ZONE_METADATA_KEY}`) .orderBy(desc(recent.finishedAt), desc(recent.position), desc(recent.createdAt)) .limit(1); return messageTimeZoneFromTurnMetadata(rows[0]?.metadata); }); } /** * Read only the immutable causal human for one exact accepted turn. Public * SessionTurn projections intentionally omit this execution-authority field. */ export async function getSessionTurnInitiatingHumanSubjectId( db: Database, workspaceId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ subjectId: schema.sessionTurns.initiatingHumanSubjectId }) .from(schema.sessionTurns) .where( and(eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.id, turnId)), ) .limit(1); return row?.subjectId ?? null; }); } /** * Resolve the exact currently executable turn/attempt from authoritative * pointers in one query. This avoids treating a stale session preview as proof * that no attempt exists during an atomic claim transition. */ export async function getActiveSessionTurnForExecution( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ turn: schema.sessionTurns }) .from(schema.sessions) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessions.workspaceId), eq(schema.sessionTurns.id, schema.sessions.activeTurnId), ), ) .innerJoin( schema.sessionTurnAttempts, and( eq(schema.sessionTurnAttempts.workspaceId, schema.sessionTurns.workspaceId), eq(schema.sessionTurnAttempts.id, schema.sessionTurns.activeAttemptId), ), ) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurnAttempts.sessionId, sessionId), eq(schema.sessionTurnAttempts.turnId, schema.sessionTurns.id), inArray(schema.sessionTurnAttempts.state, ["claimed", "running"]), inArray(schema.sessionTurns.status, ["running", "recovering", "waiting_capacity"]), sql`not exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = ${workspaceId} and interruption.attempt_id = ${schema.sessionTurnAttempts.id} and interruption.state in ('pending', 'delivered', 'acknowledged') )`, ), ) .limit(1); if (!row) return null; const linked = await getExternalLinkTurnAuthorization( scopedDb, { accountId: row.turn.accountId, workspaceId, }, row.turn.id, ); if (linked && !linked.authorized) return null; await goalSnapshotForAcceptedTurnInTransaction(scopedDb, row.turn); return mapSessionTurnForExecution(row.turn); }); } export async function getSessionTurnForAttempt( db: Database, workspaceId: string, sessionId: string, attemptId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const row = await getLiveSessionAttemptTurn(scopedDb, workspaceId, sessionId, attemptId); if (!row) return null; await goalSnapshotForAcceptedTurnInTransaction(scopedDb, row); return mapSessionTurnForExecution(row); }); } /** * Return the newest turn that reached agent execution for a session. A claimed * turn's `started_at` is set before worker admission, so it is not sufficient * evidence that the turn's model/reasoning policy was actually used. The * durable `turn.started` event is emitted only after admission succeeds and is * therefore actual causal execution evidence. It is not the effective defaults: * those also respect explicit model-setting boundaries through the shared * session read projection. Preflight-rejected turns are not execution evidence. */ export async function getLatestStartedSessionTurn( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const row = await latestStartedSessionTurnRow(scopedDb, workspaceId, sessionId); if (!row) return null; const [turn] = await withTurnUsage(scopedDb, workspaceId, [mapSessionTurn(row)]); return turn ?? null; }); } /** * Freeze the effective policy an internal scheduled update would inherit from * an existing session at occurrence admission. The later claim consumes this * exact policy instead of re-reading whichever turn happened to start most * recently in the meantime. */ export async function getScheduledTargetSessionExecution( db: Database, workspaceId: string, sessionId: string, authoritySubjectId?: string | null, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { if (authoritySubjectId) await setSubjectRlsContext(scopedDb, authoritySubjectId); const [session] = await scopedDb .select({ id: schema.sessions.id, accountId: schema.sessions.accountId, visibility: schema.sessions.visibility, authorityEpoch: schema.sessions.authorityEpoch, model: schema.sessions.model, reasoningEffort: schema.sessions.reasoningEffort, latencyMode: schema.sessions.latencyMode, metadata: schema.sessions.metadata, tools: schema.sessions.tools, sandboxBackend: schema.sessions.sandboxBackend, sandboxOs: schema.sessions.sandboxOs, firstPartyMcpTools: schema.sessions.firstPartyMcpTools, firstPartyMcpPermissions: schema.sessions.firstPartyMcpPermissions, toolPolicy: schema.sessions.toolPolicy, toolPolicyVersion: schema.sessions.toolPolicyVersion, rigId: schema.sessions.rigId, rigVersionId: schema.sessions.rigVersionId, maxNestedAgentDepthOverride: schema.sessions.maxNestedAgentDepthOverride, effectiveMaxNestedAgentDepth: schema.sessions.effectiveMaxNestedAgentDepth, }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .for("share") .limit(1); if (!session) throw new Error(`Session not found: ${sessionId}`); const targetMcpServers = await scopedDb .select({ id: schema.sessionMcpServers.serverId }) .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionMcpServers.serverId)); const latestStarted = await latestStartedSessionTurnRow(scopedDb, workspaceId, sessionId); const [effectivePolicy] = await withEffectiveSessionPolicy(scopedDb, workspaceId, [session]); const rigMetadata = session.rigId && session.rigVersionId ? await getScheduledScopedRigVersionMetadata( scopedDb, { accountId: session.accountId, workspaceId, subjectId: authoritySubjectId ?? "scheduled-task", }, session.rigId, session.rigVersionId, ) : null; if (session.rigId && session.rigVersionId && !rigMetadata) { throw new Error("scheduled target session sandbox environment version is unavailable"); } return { sessionId: session.id, visibility: session.visibility as "user_private" | "workspace_shared", authorityEpoch: session.authorityEpoch, model: effectivePolicy!.model, reasoningEffort: reasoningEffortForMetadata( { reasoningEffort: effectivePolicy!.reasoningEffort }, session.reasoningEffort as ReasoningEffort, ), latencyMode: latencyModeForMetadata( { latencyMode: effectivePolicy!.latencyMode }, session.latencyMode as LatencyMode, ), // A turn stores omitted `tools` as the non-null database default `[]`. // Only the companion marker distinguishes that inherited state from an // explicit empty override, so never let the array alone narrow a later // scheduled occurrence. tools: (latestStarted?.toolsProvided ? latestStarted.tools : session.tools) as ToolRef[], sandboxBackend: (latestStarted?.sandboxBackend ?? session.sandboxBackend) as SandboxBackend, sandboxOs: (latestStarted?.sandboxOs ?? session.sandboxOs) as SandboxOs, firstPartyMcpTools: session.firstPartyMcpTools as FirstPartyMcpToolName[], firstPartyMcpPermissions: (session.firstPartyMcpPermissions as Permission[] | null) ?? null, toolPolicy: session.toolPolicy, mcpServerIds: targetMcpServers.map((server) => server.id), effectiveMcpServerIds: targetMcpServers.map((server) => server.id), toolPolicyVersion: session.toolPolicyVersion, // Retired Variable Set fields stay in the accepted-snapshot schema until // the follow-up that drops the columns; new snapshots record none. variableSets: [], variableSetId: null, variableSetGeneration: null, rigId: session.rigId ?? null, rigVersionId: session.rigVersionId ?? null, rigDefaultVariableSets: [], maxNestedAgentDepthOverride: session.maxNestedAgentDepthOverride ?? null, effectiveMaxNestedAgentDepth: session.effectiveMaxNestedAgentDepth, }; }); } export async function listSessionTurns( db: Database, workspaceId: string, sessionId: string, limit = 100, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), ), ) .orderBy(asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt)) .limit(limit); return await withTurnUsage(scopedDb, workspaceId, rows.map(mapSessionTurn)); }); } export async function listPendingSessionTurns( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), inArray(schema.sessionTurns.status, ["queued", "running", "requires_action"]), ), ) .orderBy(asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt)); return rows.map(mapSessionTurn); }); } /** Compact MCP monitoring never needs prompt bodies or inbox attachment planning. * Keep the same control lock and stopping proof as the full queue projection. */ export async function getSessionQueueMonitoringSummary( db: Database, workspaceId: string, sessionId: string, ): Promise<(SessionMcpQueueSummary & Pick) | null> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const effectiveControl = await evaluateSessionControl(scopedDb, workspaceId, sessionId, { lock: "share", }); const [session] = await scopedDb .select({ id: schema.sessions.id }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!session) return null; const rows = await scopedDb .select({ promptRouting: schema.sessionTurns.promptRouting, metadata: schema.sessionTurns.metadata, }) .from(schema.sessionTurns) .where(sessionQueueTurnsPredicate(workspaceId, sessionId)); const [pending] = await scopedDb .select({ count: sql`count(*)` }) .from(schema.sessionSystemUpdates) .where(sessionQueuePendingInputsPredicate(workspaceId, sessionId)); return { effectiveControl: serializeEffectiveSessionControl(effectiveControl), queuedTurns: rows.filter( (row) => row.promptRouting === null || row.promptRouting === "queued_for_execution", ).length, pendingInputs: Number(pending!.count), stoppingPreviousAttempt: await sessionQueueStoppingPreviousAttempt( scopedDb, workspaceId, sessionId, rows.map((row) => row.metadata), ), }; }); } function sessionQueueTurnsPredicate(workspaceId: string, sessionId: string) { return and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.status, "queued"), inArray(schema.sessionTurns.source, ["user", "api"]), ); } function sessionQueuePendingInputsPredicate(workspaceId: string, sessionId: string) { return and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ); } async function sessionQueueStoppingPreviousAttempt( db: Database, workspaceId: string, sessionId: string, queuedMetadata: Record[], ): Promise { const latestInterruption = await latestSessionAttemptInterruption(db, workspaceId, sessionId); const predecessorIds = queuedMetadata .map(queuedSteerReplacementAttemptId) .filter((attemptId): attemptId is string => attemptId !== null); return ( (latestInterruption !== null && latestInterruption.interruptionState !== "rejected_stale" && latestInterruption.quiescedAt === null) || (await queuedSteerHasUnquiescedPredecessor(db, workspaceId, sessionId, predecessorIds)) ); } export async function getSessionQueueSnapshot( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const effectiveControl = await evaluateSessionControl(scopedDb, workspaceId, sessionId, { lock: "share", }); const [session] = await scopedDb .select() .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); if (!session) return null; const activePersonalConnections = session.activeTurnId ? ( await personalConnectionDelegationsForTurnInTransaction( scopedDb, workspaceId, sessionId, session.activeTurnId, ) ).map(({ serverId, providerDomain }) => ({ serverId, providerDomain })) : []; const rows = await scopedDb .select() .from(schema.sessionTurns) .where(sessionQueueTurnsPredicate(workspaceId, sessionId)) .orderBy(asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt)); const pendingInputs = await scopedDb .select() .from(schema.sessionSystemUpdates) .where(sessionQueuePendingInputsPredicate(workspaceId, sessionId)) .orderBy( sql`case when ${schema.sessionSystemUpdates.kind} = 'agent_steer_instruction' then 0 else 1 end`, sql`case when ${schema.sessionSystemUpdates.kind} = 'agent_steer_instruction' then ${schema.sessionSystemUpdates.createdAt} end desc`, sql`case when ${schema.sessionSystemUpdates.kind} = 'agent_steer_instruction' then ${schema.sessionSystemUpdates.id} end desc`, sql`case when ${passiveCommandNoticeSql()} then 2 when ${schema.sessionSystemUpdates.kind} = 'background_command_result' then 1 else 0 end`, asc(schema.sessionSystemUpdates.createdAt), asc(schema.sessionSystemUpdates.id), ); // `status=queued` is the physical worker-claim queue. Only an explicit // queued_for_execution admission belongs in the operator-visible queue. // Null remains visible during rolling deploys and for legacy rows so a // prompt written by an older process can never disappear from the UI. const physicalItems = rows.map(mapSessionTurn); const items = rows .filter((row) => row.promptRouting === null || row.promptRouting === "queued_for_execution") .map(mapSessionTurn); const stoppingPreviousAttempt = await sessionQueueStoppingPreviousAttempt( scopedDb, workspaceId, sessionId, physicalItems.map((turn) => turn.metadata), ); const hasPendingAgentSteer = pendingInputs.some( (update) => update.kind === "agent_steer_instruction", ); const attachmentTurn = hasPendingAgentSteer ? physicalItems.find((turn) => turn.metadata.delivery === "steer") : physicalItems[0]; const attachmentRow = attachmentTurn ? rows.find((row) => row.id === attachmentTurn.id) : undefined; let nextInputBatch: typeof pendingInputs = []; if (attachmentRow && !isSessionRealtimeDelegationTurnMetadata(attachmentRow.metadata)) { const window = pendingInboxReadWindow(pendingInputs, true); const runIds = [...new Set(window.flatMap((update) => update.scheduledTaskRunId ?? []))]; const runs = runIds.length === 0 ? [] : await scopedDb .select({ id: schema.scheduledTaskRuns.id, status: schema.scheduledTaskRuns.status, error: schema.scheduledTaskRuns.error, acceptedExecutionSnapshot: schema.scheduledTaskRuns.acceptedExecutionSnapshot, }) .from(schema.scheduledTaskRuns) .where( and( eq(schema.scheduledTaskRuns.accountId, session.accountId), eq(schema.scheduledTaskRuns.workspaceId, workspaceId), eq(schema.scheduledTaskRuns.sessionId, sessionId), inArray(schema.scheduledTaskRuns.id, runIds), ), ); const runsById = new Map(runs.map((run) => [run.id, run])); // Preview only reads durable rejection facts. Live authority and worker // admission are revalidated under claim's locks and can still change. const candidates = window.filter( (update) => recognizedInboxPayload(update) && (!update.scheduledTaskRunId || scheduledRunPreclaimDenial(runsById.get(update.scheduledTaskRunId)) === null), ); nextInputBatch = (await planInboxBatch(scopedDb, session, candidates, attachmentRow)).updates; } return { version: session.queueVersion, effectiveControl: serializeEffectiveSessionControl(effectiveControl), activePersonalConnections, stoppingPreviousAttempt, items, pendingInputs: pendingInputs.map((update) => { // Queue labels do not expose the payload. A malformed payload remains // visible here until claim records its failure, without breaking reads. return { id: update.id, sessionId: update.sessionId, kind: update.kind as SessionSystemUpdateKind, classification: update.classification as SystemUpdateClassification, sourceId: boundedInternalUpdateEventText(update.sourceId, 256).text, summary: boundedInternalUpdateEventText( fromPostgresLosslessText(update.summary, update.summaryCodecVersion), 512, ).text, createdAt: update.createdAt.toISOString(), }; }), pendingInputAttachment: attachmentTurn && nextInputBatch.length > 0 ? { turnId: attachmentTurn.id, inputIds: nextInputBatch.map((update) => update.id), } : null, }; }); } function queuedSteerReplacementAttemptId(metadata: Record): string | null { if (metadata.delivery !== "steer") return null; const attemptId = metadata.replacedAttemptId; const interruptionCount = metadata.interruptionCount; if (attemptId === null && interruptionCount === 0) return null; if ( typeof attemptId === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(attemptId) && typeof interruptionCount === "number" && Number.isSafeInteger(interruptionCount) && interruptionCount > 0 ) { return attemptId; } // The interruption ledger is authoritative. Historical or malformed display // metadata must not make the read-only queue projection fail. return null; } type ChildOutboxSession = Pick< typeof schema.sessions.$inferSelect, "id" | "accountId" | "parentSessionId" | "parentTurnId" >; type ChildLifecycleOutboxPayload = Extract< SessionSystemUpdatePayload, { type: ChildLifecycleSystemUpdateKind } >; type ChildLifecycleNoticeInput = { [Kind in ChildLifecycleSystemUpdateKind]: { kind: Kind; payload: Extract; }; }[ChildLifecycleSystemUpdateKind] & { dedupeKey: string; classification: SystemUpdateClassification; summary: string; lineage?: Record; /** A child's question routed past a parent that cannot act (childRequiresActionRouteTx). */ route?: ChildRequiresActionRoute; }; /** * The one child -> parent outbox writer. The caller must already hold the * child-lifecycle lock prefix (control FOR SHARE -> workspace FOR KEY SHARE -> * UUID-ordered child + parent sessions FOR NO KEY UPDATE -> exact turn/attempt) * or, for the generic-prefix human-input/approval producers, the UUID-ordered * child + parent session rows. The insert is dedupe-keyed and idempotent; a * session without a parent produces nothing. Returns whether a row was added. */ async function enqueueChildLifecycleNoticeOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: ChildLifecycleNoticeInput, ): Promise { if (!session.parentSessionId) return false; const route = input.route ?? null; const targetSessionId = route?.targetSessionId ?? session.parentSessionId; // An escalated notice carries the target's own causal turn: the one that // started the branch the child is on. const authority = await parentOutboxAuthorityTx(tx, workspaceId, { ...(route?.via ?? session), parentSessionId: targetSessionId, }); const routeLineage = route && route.targetSessionId !== session.parentSessionId ? { childSessionId: session.id, ...(route.escalatedFromSessionId ? { escalatedFromSessionId: route.escalatedFromSessionId } : {}), } : {}; // Freeze complete content at notice creation, never at parent claim time. // Oversized evidence is omitted, not truncated and then called consumed. // Bound index candidates before payload filters, and prefer the newest complete // result within the total budget. Explicit reads handle omitted evidence. // A terminal result that carries the child's final answer needs no second // copy: an untruncated answer is itself the consumption evidence. const carriesFinalAnswer = input.kind === "child_terminal_result" && input.payload.finalAnswer !== undefined; const candidates = carriesFinalAnswer ? [] : await rawRows<{ sequence: number; type: string; payload: unknown; payloadCodecVersion: number | null; }>( tx, childLifecycleEvidenceCandidatesSql(sql`${workspaceId}::uuid`, sql`${session.id}::uuid`), ); const noticePayload = carriesFinalAnswer ? input.payload : { ...input.payload, childEventEvidence: boundedChildLifecycleEvidence(candidates) }; const inserted = await tx .insert(schema.sessionSystemUpdateOutbox) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId, sourceSessionId: session.id, targetSessionId, dedupeKey: input.dedupeKey, kind: input.kind, classification: input.classification, sourceId: session.id, summary: input.summary, payload: noticePayload, lineage: { ...authority.lineage, ...routeLineage, ...(input.lineage ?? {}) }, personalConnectionDelegations: authority.personalConnectionDelegations, mcpAccountBindings: authority.mcpAccountBindings, xaiProviderAccountAuthoritySnapshot: authority.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: authority.claudeProviderAccountAuthoritySnapshot, subscriptionAuthority: authority.subscriptionAuthority, }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionSystemUpdateOutbox.workspaceId, schema.sessionSystemUpdateOutbox.dedupeKey, ], }) .returning({ id: schema.sessionSystemUpdateOutbox.id }); await copySubscriptionAuthorityCompatInTransaction( tx, inserted.map((row) => ({ kind: "session_system_update_outbox" as const, workspaceId, id: row.id, })), ); return inserted.length > 0; } async function enqueueFailedChildOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: { turnId: string | null; dedupeKey: string }, ): Promise { if (!session.parentSessionId) return; await enqueueChildLifecycleNoticeOutboxTx(tx, workspaceId, session, { dedupeKey: input.dedupeKey, kind: "child_terminal_result", classification: "failure", summary: "Child session failed; inspect the durable child timeline.", payload: { type: "child_terminal_result", childSessionId: session.id, status: "failed", ...(input.turnId ? { turnId: input.turnId } : {}), }, ...(input.turnId ? { lineage: { turnId: input.turnId } } : {}), }); } /** * Child-lifecycle notice producers below. Every one of them is gated by the * process-global rollout flag, takes the child-lifecycle lock prefix (the * parent session row is locked with the child), and only inserts the durable * outbox row; the worker delivers it to the parent. */ async function enqueueChildRequiresActionOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: { turnId: string; turnGeneration: number; humanInputRequests: Parameters[0]["humanInputRequests"]; /** Requests this freeze created; only these can be held. */ newHumanInputRequestIds: readonly string[]; pendingApprovals: readonly unknown[]; }, ): Promise { if (!session.parentSessionId || !childLifecycleNoticesEnabled()) return false; const payload = buildChildRequiresActionPayload({ childSessionId: session.id, childTurnId: input.turnId, childTurnGeneration: input.turnGeneration, humanInputRequests: input.humanInputRequests, pendingApprovals: input.pendingApprovals, }); if (payload.requests.length === 0 && !payload.truncated) return false; // A parent that cannot act (failed, or without session tools) does not // hold its child's question: the nearest ancestor that can gets it. const route = await childRequiresActionRouteTx(tx, workspaceId, { ...session, parentSessionId: session.parentSessionId, }); const summary = childRequiresActionSummary(session.id, payload); const dedupeKey = childRequiresActionDedupeKey({ childSessionId: session.id, turnId: input.turnId, turnGeneration: input.turnGeneration, }); const enqueued = await enqueueChildLifecycleNoticeOutboxTx(tx, workspaceId, session, { dedupeKey, kind: "child_requires_action", classification: "action_required", summary: route.escalatedFromSessionId ? `${summary}\nIts parent session ${route.escalatedFromSessionId} can't act on it, so it came to you; answer it the same way.` : summary, payload, lineage: { turnId: input.turnId }, route, }); // The agent gets the whole pause or none of it. const hold = enqueued && route.targetCanAct && !payload.truncated && payload.requests.length === input.humanInputRequests.length && input.humanInputRequests.every((request) => request.questions.every((question) => !humanInputQuestionIsPersonOnly(question)), ); if (hold && input.newHumanInputRequestIds.length > 0) { // Before the pause's request events: the inbox and push triggers skip a // held question, and release it when the agent no longer has it (1553). await tx .update(schema.sessionHumanInputRequests) .set({ heldForAgent: true }) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, session.id), inArray(schema.sessionHumanInputRequests.id, [...input.newHumanInputRequestIds]), ), ); } return enqueued; } async function enqueueChildRequiresActionResolvedOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: { turnId: string; turnGeneration: number; requestId: string | null; approvalId: string | null; outcome: ChildRequiresActionResolvedOutcome; respondedByKind: ChildRequiresActionRespondedByKind; }, ): Promise { if (!session.parentSessionId || !childLifecycleNoticesEnabled()) return false; const payload = { type: "child_requires_action_resolved" as const, childSessionId: session.id, childTurnId: input.turnId, childTurnGeneration: input.turnGeneration, requestId: input.requestId, approvalId: input.approvalId, outcome: input.outcome, respondedByKind: input.respondedByKind, }; // The resolution follows its question, so it supersedes the notice where it landed. const recordedTarget = await recordedChildNoticeTargetTx( tx, workspaceId, childRequiresActionDedupeKey({ childSessionId: session.id, turnId: input.turnId, turnGeneration: input.turnGeneration, }), ); const route = recordedTarget && recordedTarget !== session.parentSessionId ? await childRequiresActionRouteTx( tx, workspaceId, { ...session, parentSessionId: session.parentSessionId }, recordedTarget, ) : undefined; return await enqueueChildLifecycleNoticeOutboxTx(tx, workspaceId, session, { dedupeKey: childRequiresActionResolvedDedupeKey({ childSessionId: session.id, turnId: input.turnId, turnGeneration: input.turnGeneration, requestId: input.requestId, approvalId: input.approvalId, }), kind: "child_requires_action_resolved", classification: "info", summary: childRequiresActionResolvedSummary(session.id, payload), payload, lineage: { turnId: input.turnId }, ...(route ? { route } : {}), }); } /** Derive the bounded responder kind of a human-input/approval resolution. */ export function childRequiresActionRespondedByKindFor( respondedBy: string, explicit?: ChildRequiresActionRespondedByKind, ): ChildRequiresActionRespondedByKind { if (explicit) return explicit; if (respondedBy.startsWith("agent_attempt:")) return "agent_attempt"; if (respondedBy.startsWith("system:")) return "system"; return "human"; } async function enqueueChildWaitingCapacityOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: { turnId: string; waiterId: string; provider: "codex" | "xai" | "claude"; nextCheckAt: Date | null; resetsAt: Date | null; explanation?: string; restatement?: { restatedResetsAt: string | null; restatedReasonSequence?: number }; }, ): Promise { if (!session.parentSessionId || !childLifecycleNoticesEnabled()) return false; const payload = { type: "child_waiting_capacity" as const, childSessionId: session.id, childTurnId: input.turnId, provider: input.provider, nextCheckAt: input.nextCheckAt?.toISOString() ?? null, resetsAt: input.resetsAt?.toISOString() ?? null, }; return await enqueueChildLifecycleNoticeOutboxTx(tx, workspaceId, session, { dedupeKey: childWaitingCapacityDedupeKey({ childSessionId: session.id, waiterId: input.waiterId, ...input.restatement, }), kind: "child_waiting_capacity", classification: "info", summary: childWaitingCapacitySummary(session.id, payload, input.explanation), payload, lineage: { turnId: input.turnId }, }); } async function enqueueChildProgressOutboxTx( tx: Database, workspaceId: string, session: ChildOutboxSession, input: { goalId: string; objectiveRevision: number; operationId: string; progressNote: string; }, ): Promise { if (!session.parentSessionId || !childLifecycleNoticesEnabled()) return false; const payload = { type: "child_progress" as const, childSessionId: session.id, goalId: input.goalId, objectiveRevision: input.objectiveRevision, operationId: input.operationId, progressNote: boundedChildProgressNote(input.progressNote), }; return await enqueueChildLifecycleNoticeOutboxTx(tx, workspaceId, session, { dedupeKey: childProgressDedupeKey({ childSessionId: session.id, receiptId: input.operationId, }), kind: "child_progress", classification: "info", summary: childProgressSummary(session.id, payload), payload, }); } /** * Read the child's parent id without locking, so a generic-prefix writer can * include the parent in its one UUID-ordered session lock call. The helper that * later inserts the outbox row re-reads the locked child row and refuses a * changed parent, exactly like the child-lifecycle lock prefix does. */ async function sessionIdsWithParentTx( tx: Database, workspaceId: string, sessionId: string, ): Promise { if (!childLifecycleNoticesEnabled()) return [sessionId]; const [preview] = await tx .select({ parentSessionId: schema.sessions.parentSessionId }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return preview?.parentSessionId ? [sessionId, preview.parentSessionId] : [sessionId]; } async function enqueueFailedChildOutboxForTurnTx( tx: Database, workspaceId: string, session: Pick< typeof schema.sessions.$inferSelect, "id" | "accountId" | "parentSessionId" | "parentTurnId" >, turn: Pick, ): Promise { if (turn.accountId !== session.accountId || turn.sessionId !== session.id) { throw new SessionControlInvariantError( `Failed child turn ${turn.id} lost session ${session.id} ownership`, ); } await enqueueFailedChildOutboxTx(tx, workspaceId, session, { turnId: turn.id, dedupeKey: childFailedTurnDedupeKey(turn.sessionId, turn.id), }); } /** * Dedupe key of the notice a child's failed turn sends its parent. The SQL twin * below must build the same string: sessionFailureHandledByParentSql relies on * it to tell the failed turn itself from later work. */ export function childFailedTurnDedupeKey(childSessionId: string, turnId: string): string { return `child-completion:${childSessionId}:turn:${turnId}`; } /** SQL form of childFailedTurnDedupeKey; keep the two in step. */ function childFailedTurnDedupeKeySql(childSessionId: SQL, turnId: SQL): SQL { return sql`('child-completion:' || (${childSessionId})::text || ':turn:' || (${turnId})::text)`; } /** SQL twin of childRequiresActionDedupeKey. */ function childRequiresActionDedupeKeySql( childSessionId: SQL, turnId: SQL, turnGeneration: SQL, ): SQL { return sql`('child-requires-action:' || (${childSessionId})::text || ':' || (${turnId})::text || ':' || (${turnGeneration})::text)`; } async function enqueueFailedChildOutboxWithoutTurnTx( tx: Database, workspaceId: string, session: Pick< typeof schema.sessions.$inferSelect, "id" | "accountId" | "parentSessionId" | "parentTurnId" >, terminalSequence: number, ): Promise { await enqueueFailedChildOutboxTx(tx, workspaceId, session, { turnId: null, dedupeKey: `child-completion:${session.id}:pre-claim:${terminalSequence}`, }); } function parseChildLifecycleOutboxPayload( input: unknown, kind: string, ): { kind: ChildLifecycleSystemUpdateKind; payload: ChildLifecycleOutboxPayload; } { if (!isChildLifecycleSystemUpdateKind(kind)) { throw new Error(`System-update outbox contains retired kind ${kind}`); } const payload = SessionSystemUpdatePayload.parse(input); if (payload.type !== kind) { throw new Error(`Child-lifecycle outbox ${kind} contains ${payload.type} payload`); } return { kind, payload: payload as ChildLifecycleOutboxPayload }; } /** The exact kind/payload pair of one child-lifecycle outbox row, correlated for typed re-insert. */ export type SessionSystemUpdateOutboxKindPayload = { [Kind in ChildLifecycleSystemUpdateKind]: { kind: Kind; payload: Extract; }; }[ChildLifecycleSystemUpdateKind]; export type SessionSystemUpdateOutboxDelivery = { id: string; status: "pending" | "delivered"; accountId: string; workspaceId: string; sourceSessionId: string; targetSessionId: string; dedupeKey: string; kind: ChildLifecycleSystemUpdateKind; classification: SystemUpdateClassification; sourceId: string; summary: string; payload: ChildLifecycleOutboxPayload; lineage: Record; personalConnectionDelegations: McpPersonalConnectionDelegation[]; mcpAccountBindings: McpConnectionAccountBinding[] | null; xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1; claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1; /** Codex v2 (M3 PR 3b): the exact spawning parent turn's frozen value. */ subscriptionAuthority: SubscriptionPersonalAuthorityV2 | null; }; /** Narrow an outbox row back to its correlated typed kind/payload input variant. */ export function sessionSystemUpdateOutboxKindPayload( outbox: Pick, ): SessionSystemUpdateOutboxKindPayload { if (outbox.payload.type !== outbox.kind) { throw new Error(`Outbox ${outbox.kind} carries a ${outbox.payload.type} payload`); } return { kind: outbox.kind, payload: outbox.payload, } as SessionSystemUpdateOutboxKindPayload; } function mapSystemUpdateOutboxRow(row: { id: string; account_id: string; workspace_id: string; source_session_id: string; target_session_id: string; dedupe_key: string; kind: string; classification: string; source_id: string; summary: string; summary_codec_version: number | null; payload: Record; payload_codec_version: number | null; lineage: Record; personal_connection_delegations: unknown; mcp_account_bindings: unknown; xai_provider_account_authority_snapshot: unknown; claude_provider_account_authority_snapshot: unknown; /** Absent from the claim routine's fixed columns; filled in after the claim. */ subscription_authority?: unknown; }): SessionSystemUpdateOutboxDelivery { const typed = parseChildLifecycleOutboxPayload( fromPostgresLosslessJson(row.payload, row.payload_codec_version), row.kind, ); return { id: row.id, status: "pending", accountId: row.account_id, workspaceId: row.workspace_id, sourceSessionId: row.source_session_id, targetSessionId: row.target_session_id, dedupeKey: row.dedupe_key, kind: typed.kind, classification: row.classification as SystemUpdateClassification, sourceId: row.source_id, summary: fromPostgresLosslessText(row.summary, row.summary_codec_version), payload: typed.payload, lineage: row.lineage, personalConnectionDelegations: parsedPersonalConnectionDelegations( row.personal_connection_delegations, `session_system_update_outbox:${row.workspace_id}:${row.id}`, ), mcpAccountBindings: parseAcceptedMcpAccountBindings(row.mcp_account_bindings), xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1.parse( row.xai_provider_account_authority_snapshot, ), claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1.parse( row.claude_provider_account_authority_snapshot, ), subscriptionAuthority: frozenSubscriptionAuthorityV2(row.subscription_authority), }; } /** A carrier's frozen Codex v2 value (M3 PR 3b), or null when it froze none. */ function frozenSubscriptionAuthorityV2(value: unknown): SubscriptionPersonalAuthorityV2 | null { return value === null || value === undefined ? null : SubscriptionPersonalAuthorityV2.parse(value); } /** * The Codex v2 value of a child's exact spawning parent turn (M3 PR 3b): a * child-lifecycle notice carries it like the v1 pools, never recomputed. */ async function childNoticeParentSubscriptionAuthorityTx( tx: Database, workspaceId: string, childSessionId: string, ): Promise { const [child] = await tx .select({ parentSessionId: schema.sessions.parentSessionId, parentTurnId: schema.sessions.parentTurnId, }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, childSessionId)), ) .limit(1); if (!child?.parentSessionId || !child.parentTurnId) return null; const [parentTurn] = await tx .select({ subscriptionAuthority: schema.sessionTurns.subscriptionAuthority }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, child.parentSessionId), eq(schema.sessionTurns.id, child.parentTurnId), ), ) .limit(1); return frozenSubscriptionAuthorityV2(parentTurn?.subscriptionAuthority); } /** * Read the exact durable parent-update row created by terminal turn settlement. * Failure delivery must never upsert this row: settlement owns its payload and * turn provenance, while the activity layer only delivers the committed fact. */ export async function getSessionSystemUpdateOutboxByDedupeKey( db: Database, input: { accountId: string; workspaceId: string; dedupeKey: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionSystemUpdateOutbox) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdateOutbox.dedupeKey, input.dedupeKey), ), ) .limit(1); if (!row) return null; const typed = parseChildLifecycleOutboxPayload( fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), row.kind, ); return { id: row.id, status: row.status as "pending" | "delivered", accountId: row.accountId, workspaceId: row.workspaceId, sourceSessionId: row.sourceSessionId, targetSessionId: row.targetSessionId, dedupeKey: row.dedupeKey, kind: typed.kind, classification: row.classification as SystemUpdateClassification, sourceId: row.sourceId, summary: fromPostgresLosslessText(row.summary, row.summaryCodecVersion), payload: typed.payload, lineage: row.lineage, personalConnectionDelegations: parsedPersonalConnectionDelegations( row.personalConnectionDelegations, `session_system_update_outbox:${row.workspaceId}:${row.id}`, ), mcpAccountBindings: parseAcceptedMcpAccountBindings(row.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1.parse( row.xaiProviderAccountAuthoritySnapshot, ), claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1.parse( row.claudeProviderAccountAuthoritySnapshot, ), subscriptionAuthority: frozenSubscriptionAuthorityV2(row.subscriptionAuthority), }; }, ); } export async function claimPendingSessionSystemUpdateOutbox( db: Database, limit = 100, ): Promise { const rows = await rawRows<{ id: string; account_id: string; workspace_id: string; source_session_id: string; target_session_id: string; dedupe_key: string; kind: string; classification: string; source_id: string; summary: string; summary_codec_version: number | null; payload: Record; payload_codec_version: number | null; lineage: Record; personal_connection_delegations: unknown; mcp_account_bindings: unknown; xai_provider_account_authority_snapshot: unknown; claude_provider_account_authority_snapshot: unknown; }>(db, sql`select * from opengeni_private.claim_session_system_update_outbox_v2(${limit})`); // One unparseable row (for example a kind this image does not understand, or // a payload that no longer matches its schema) must not poison the whole // batch: dead-letter exactly that row with a bounded error and keep // delivering the rest. The row stays inspectable as `failed` + `last_error`. const deliveries: SessionSystemUpdateOutboxDelivery[] = []; for (const row of rows) { try { deliveries.push(mapSystemUpdateOutboxRow(row)); } catch (error) { const message = `unrecognized outbox row: ${error instanceof Error ? error.message : String(error)}`; await withRlsContext( db, { accountId: row.account_id, workspaceId: row.workspace_id }, async (scopedDb) => { await scopedDb .update(schema.sessionSystemUpdateOutbox) .set({ status: "failed", lastError: message.slice(0, 500), updatedAt: new Date(), }) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, row.workspace_id), eq(schema.sessionSystemUpdateOutbox.id, row.id), eq(schema.sessionSystemUpdateOutbox.status, "pending"), ), ); }, ); } } // The claim routine's fixed columns predate the Codex v2 slot (M3 PR 3b): // read the frozen values of the claimed rows, one query per workspace. const byWorkspace = new Map(); for (const delivery of deliveries) { const group = byWorkspace.get(delivery.workspaceId) ?? []; group.push(delivery); byWorkspace.set(delivery.workspaceId, group); } for (const [workspaceId, group] of byWorkspace) { const values = await withRlsContext( db, { accountId: group[0]!.accountId, workspaceId }, async (scopedDb) => await scopedDb .select({ id: schema.sessionSystemUpdateOutbox.id, subscriptionAuthority: schema.sessionSystemUpdateOutbox.subscriptionAuthority, }) .from(schema.sessionSystemUpdateOutbox) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, workspaceId), inArray( schema.sessionSystemUpdateOutbox.id, group.map((delivery) => delivery.id), ), ), ), ); const frozen = new Map(values.map((value) => [value.id, value.subscriptionAuthority])); for (const delivery of group) { delivery.subscriptionAuthority = frozenSubscriptionAuthorityV2(frozen.get(delivery.id)); } } return deliveries; } export type AutomaticSessionTitleFanoutDelivery = { outboxId: string; event: SessionEvent; }; /** * Claim migration-created title events for deployment-wide NATS fanout. The * function is SECURITY DEFINER because one control worker drains obligations * across workspaces; callers receive only the exact already-public event * projection, never arbitrary session rows. */ export async function claimAutomaticSessionTitleFanout( db: Database, limit = 100, ): Promise { const rows = await rawRows<{ outbox_id: string; workspace_id: string; session_id: string; event_id: string; sequence: number; type: string; payload: unknown; payload_codec_version: number | null; occurred_at: Date | string; client_event_id: string | null; turn_id: string | null; turn_generation: number | null; turn_attempt_id: string | null; turn_association: string | null; duplicate_of_event_id: string | null; duplicate_reason: string | null; }>(db, sql`select * from opengeni_private.claim_automatic_session_title_fanout_v1(${limit})`); return rows.map((row) => ({ outboxId: row.outbox_id, event: { id: row.event_id, workspaceId: row.workspace_id, sessionId: row.session_id, sequence: row.sequence, type: row.type as SessionEventType, payload: fromPostgresLosslessJson(row.payload, row.payload_codec_version), occurredAt: row.occurred_at instanceof Date ? row.occurred_at.toISOString() : new Date(row.occurred_at).toISOString(), clientEventId: row.client_event_id, turnId: row.turn_id, turnGeneration: row.turn_generation, turnAttemptId: row.turn_attempt_id, turnAssociation: row.turn_association as SessionEvent["turnAssociation"], duplicateOfEventId: row.duplicate_of_event_id, duplicateReason: row.duplicate_reason, }, })); } export async function markAutomaticSessionTitleFanoutDelivered( db: Database, delivery: AutomaticSessionTitleFanoutDelivery, ): Promise { const [row] = await rawRows<{ changed: boolean }>( db, sql`select opengeni_private.mark_automatic_session_title_fanout_delivered_v1( ${delivery.outboxId}::uuid, ${delivery.event.id}::uuid ) as changed`, ); return row?.changed === true; } export async function markAutomaticSessionTitleFanoutFailed( db: Database, delivery: AutomaticSessionTitleFanoutDelivery, error: string, ): Promise { const [row] = await rawRows<{ changed: boolean }>( db, sql`select opengeni_private.mark_automatic_session_title_fanout_failed_v1( ${delivery.outboxId}::uuid, ${delivery.event.id}::uuid, ${error} ) as changed`, ); return row?.changed === true; } export type SessionWorkflowWake = { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; wakeRevision: number; interruptionRequested: boolean; }; /** * Record a new workflow nudge in the same transaction as the state mutation * that made it necessary. Concurrent producers serialize on the one * per-session row and each receive the exact committed revision they own. */ export async function enqueueSessionWorkflowWakeInTransaction( tx: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }, ): Promise { const now = new Date(); const nextAttemptAt = input.notBefore ?? now; const [row] = await tx .insert(schema.sessionWorkflowWakeOutbox) .values({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: input.temporalWorkflowId, controlRevision: input.controlRequested ? 1 : 0, reason: input.reason, nextAttemptAt, }) .onConflictDoUpdate({ target: schema.sessionWorkflowWakeOutbox.sessionId, set: { temporalWorkflowId: input.temporalWorkflowId, wakeRevision: sql`${schema.sessionWorkflowWakeOutbox.wakeRevision} + 1`, controlRevision: input.controlRequested ? sql`${schema.sessionWorkflowWakeOutbox.wakeRevision} + 1` : sql`${schema.sessionWorkflowWakeOutbox.controlRevision}`, reason: input.reason, attempts: 0, // Coalescing a delayed retry must never postpone an undelivered wake // owned by another producer. Once every prior revision is delivered, // however, this is a new obligation and must honor its own deadline; // retaining the old (usually past) deadline would defeat backoff. nextAttemptAt: sql`case when ${schema.sessionWorkflowWakeOutbox.wakeRevision} > ${schema.sessionWorkflowWakeOutbox.deliveredRevision} then least( ${schema.sessionWorkflowWakeOutbox.nextAttemptAt}, ${nextAttemptAt.toISOString()}::timestamptz ) else ${nextAttemptAt.toISOString()}::timestamptz end`, lastError: null, updatedAt: now, }, }) .returning({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision }); if (!row) throw new Error(`Failed to enqueue workflow wake for session ${input.sessionId}`); return row.wakeRevision; } /** Standalone transactional producer for operations not already in a DB txn. */ export async function enqueueSessionWorkflowWake( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await enqueueSessionWorkflowWakeInTransaction(scopedDb, input), ); } /** * Re-deliver already-committed session work only when admission currently * allows this session to run. The workspace-then-session lock order matches * every Pause/Resume producer, so a retry cannot race around either gate. */ export async function enqueueSessionWorkflowWakeIfRunnable( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const effectiveControl = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { lock: "share" }, ); const [workspace] = await tx .select() .from(schema.workspaces) .where(eq(schema.workspaces.id, input.workspaceId)) .for("update") .limit(1); const [session] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .for("no key update") .limit(1); if (!workspace || !session) throw new Error(`Session not found: ${input.sessionId}`); const realtimeActive = await sessionRealtimeIsActiveInTransaction( tx as unknown as Database, input.workspaceId, input.sessionId, ); const runnable = session.status !== "cancelled" && !realtimeActive && session.activeTurnId === null && effectiveControl.state === "active"; return runnable ? await enqueueSessionWorkflowWakeInTransaction(tx as unknown as Database, input) : null; }), ); } /** Claim only explicit, undelivered wake revisions; never infer work by scan. */ export async function claimPendingSessionWorkflowWakes( db: Database, limit = 100, ): Promise { const rows = await rawRows<{ account_id: string; workspace_id: string; session_id: string; temporal_workflow_id: string; wake_revision: number | string; interruption_requested: boolean; }>(db, sql`select * from opengeni_private.claim_session_workflow_wakes(${limit})`); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, temporalWorkflowId: row.temporal_workflow_id, wakeRevision: Number(row.wake_revision), interruptionRequested: row.interruption_requested, })); } /** * Acknowledge an immediate post-commit signal only after it cannot strand an * accepted direction or an interrupted attempt awaiting writer-set proof. * Temporal accepting a signal is transport evidence, not proof that a closing * workflow observed Postgres. While active control still has an actionable * Agent Steer, a current wake owns a queued human/API turn, eligible machine * input, or a due idle input-wait obligation, or an attempt awaits quiescence, retain the revision so the bounded outbox * dispatcher retries signalWithStart. The attempt-fenced claim consumes each * direction once; a real Pause is the typed blocker and may acknowledge this * revision because Resume commits a new one. * * An older sender may advance only its own revision; it cannot clear a claim or * failure state belonging to a newer revision. Therefore queued prompt work * blocks acknowledgement only for the current coalesced revision: a stale * acknowledgement still leaves the newer revision outstanding. The control -> * workspace -> session lock prefix serializes this decision with Send, Steer, * Pause/Resume, and claim without weakening physical-quiescence admission. */ export type SessionWorkflowWakeDeliveryResult = | { action: "acknowledged" } | { action: "pending_admission"; blocker: | "pending_agent_steer" | "pending_prompt_turn" | "pending_quiescence" | "pending_machine_input" | "pending_input_wait" | "session_unavailable"; }; export async function markSessionWorkflowWakeDelivered( db: Database, input: Omit, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!session) return { action: "pending_admission", blocker: "session_unavailable" } as const; const effectiveControl = await evaluateSessionWriteAdmissionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined, lockedSession: session }, ); if (effectiveControl.state === "active" && !session.admissionBlock) { const [pendingAgentSteer] = await tx .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "agent_steer_instruction"), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .limit(1); if (pendingAgentSteer) { return { action: "pending_admission", blocker: "pending_agent_steer", } as const; } if ( await hasPendingSessionAttemptQuiescenceTx(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, }) ) { return { action: "pending_admission", blocker: "pending_quiescence", } as const; } const [currentWake] = await tx .select({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), ), ) .limit(1); if (currentWake?.wakeRevision === input.wakeRevision) { if (session.activeTurnId !== null) { const [recovering] = await tx .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, session.activeTurnId), eq(schema.sessionTurns.status, "recovering"), isNull(schema.sessionTurns.activeAttemptId), ), ) .limit(1); // The receipt proves the previous writer is gone, not that a // closing workflow consumed the recovery. Keep transport debt // until the exact logical turn is reclaimed. Use the ordinary // peek so setup/capacity/lifecycle blockers remain authoritative. if ( recovering && ( await peekSessionWork( tx as unknown as Database, input.workspaceId, input.sessionId, ) ).kind === "runnable" ) { return { action: "pending_admission", blocker: "pending_prompt_turn" } as const; } } // A transport ACK is not consumption. The workflow may have already // taken its closing snapshot when a timeout or child result arrives. // Keep the current revision retryable until claim consumes the input. if ( session.activeTurnId === null && session.status !== "failed" && session.status !== "cancelled" && session.status !== "requires_action" && !(await sessionRealtimeIsActiveInTransaction( tx as unknown as Database, input.workspaceId, input.sessionId, )) ) { const wait = await sessionInputWaitStateTx( tx as unknown as Database, input.workspaceId, input.sessionId, session, ); // Input held by a terminal compaction failure is not admissible // until newer truth arrives (see `peekSessionWork`); keeping the // wake open for it would only re-signal a workflow that has // nothing to claim, forever. const compactionHoldSequence = await compactionFailureHoldSequenceTx( tx as unknown as Database, input.workspaceId, input.sessionId, ); const pending = await tx .selectDistinct({ kind: schema.sessionSystemUpdates.kind, passive: passiveCommandNoticeSql(), }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.state, "pending"), compactionHoldSequence === null ? undefined : systemUpdatePendingAfterSequenceSql( tx as unknown as Database, input.workspaceId, input.sessionId, compactionHoldSequence, ), ), ); const [goal] = await tx .select({ status: schema.sessionGoals.status }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .limit(1); if ( pending.some( ({ kind, passive }) => !passive && SESSION_SYSTEM_UPDATE_WAKE_CLASS[kind as SessionSystemUpdateKind] === "immediate" && (kind !== "background_command_result" || wait.disposition === "held") && (!isChildLifecycleSystemUpdateKind(kind as SessionSystemUpdateKind) || goal?.status === "active" || wait.disposition === "held" || session.status === "queued"), ) ) return { action: "pending_admission", blocker: "pending_machine_input" } as const; // A future hold is explicitly re-armed by settlement. Retaining its // early transport revision would coalesce every rearm back to now. if (wait.disposition === "timeout") { return { action: "pending_admission", blocker: "pending_input_wait" } as const; } } // A message waiting for the personal machine's owner is not // undelivered work, so it must not keep the wake pending. const pendingPromptTurn = await runnableQueuedTurnExists(tx as unknown as Database, { accountId: null, workspaceId: input.workspaceId, sessionId: input.sessionId, sources: ["user", "api"], }); if (pendingPromptTurn) { return { action: "pending_admission", blocker: "pending_prompt_turn", } as const; } } } const [row] = await tx .update(schema.sessionWorkflowWakeOutbox) .set({ deliveredRevision: sql`greatest(${schema.sessionWorkflowWakeOutbox.deliveredRevision}, ${input.wakeRevision})`, attempts: sql`case when ${schema.sessionWorkflowWakeOutbox.wakeRevision} = ${input.wakeRevision} then 0 else ${schema.sessionWorkflowWakeOutbox.attempts} end`, lastError: sql`case when ${schema.sessionWorkflowWakeOutbox.wakeRevision} = ${input.wakeRevision} then null else ${schema.sessionWorkflowWakeOutbox.lastError} end`, updatedAt: new Date(), }) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), gte(schema.sessionWorkflowWakeOutbox.wakeRevision, input.wakeRevision), ), ) .returning({ sessionId: schema.sessionWorkflowWakeOutbox.sessionId }); if (!row) { throw new Error( `Workflow wake revision ${input.wakeRevision} is not current for session ${input.sessionId}`, ); } return { action: "acknowledged" } as const; }), ); } /** Record delivery failure; the claim already scheduled the bounded retry. */ export async function markSessionWorkflowWakeFailed( db: Database, input: SessionWorkflowWake, error: string, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { // 0560's archive guard locks the session during the outbox UPDATE. // Own the canonical prefix first, like delivery ACK and wake enqueue, // so a failed transport cannot deadlock the turn committing that wake. const locks = await lockSessionEventWriteRows(scopedDb, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); if (!locks.sessions[0]) return false; const [row] = await scopedDb .update(schema.sessionWorkflowWakeOutbox) .set({ lastError: error.slice(0, 500), updatedAt: new Date(), }) .where( and( eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.wakeRevision, input.wakeRevision), lt(schema.sessionWorkflowWakeOutbox.deliveredRevision, input.wakeRevision), ), ) .returning({ sessionId: schema.sessionWorkflowWakeOutbox.sessionId }); return row !== undefined; }, ); } export async function getOrCreateSessionSystemUpdateOutbox( db: Database, input: Omit & { /** Default: the source child's exact spawning parent turn's value. */ subscriptionAuthority?: SubscriptionPersonalAuthorityV2 | null; }, ): Promise { const persistence = { stage: "session_lifecycle_outbox.get_or_create", eventTypes: ["child_terminal_result"], maxAttempts: 3, }; const context = { accountId: input.accountId, workspaceId: input.workspaceId, }; return await retryRlsPersistence(db, context, persistence, async (scopedDb) => { const locks = await lockSessionEventWriteRows(scopedDb, { workspaceId: input.workspaceId, controlLock: "none", sessionIds: [input.sourceSessionId, input.targetSessionId], }); const expectedSessionIds = new Set([input.sourceSessionId, input.targetSessionId]); if (locks.sessions.length !== expectedSessionIds.size) { throw new SessionControlInvariantError( "System-update outbox source and target sessions must exist in the same workspace", ); } // The producing lifecycle transaction may already have committed this row // with content only it could freeze (the child's final answer, or its // consumption evidence). Enrichment adds facts on top of that content and // never replaces it, under the same row lock the upsert takes. const [committed] = await scopedDb .select({ kind: schema.sessionSystemUpdateOutbox.kind, payload: schema.sessionSystemUpdateOutbox.payload, payloadCodecVersion: schema.sessionSystemUpdateOutbox.payloadCodecVersion, }) .from(schema.sessionSystemUpdateOutbox) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdateOutbox.dedupeKey, input.dedupeKey), ), ) .for("update") .limit(1); const payload = committed ? withCommittedChildResultContent(committed, input.payload) : input.payload; const [row] = await scopedDb .insert(schema.sessionSystemUpdateOutbox) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sourceSessionId: input.sourceSessionId, targetSessionId: input.targetSessionId, dedupeKey: input.dedupeKey, kind: input.kind, classification: input.classification, sourceId: input.sourceId, summary: input.summary, payload, lineage: input.lineage, personalConnectionDelegations: input.personalConnectionDelegations, mcpAccountBindings: input.mcpAccountBindings, xaiProviderAccountAuthoritySnapshot: input.xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot: input.claudeProviderAccountAuthoritySnapshot, subscriptionAuthority: input.subscriptionAuthority !== undefined ? input.subscriptionAuthority : await childNoticeParentSubscriptionAuthorityTx( scopedDb as unknown as Database, input.workspaceId, input.sourceSessionId, ), }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .onConflictDoUpdate({ target: [ schema.sessionSystemUpdateOutbox.workspaceId, schema.sessionSystemUpdateOutbox.dedupeKey, ], set: withLosslessContentWriteVersion( withLosslessContentWriteVersion( { kind: input.kind, classification: input.classification, sourceId: input.sourceId, summary: input.summary, payload, updatedAt: new Date(), }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), }) .returning(); if (!row) throw new Error("Failed to persist system-update outbox row"); // Skipped when the upsert updated an existing row. await copySubscriptionAuthorityCompatInTransaction(scopedDb as unknown as Database, [ { kind: "session_system_update_outbox", workspaceId: input.workspaceId, id: row.id }, ]); if ( stableJson(parseAcceptedMcpAccountBindings(row.mcpAccountBindings)) !== stableJson(parseAcceptedMcpAccountBindings(input.mcpAccountBindings)) ) { throw new Error("System-update outbox replay changed its accepted MCP accounts"); } if ( stableJson( XaiProviderAccountAuthoritySnapshotV1.parse(row.xaiProviderAccountAuthoritySnapshot), ) !== stableJson(input.xaiProviderAccountAuthoritySnapshot) ) { throw new Error("System-update outbox replay changed its xAI authority snapshot"); } const storedXaiSubjectId = row.lineage.xaiAuthoritySubjectId; const inputXaiSubjectId = input.lineage.xaiAuthoritySubjectId; if (storedXaiSubjectId !== inputXaiSubjectId) { throw new Error("System-update outbox replay changed its xAI authority subject"); } if ( stableJson( ClaudeProviderAccountAuthoritySnapshotV1.parse(row.claudeProviderAccountAuthoritySnapshot), ) !== stableJson(input.claudeProviderAccountAuthoritySnapshot) ) { throw new Error("System-update outbox replay changed its Claude authority snapshot"); } const storedClaudeSubjectId = row.lineage.claudeAuthoritySubjectId; const inputClaudeSubjectId = input.lineage.claudeAuthoritySubjectId; if (storedClaudeSubjectId !== inputClaudeSubjectId) { throw new Error("System-update outbox replay changed its Claude authority subject"); } if (row.lineage.connectionAuthoritySubjectId !== input.lineage.connectionAuthoritySubjectId) { throw new Error("System-update outbox replay changed its connection authority subject"); } const typed = parseChildLifecycleOutboxPayload( fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), row.kind, ); return { id: row.id, status: row.status as "pending" | "delivered", accountId: row.accountId, workspaceId: row.workspaceId, sourceSessionId: row.sourceSessionId, targetSessionId: row.targetSessionId, dedupeKey: row.dedupeKey, kind: typed.kind, classification: row.classification as SystemUpdateClassification, sourceId: row.sourceId, summary: fromPostgresLosslessText(row.summary, row.summaryCodecVersion), payload: typed.payload, lineage: row.lineage, personalConnectionDelegations: parsedPersonalConnectionDelegations( row.personalConnectionDelegations, `session_system_update_outbox:${row.workspaceId}:${row.id}`, ), mcpAccountBindings: parseAcceptedMcpAccountBindings(row.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1.parse( row.xaiProviderAccountAuthoritySnapshot, ), claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1.parse( row.claudeProviderAccountAuthoritySnapshot, ), subscriptionAuthority: frozenSubscriptionAuthorityV2(row.subscriptionAuthority), }; }); } /** Content the child's own lifecycle transaction froze into its terminal * result. A committed payload that no longer parses is rewritten from the * enrichment alone, as before this content existed. */ const COMMITTED_CHILD_RESULT_CONTENT_KEYS = ["finalAnswer", "childEventEvidence"] as const; function withCommittedChildResultContent( committed: { kind: string; payload: unknown; payloadCodecVersion: number | null }, enrichment: ChildLifecycleOutboxPayload, ): ChildLifecycleOutboxPayload { let stored: Record; try { stored = parseChildLifecycleOutboxPayload( fromPostgresLosslessJson(committed.payload, committed.payloadCodecVersion), committed.kind, ).payload as Record; } catch { return enrichment; } if (stored.type !== enrichment.type) return enrichment; const merged: Record = { ...enrichment }; for (const key of COMMITTED_CHILD_RESULT_CONTENT_KEYS) { if (Object.hasOwn(stored, key) && !Object.hasOwn(merged, key)) merged[key] = stored[key]; } return merged as ChildLifecycleOutboxPayload; } export async function markSessionSystemUpdateOutboxFailed( db: Database, input: Pick, error: string, ): Promise { await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await scopedDb .update(schema.sessionSystemUpdateOutbox) .set({ lastError: error.slice(0, 500), updatedAt: new Date() }) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdateOutbox.id, input.id), eq(schema.sessionSystemUpdateOutbox.status, "pending"), ), ); }, ); } /** DB-only callback for addSessionSystemUpdateWithSourceMutation. */ export async function markSessionSystemUpdateOutboxDeliveredInTransaction( tx: Database, input: Pick, ): Promise { const [row] = await tx .update(schema.sessionSystemUpdateOutbox) .set({ status: "delivered", deliveredAt: new Date(), lastError: null, updatedAt: new Date(), }) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdateOutbox.id, input.id), eq(schema.sessionSystemUpdateOutbox.status, "pending"), ), ) .returning({ id: schema.sessionSystemUpdateOutbox.id }); if (!row) { const [existing] = await tx .select({ status: schema.sessionSystemUpdateOutbox.status }) .from(schema.sessionSystemUpdateOutbox) .where( and( eq(schema.sessionSystemUpdateOutbox.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdateOutbox.id, input.id), ), ) .limit(1); if (existing?.status !== "delivered") { throw new Error(`System-update outbox row not pending: ${input.id}`); } } } type SessionSystemUpdateInputVariant = { [Kind in SessionSystemUpdateKind]: { kind: Kind; payload: Extract; }; }[SessionSystemUpdateKind]; export type AddSessionSystemUpdateInput = { accountId: string; workspaceId: string; sessionId: string; classification: SystemUpdateClassification; sourceId: string; dedupeKey: string; summary: string; lineage?: Record; personalConnectionDelegations?: McpPersonalConnectionDelegation[]; mcpAccountBindings?: McpConnectionAccountBinding[] | null; xaiProviderAccountAuthoritySnapshot?: XaiProviderAccountAuthoritySnapshotV1; claudeProviderAccountAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1; scheduledTaskRunId?: string | null; /** * Codex v2 (M3 PR 3b) frozen by the producer (a child notice's parent turn, * a scheduled task, a causal turn). Absent means none; the delivering turn * then copies its receiving context or takes the empty value. */ subscriptionAuthority?: SubscriptionPersonalAuthorityV2 | null; } & SessionSystemUpdateInputVariant; export type AddSessionSystemUpdateResult = | { added: false; reason: "session_cancelled" } | (RequireIdleSession extends true ? | { added: false; reason: "session_not_idle" } | { added: false; reason: "session_waiting_capacity" } | { added: false; reason: "session_paused" } | { added: false; reason: "workspace_paused" } : never) | { added: boolean; reason: "added" | "duplicate"; update: SessionSystemUpdate; shouldWake: boolean; workflowWakeRevision: number | null; wakeEventId: string; temporalWorkflowId: string | null; events: SessionEvent[]; }; export type PrepareSessionSystemUpdateSourceResult = { /** Private, bounded, content-free source authority appended before insert. */ lineage?: Record; /** Source-owned events appended before the pending-update event. */ events?: SessionEvent[]; }; export async function addSessionSystemUpdate( db: Database, input: AddSessionSystemUpdateInput, ): Promise> { if (input.payload.type !== input.kind) { throw new Error(`Internal update payload discriminator must equal kind ${input.kind}`); } return await addSessionSystemUpdateWithSourceMutation(db, input, async () => undefined); } export type EnqueueCapabilitySetupContinuationInput = { accountId: string; workspaceId: string; sessionId: string; capabilityId: string; /** * The capability's MCP endpoint. An agent's request to add a server * (custom_mcp_setup_request) posts its card before the capability exists, so * that card names the endpoint rather than a capability id. */ endpointUrl?: string; /** * The card is a connected account's own notice (expired access, more access * a tool needs) rather than a capability card: find it by this connection. */ connectionId?: string; /** The live catalog's name for the capability, shown to the agent. */ capabilityName: string; /** * Whether the caller verified the capability's tools are in the chat (not * only assumed because the chat's tool list was too long to check). */ toolsVerified: boolean; /** The authenticated person who finished setup. */ requesterSubjectId: string; }; export type EnqueueCapabilitySetupContinuationResult = | { outcome: "queued" | "already_queued"; update: SessionSystemUpdate; shouldWake: boolean; workflowWakeRevision: number | null; temporalWorkflowId: string | null; events: SessionEvent[]; } | { outcome: "not_needed"; reason: Extract< CapabilitySetupContinuationSkipReason, "no_card" | "later_message" | "not_requester" | "session_closed" >; }; class CapabilitySetupContinuationNotNeeded extends Error { constructor(readonly reason: "later_message" | "not_requester") { super(`capability setup continuation not needed: ${reason}`); } } /** The card's dedupe key: at most one continuation per posted card. */ export function capabilitySetupContinuationDedupeKey(cardEventId: string): string { return `capability-setup-continuation:${cardEventId}`; } /** * Wake the agent once after the person finished setup from the latest card it * posted for `capabilityId`. The caller has already checked that the * capability is usable in this chat. Nothing is sent when no such card exists, * when the person has written since the card (their message carries on), or * when the request the card belongs to is someone else's. The update runs in * the person's receiving context, exactly as their own next message would. */ export async function enqueueCapabilitySetupContinuation( db: Database, input: EnqueueCapabilitySetupContinuationInput, ): Promise { const read = await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scoped) => { const tx = scoped as unknown as Database; const [card] = await latestAuthCardTx(tx, input); if (!card) return { kind: "skip", reason: "no_card" } as const; const [existing] = await tx .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.dedupeKey, capabilitySetupContinuationDedupeKey(card.id)), ), ) .limit(1); if (existing) return { kind: "existing", update: mapSessionSystemUpdate(existing) } as const; const [session] = await tx .select({ status: schema.sessions.status, contentArchiveState: schema.sessions.contentArchiveState, executionContextTurnId: schema.sessions.executionContextTurnId, }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session || session.status === "cancelled" || session.contentArchiveState !== null) { return { kind: "skip", reason: "session_closed" } as const; } if (await userMessageAfterSequenceTx(tx, input, card.sequence)) { return { kind: "skip", reason: "later_message" } as const; } if (!session.executionContextTurnId) return { kind: "skip", reason: "not_requester" } as const; const [context] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, session.executionContextTurnId), ), ) .limit(1); // The continuation stands in for the requester's own "done", so it runs // on their receiving context: the person who made the request, or for a // request no person made (a host server's own key) that same principal. // Someone else finishing setup in a shared chat can simply say so. if ( !context || (turnHuman(context) ?? context.initiatorSubjectId) !== input.requesterSubjectId ) { return { kind: "skip", reason: "not_requester" } as const; } return { kind: "card", card, context } as const; }); if (read.kind === "skip") return { outcome: "not_needed", reason: read.reason }; if (read.kind === "existing") { return { outcome: "already_queued", update: read.update, shouldWake: false, workflowWakeRevision: null, temporalWorkflowId: null, events: [], }; } const { card, context } = read; const human = turnHuman(context); // The receiving context's exact authority, as a goal continuation copies // its causal turn's: the claim then admits it into that context and // resolves the person's current accounts, including the one just set up. const personalConnectionDelegations = parsedPersonalConnectionDelegations( context.personalConnectionDelegations, `session_turns:${input.workspaceId}:${input.sessionId}:${context.id}`, ); const xaiProviderAccountAuthoritySnapshot = XaiProviderAccountAuthoritySnapshotV1.parse( context.xaiProviderAccountAuthoritySnapshot, ); const claudeProviderAccountAuthoritySnapshot = ClaudeProviderAccountAuthoritySnapshotV1.parse( context.claudeProviderAccountAuthoritySnapshot, ); const name = input.capabilityName.trim().slice(0, CAPABILITY_SETUP_COMPLETED_NAME_MAX_CHARS); try { const result = await addSessionSystemUpdateWithSourceMutation( db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: "capability_setup_completed", classification: "success", sourceId: card.id, dedupeKey: capabilitySetupContinuationDedupeKey(card.id), summary: capabilitySetupCompletedSummary(name || input.capabilityId, input.toolsVerified), payload: { type: "capability_setup_completed", capabilityId: input.capabilityId, name: name || input.capabilityId.slice(0, CAPABILITY_SETUP_COMPLETED_NAME_MAX_CHARS), cardEventId: card.id, }, lineage: { causalTurnId: context.id, ...(human && personalConnectionDelegations.length > 0 ? { connectionAuthoritySubjectId: human } : {}), ...(human && xaiProviderAccountAuthoritySnapshot.scope === "user" ? { xaiAuthoritySubjectId: human } : {}), ...(human && claudeProviderAccountAuthoritySnapshot.scope === "user" ? { claudeAuthoritySubjectId: human } : {}), }, personalConnectionDelegations, mcpAccountBindings: parseAcceptedMcpAccountBindings(context.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot, }, async () => undefined, { // Re-check under the session lock: a message or a new receiving // context committed since the read wins over this continuation. prepareSource: async (tx) => { const [locked] = await tx .select({ executionContextTurnId: schema.sessions.executionContextTurnId }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (await userMessageAfterSequenceTx(tx, input, card.sequence)) { throw new CapabilitySetupContinuationNotNeeded("later_message"); } if (locked?.executionContextTurnId !== context.id) { throw new CapabilitySetupContinuationNotNeeded("not_requester"); } }, }, ); if (result.reason === "session_cancelled") { return { outcome: "not_needed", reason: "session_closed" }; } return { outcome: result.added ? "queued" : "already_queued", update: result.update, shouldWake: result.shouldWake, workflowWakeRevision: result.workflowWakeRevision, temporalWorkflowId: result.temporalWorkflowId, events: result.events, }; } catch (error) { if (error instanceof CapabilitySetupContinuationNotNeeded) { return { outcome: "not_needed", reason: error.reason }; } throw error; } } /** The latest card the continuation answers: a capability card, or an account's own. */ async function latestAuthCardTx( tx: Database, input: Pick< EnqueueCapabilitySetupContinuationInput, "workspaceId" | "sessionId" | "capabilityId" | "connectionId" | "endpointUrl" >, ): Promise> { const capabilityCard = sql`${schema.sessionEvents.payload} -> 'capability' ->> 'id' = ${input.capabilityId}`; // The card keeps the address as the agent gave it; ignore case and a // trailing slash so the saved server's address still finds it. const setupRequestCard = input.endpointUrl ? sql`rtrim(lower(${schema.sessionEvents.payload} -> 'setupRequest' ->> 'endpointUrl'), '/') = rtrim(lower(${input.endpointUrl}), '/')` : null; return await tx .select({ id: schema.sessionEvents.id, sequence: schema.sessionEvents.sequence, payload: schema.sessionEvents.payload, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "tool.auth_needed"), input.connectionId ? sql`${schema.sessionEvents.payload} ->> 'connectionId' = ${input.connectionId}` : setupRequestCard ? sql`(${capabilityCard} or ${setupRequestCard})` : capabilityCard, ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(1); } /** * The latest auth notice this chat showed for one connected account, so the * caller can check the account now has what the notice asked for before it * continues the request. Null when the chat showed none. */ export async function latestConnectionAuthNotice( db: Database, input: { workspaceId: string; sessionId: string; connectionId: string }, ): Promise<{ id: string; payload: Record } | null> { return await withWorkspaceSessionActivityRls(db, input.workspaceId, async (scoped) => { const [card] = await latestAuthCardTx(scoped as unknown as Database, { ...input, capabilityId: "", }); if (!card) return null; const payload = card.payload && typeof card.payload === "object" && !Array.isArray(card.payload) ? (card.payload as Record) : {}; return { id: card.id, payload }; }); } async function userMessageAfterSequenceTx( tx: Database, input: Pick, sequence: number, ): Promise { const [message] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "user.message"), gt(schema.sessionEvents.sequence, sequence), ), ) .limit(1); return message !== undefined; } /** * Persist one internal update without fabricating a user prompt or queue row. * Dedupe and any producer/outbox mutation commit in the same transaction. */ export async function addSessionSystemUpdateWithSourceMutation< RequireIdleSession extends boolean = false, >( db: Database, input: AddSessionSystemUpdateInput, mutateSource: ( tx: Database, wakeEventId: string | null, updateId: string | null, rejectionReason: | "session_cancelled" | "session_not_idle" | "session_waiting_capacity" | "session_paused" | "workspace_paused" | null, ) => Promise, options: { /** * Admit only when the already-locked session has no work in progress: * idle, or failed (its last turn ended and it accepts new turns). */ requireIdleSession?: RequireIdleSession; /** * Refuse while a Pause holds the session, whatever its other work: * `session_paused` for a Pause of this session or an ancestor, * `workspace_paused` for a workspace Pause alone. Input queued behind a * Pause could neither run nor settle until someone resumes. */ refusePaused?: RequireIdleSession; /** Runs under the locked session/source transaction before any update/event insert. */ prepareSource?: ( tx: Database, sessionId: string, ) => Promise; } = {}, ): Promise> { if (Buffer.byteLength(JSON.stringify(input.payload)) > MAX_INTERNAL_UPDATE_BYTES) { throw new Error(`Internal update payload exceeds ${MAX_INTERNAL_UPDATE_BYTES} bytes`); } if (Buffer.byteLength(input.summary) > MAX_INTERNAL_UPDATE_BYTES) { throw new Error(`Internal update summary exceeds ${MAX_INTERNAL_UPDATE_BYTES} bytes`); } return (await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); let session = locks.sessions[0]; if (!session) throw new Error(`Session not found: ${input.sessionId}`); const temporalWorkflowId = session.temporalWorkflowId; const effectiveControl = await evaluateSessionControl( tx as unknown as Database, input.workspaceId, input.sessionId, { workspaceControl: locks.control ?? undefined }, ); // An archived session is read-only: machine input addressed to it (a // late child result, schedule or media completion) is settled exactly // like input to a cancelled session instead of being retried forever. // That includes a chat archived and waiting to be stored, so nothing // starts work in it again. if ( session.status === "cancelled" || session.contentArchiveState !== null || session.archivedAt !== null ) { await mutateSource(tx as unknown as Database, null, null, "session_cancelled"); return { added: false, reason: "session_cancelled" } as const; } const replayExistingUpdate = async (events: SessionEvent[]) => { const [existing] = await tx .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.dedupeKey, input.dedupeKey), ), ) .limit(1); if (!existing) return null; if ( stableJson(parseAcceptedMcpAccountBindings(existing.mcpAccountBindings)) !== stableJson(parseAcceptedMcpAccountBindings(input.mcpAccountBindings)) ) { throw new Error("System-update replay changed its accepted MCP accounts"); } const [pendingEvent] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "system.update.pending"), sql`${schema.sessionEvents.payload} ->> 'updateId' = ${existing.id}`, ), ) .limit(1); if (!pendingEvent) throw new Error("System-update pending event disappeared"); await mutateSource(tx as unknown as Database, pendingEvent.id, existing.id, null); return { added: false, reason: "duplicate", update: mapSessionSystemUpdate(existing), shouldWake: false, workflowWakeRevision: null, wakeEventId: pendingEvent.id, temporalWorkflowId, events, } as const; }; // A stale queued projection with no accepted work must not suppress // every future occurrence. Prove emptiness under the admission lock; // never bypass Pause, a parked turn, pending input or physical writers. const emptyQueuedProjection = options.requireIdleSession && session.status === "queued" && (await sessionQueueIsEmptyInTransaction( tx as unknown as Database, input.workspaceId, input.sessionId, )); const sessionPaused = effectiveControl.blockers.some( (blocker) => blocker.kind === "session", ); if ( (options.refusePaused && effectiveControl.state !== "active") || (options.requireIdleSession && ((session.status !== "idle" && session.status !== "failed" && !emptyQueuedProjection) || session.activeTurnId !== null || effectiveControl.state !== "active")) ) { const replayed = await replayExistingUpdate([]); if (replayed) { return replayed; } const reason = effectiveControl.state === "active" ? // A chat parked on a model account (for example a Codex plan // out of usage or no longer connected) is told apart, so the // schedule can name the fix: pick another model in the chat. session.status === "waiting_capacity" ? "session_waiting_capacity" : "session_not_idle" : sessionPaused ? "session_paused" : "workspace_paused"; await mutateSource(tx as unknown as Database, null, null, reason); return { added: false, reason } as const; } const prepared = await options.prepareSource?.(tx as unknown as Database, input.sessionId); if ((prepared?.events?.length ?? 0) > 0) { const [refreshedSession] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!refreshedSession) throw new Error(`Session not found: ${input.sessionId}`); session = refreshedSession; } const lineage = { ...(input.lineage ?? {}), ...(prepared?.lineage ?? {}), }; // The parent's own attempt may already have read this exact answer // before the child's idle boundary committed it. Such a result stays // canonical but arrives consumed: no pending input, no wake. const consumedByParentRead = input.kind === "child_terminal_result" && input.classification === "success" && (await childTerminalResultConsumedByParentReadTx(tx as unknown as Database, { workspaceId: input.workspaceId, parentSessionId: input.sessionId, payload: input.payload, })); // Producers without causal authority have no exact human: resolve the // organization or workspace pool rather than assuming workspace. const sharedUpdatePool = input.xaiProviderAccountAuthoritySnapshot === undefined || input.claudeProviderAccountAuthoritySnapshot === undefined ? await sharedPoolSubscriptionAuthoritySnapshotsInTransaction( tx as unknown as Database, input.workspaceId, ) : null; const [inserted] = await tx .insert(schema.sessionSystemUpdates) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: input.kind, classification: input.classification, sourceId: input.sourceId, dedupeKey: input.dedupeKey, summary: input.summary, payload: input.payload, lineage, personalConnectionDelegations: input.personalConnectionDelegations ?? [], mcpAccountBindings: parseAcceptedMcpAccountBindings(input.mcpAccountBindings), xaiProviderAccountAuthoritySnapshot: input.xaiProviderAccountAuthoritySnapshot ?? sharedUpdatePool!.xai, claudeProviderAccountAuthoritySnapshot: input.claudeProviderAccountAuthoritySnapshot ?? sharedUpdatePool!.claude, subscriptionAuthority: input.subscriptionAuthority ?? null, scheduledTaskRunId: input.scheduledTaskRunId ?? null, state: consumedByParentRead ? "superseded" : "pending", }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionSystemUpdates.workspaceId, schema.sessionSystemUpdates.sessionId, schema.sessionSystemUpdates.dedupeKey, ], }) .returning(); if (!inserted) { const replayed = await replayExistingUpdate(prepared?.events ?? []); if (!replayed) throw new Error("System-update dedupe row disappeared"); return replayed; } await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_system_update", workspaceId: input.workspaceId, id: inserted.id }, ]); const now = new Date(); const eventPreview = internalUpdateEventMember( inserted, await automationNamesForUpdatesInTransaction( tx as unknown as Database, input.workspaceId, [inserted], ), ); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "system.update.pending", payload: { updateId: eventPreview.id, kind: eventPreview.kind, classification: eventPreview.classification, sourceId: eventPreview.sourceId, sourceIdTruncated: eventPreview.sourceIdTruncated, summary: eventPreview.summary, summaryTruncated: eventPreview.summaryTruncated, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to create system-update pending event"); await mutateSource(tx as unknown as Database, event.id, inserted.id, null); // Producer-side supersession of this child's now-stale pending notices // on the parent: a newer child_progress replaces an older one, and a // resolution supersedes the child_requires_action of the same exact // (child, turn, generation) because one accepted response advances that // blocked boundary (a re-freeze is a new generation and a new notice). const supersededUpdateIds = await supersedeStaleChildLifecycleNoticesInTransaction( tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, inserted, }, ); const [supersededEvent] = supersededUpdateIds.length > 0 ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2, type: "system.update.cancelled", payload: { updateIds: supersededUpdateIds, count: supersededUpdateIds.length, reason: childLifecycleSupersessionReason(input.kind), supersededByUpdateId: inserted.id, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning() : []; if (supersededUpdateIds.length > 0 && !supersededEvent) { throw new Error("Failed to append system-update supersession event"); } const [consumedEvent] = consumedByParentRead ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2 + (supersededEvent ? 1 : 0), type: "system.update.cancelled", payload: { updateIds: [inserted.id], count: 1, reason: "consumed_by_parent_read", }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning() : []; if (consumedByParentRead && !consumedEvent) { throw new Error("Failed to append consumed child result event"); } const supersessionSequences = (supersededEvent ? 1 : 0) + (consumedEvent ? 1 : 0); const realtimeActive = await sessionRealtimeIsActiveInTransaction( tx as unknown as Database, input.workspaceId, input.sessionId, ); // Wake class: only an `immediate` kind may register a workflow wake or // resume a cap-paused goal in this commit; a `deferred` kind is a // durable pending row that the next claim delivers coalesced. const wakeClass = SESSION_SYSTEM_UPDATE_WAKE_CLASS[input.kind]; const childLifecycleKind = isChildLifecycleSystemUpdateKind(input.kind); const commandMayWake = input.kind !== "background_command_result" || (await sessionInputWaitStateTx(tx, input.workspaceId, input.sessionId, session)) .disposition === "held"; // Every immediate kind except the goal's own synthesized continuation // is external input for the goal. A child notice may not revive an // already-failed parent (settled authority); every other kind already // wakes one. A deferred notice never resumes a goal by itself: a goal // resumed without a workflow wake would strand its obligation. const externalGoalInput = !consumedByParentRead && wakeClass === "immediate" && commandMayWake && input.kind !== "goal_continuation" && (!childLifecycleKind || session.status !== "failed"); let goalStatus: string | null = null; let autoResumed: SessionGoalAutoResumedByExternalInput | null = null; if (externalGoalInput) { // Session row first, then the goal row FOR UPDATE: the goal tools' // order. A `max_auto_continuations` pause is pacing, not intent, so // this new input resumes it in the same commit as the input itself // and the goal counts as active for the wake decision below. Any // other pause reason is left alone. autoResumed = await autoResumeGoalPausedByCapInTransaction(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, cause: { kind: input.kind, updateId: inserted.id }, now, }); if (autoResumed) { goalStatus = autoResumed.goal.status; } else { const [goal] = await tx .select({ status: schema.sessionGoals.status }) .from(schema.sessionGoals) .where( and( eq(schema.sessionGoals.workspaceId, input.workspaceId), eq(schema.sessionGoals.sessionId, input.sessionId), ), ) .for("update") .limit(1); goalStatus = goal?.status ?? null; } } const [resumedEvent] = autoResumed ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2 + supersessionSequences, type: "goal.resumed", payload: autoResumed.payload, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning() : []; if (autoResumed && !resumedEvent) { throw new Error("Failed to append goal.resumed event"); } const appendedSequences = (autoResumed ? 2 : 1) + supersessionSequences; // A child notice (completion, blocked-on-input, pause, capacity wait, // progress) remains durable model memory, but it is not new human // intent. A completed goal, a goal paused by intent, or an // already-failed parent is settled authority and cannot be restarted // solely by a late child. An active session-level input wait is also an // explicit durable obligation, independent of whether the session has // a goal, so an immediate child result may wake it. A parent with no // goal at all (an ordinary chat that started a worker and promised its // result) is woken by the child's terminal result. A child's blocking // question also wakes a parent whose goal is completed: the worker is // still the parent's work, and the parent should answer what it can // before the person has to. It does not reopen the goal. The person // sees the question too, and the first answer wins. A goal paused by // intent still holds every child notice for its next turn. const waitingForInput = childLifecycleKind && session.status !== "failed" && (await sessionInputWaitStateTx(tx, input.workspaceId, input.sessionId, session)) .disposition === "held"; const childNoticeMayWake = !childLifecycleKind || (session.status !== "failed" && (goalStatus === "active" || waitingForInput || ((input.kind === "child_terminal_result" || input.kind === "child_requires_action") && goalStatus === null) || (input.kind === "child_requires_action" && goalStatus === "completed"))); const shouldWake = !consumedByParentRead && wakeClass === "immediate" && !session.admissionBlock && commandMayWake && childNoticeMayWake && !realtimeActive && session.activeTurnId === null && effectiveControl.state === "active"; const wake = shouldWake ? await registerInternalUpdateWakeInTransaction(tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, }) : null; // An idle-gated admission consumes that boundary even when control or // realtime ownership withholds the workflow wake. Persisting `queued` // reserves the accepted work so a later distinct skip occurrence // cannot cross the same idle boundary while this update is pending. const shouldQueue = !session.admissionBlock && (shouldWake || options.requireIdleSession === true); await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + appendedSequences, ...(shouldQueue ? { status: "queued" as const } : {}), updatedAt: now, }) .where(eq(schema.sessions.id, session.id)); return { added: true, reason: "added", update: mapSessionSystemUpdate(inserted), shouldWake: wake !== null, workflowWakeRevision: wake?.wakeRevision ?? null, wakeEventId: event.id, temporalWorkflowId: session.temporalWorkflowId, events: [ ...(prepared?.events ?? []), mapEvent(event), ...(supersededEvent ? [mapEvent(supersededEvent)] : []), ...(consumedEvent ? [mapEvent(consumedEvent)] : []), ...(resumedEvent ? [mapEvent(resumedEvent)] : []), ], }; }), )) as AddSessionSystemUpdateResult; } async function sameSessionCausalAuthorityTx( tx: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string }, ) { const [turn] = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.accountId, input.accountId), eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, input.turnId), ), ) .limit(1); if (!turn) return null; const personalConnectionDelegations = parsedPersonalConnectionDelegations( turn.personalConnectionDelegations, `session_turns:${turn.id}`, ); const xaiProviderAccountAuthoritySnapshot = XaiProviderAccountAuthoritySnapshotV1.parse( turn.xaiProviderAccountAuthoritySnapshot, ); const claudeProviderAccountAuthoritySnapshot = ClaudeProviderAccountAuthoritySnapshotV1.parse( turn.claudeProviderAccountAuthoritySnapshot, ); const human = turn.initiatingHumanSubjectId ?? (turn.initiatorKind === "subject" ? turn.initiatorSubjectId : null); if ( !human && (personalConnectionDelegations.length > 0 || xaiProviderAccountAuthoritySnapshot.scope === "user" || claudeProviderAccountAuthoritySnapshot.scope === "user") ) { throw new SessionControlInvariantError("Causal turn lost its personal execution authority"); } return { personalConnectionDelegations, xaiProviderAccountAuthoritySnapshot, claudeProviderAccountAuthoritySnapshot, // Codex v2 (M3 PR 3b): the causal turn's frozen value, copied. subscriptionAuthority: frozenSubscriptionAuthorityV2(turn.subscriptionAuthority), lineage: { causalTurnId: turn.id, ...(human && personalConnectionDelegations.length > 0 ? { connectionAuthoritySubjectId: human } : {}), ...(human && xaiProviderAccountAuthoritySnapshot.scope === "user" ? { xaiAuthoritySubjectId: human } : {}), ...(human && claudeProviderAccountAuthoritySnapshot.scope === "user" ? { claudeAuthoritySubjectId: human } : {}), }, mcpAccountBindings: parseAcceptedMcpAccountBindings(turn.mcpAccountBindings), }; } /** Resolve only the immutable launch receipt, including pre-0419 managed rows. * Legacy Connected Machine rows have no durable launch identity and stay * unattributed. Neither a current session owner nor its latest turn is a substitute. */ async function backgroundCommandCausalAuthorityTx( tx: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string }, ) { const [command] = await tx .select() .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.accountId, input.accountId), eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), ), ) .limit(1); if (!command || !["exited", "lost"].includes(command.state) || !command.settledAt) return null; let turnId = command.launchTurnId; let attemptId = command.launchAttemptId; let generation = command.launchExecutionGeneration; if (!turnId && command.provider === "managed" && command.retainedProcessId) { const [process] = await tx .select() .from(schema.sandboxRetainedProcesses) .where( and( eq(schema.sandboxRetainedProcesses.id, command.retainedProcessId), eq(schema.sandboxRetainedProcesses.accountId, input.accountId), eq(schema.sandboxRetainedProcesses.workspaceId, input.workspaceId), eq(schema.sandboxRetainedProcesses.sessionId, input.sessionId), ), ) .limit(1); if (process?.ownerActorKind === "turn" && process.ownerActorId === process.ownerAttemptId) { turnId = process.ownerTurnId; attemptId = process.ownerAttemptId; generation = process.ownerExecutionGeneration; } } if (!turnId || !attemptId || !generation) return null; const [attempt] = await tx .select({ id: schema.sessionTurnAttempts.id }) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.id, attemptId), eq(schema.sessionTurnAttempts.accountId, input.accountId), eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.sessionId, input.sessionId), eq(schema.sessionTurnAttempts.turnId, turnId), eq(schema.sessionTurnAttempts.executionGeneration, generation), ), ) .limit(1); if (!attempt) return null; const authority = await sameSessionCausalAuthorityTx(tx, { ...input, turnId }); return authority ? { ...authority, lineage: { ...authority.lineage, causalAttemptId: attemptId, causalExecutionGeneration: generation, }, } : null; } /** Loss reasons that mean the whole sandbox box is gone, not just one exec. */ const SANDBOX_GONE_COMMAND_REASONS: ReadonlySet = new Set([ "provider_instance_lost", "provider_instance_not_found", "provider_instance_terminated", ]); function backgroundCommandTerminalMutation(input: { accountId: string; workspaceId: string; sessionId: string; /** Idle window named in an idle-containment notice, when known. */ idleContainmentMinutes?: number | null; }): { events: SessionEvent[]; wakes: SessionWorkflowWake[]; prepare: (tx: SessionActivityDatabase) => Promise; commit: (tx: SessionActivityDatabase, command: SessionBackgroundCommand) => Promise; } { let controlActive = false; const events: SessionEvent[] = []; const wakes: SessionWorkflowWake[] = []; return { events, wakes, prepare: async (tx: SessionActivityDatabase): Promise => { const locks = await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); const session = locks.sessions[0]; if (!locks.control || !locks.workspace || !session) { throw new Error(`Session not found: ${input.sessionId}`); } if (session.accountId !== input.accountId) { throw new SessionControlInvariantError( `Session ${input.sessionId} does not belong to account ${input.accountId}`, ); } // Terminal settlement only needs pause/admission state. Recounting all // stopping commands here makes draining a backlog quadratic, while each // count holds the session write lock and blocks unrelated lifecycle work. controlActive = ( await evaluateSessionWriteAdmissionControl(tx, input.workspaceId, input.sessionId, { workspaceControl: locks.control, lockedSession: session, }) ).state === "active"; }, commit: async ( tx: SessionActivityDatabase, command: SessionBackgroundCommand, ): Promise => { if ( command.workspaceId !== input.workspaceId || command.sessionId !== input.sessionId || (command.state !== "exited" && command.state !== "lost") || !command.settledAt || !command.settlementReason ) { throw new SessionControlInvariantError("Background command terminal identity is invalid"); } const [session] = await tx .select() .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ) .limit(1); if (!session) throw new Error(`Session not found: ${input.sessionId}`); // An operation abandoned on an unreachable machine already failed in the // turn that launched it; its later stop is audit, not new model input. const [stopRequest] = await tx .select({ requestedBy: schema.sessionBackgroundCommands.cancelRequestedBy }) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, command.id), ), ) .limit(1); const abandonedOnUnreachableMachine = stopRequest?.requestedBy === UNREACHABLE_MACHINE_STOP_REQUESTER; const terminalOccurredAt = new Date(command.settledAt); const now = new Date(); const reason = boundedSessionBackgroundCommandReason( command.settlementReason, "Stored background command settlement reason", ); const outputLocator = { eventType: "sandbox.command.output.delta" as const, commandId: command.id, }; const [finishedEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 1, type: "session.command.finished", payload: { commandId: command.id, provider: command.provider, state: command.state, exitCode: command.exitCode, reason, ...(command.failure ? { failure: command.failure } : {}), settledAt: command.settledAt, outputLocator, }, occurredAt: terminalOccurredAt, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!finishedEvent) throw new Error("Failed to append session.command.finished event"); // Failed/cancelled sessions are terminal and cannot claim another model // turn. Their terminal transition has already drained pending machine // input, so reopening one here would violate cancellation authority. The // exact command event remains durable audit/read truth; live sessions get // the typed model input below unless a terminal read already observed it. if ( session.status === "cancelled" || session.status === "failed" || command.completionObservedAt || abandonedOnUnreachableMachine ) { await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: now }) .where(eq(schema.sessions.id, session.id)); events.push(mapEvent(finishedEvent)); return; } // A command stopped on request (a person's Stop, the agent's own stop, or // a session Pause/Cancel) did not finish on its own; its exit code says // only how it ended (a terminal wrapper can even report 0). const stoppedOnRequest = command.state === "exited" && command.cancelRequestedAt !== null && !command.failure; const classification: SystemUpdateClassification = stoppedOnRequest ? "info" : command.state === "exited" && command.exitCode === 0 && !command.failure ? "success" : "failure"; const commandLabel = command.commandPreview || "Background command"; const idleMinutes = input.idleContainmentMinutes; const summary = command.failure ? `${commandLabel}: output delivery failed (${command.failure.code}); process exit code ${command.exitCode ?? "unknown"} is not a successful command result.` : command.state === "lost" && reason === IDLE_COMMAND_CONTAINMENT_REASON ? `\`${commandLabel}\` was stopped because nobody used this session${idleMinutes ? ` for ${idleMinutes} minute${idleMinutes === 1 ? "" : "s"} and it printed no output in that time` : " and it printed no output"}; the workspace was saved. Restart it if you still need it.` : command.state === "lost" && reason === DEADLINE_COMMAND_CONTAINMENT_REASON ? `\`${commandLabel}\` was stopped because the sandbox reached its maximum lifetime; the workspace was saved. Restart it if you still need it.` : command.state === "lost" && SANDBOX_GONE_COMMAND_REASONS.has(reason) ? `\`${commandLabel}\` is no longer running because its sandbox was shut down or lost; whether it finished is unknown. Check its effects before running it again.` : command.state === "lost" ? `${commandLabel}: result unavailable. Its exit status could not be confirmed.` : stoppedOnRequest ? `\`${commandLabel}\` was stopped.` : command.exitCode === 0 ? `${commandLabel}: completed successfully.` : `${commandLabel}: exited with code ${command.exitCode ?? "unknown"}.`; // The result carries the start and end of the output, so the turn it // wakes or reaches needs no extra read to learn what the command did. // A lost command (its sandbox gone, or contained) carries none: those // settle in bulk under lease locks, and its output stays readable. const output = command.state === "lost" ? null : await backgroundCommandResultOutputInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, commandId: command.id, }); const payload = { type: "background_command_result" as const, commandId: command.id, state: command.state, exitCode: command.exitCode, reason, ...(command.failure ? { failure: command.failure } : {}), outputLocator, ...(output !== null ? { output } : {}), ...(command.backgroundChildrenStopped ? { notice: CONNECTED_COMMAND_CHILD_CLEANUP_NOTICE } : {}), }; const causalAuthority = await backgroundCommandCausalAuthorityTx(tx as unknown as Database, { ...input, commandId: command.id, }); const sharedCommandPool = causalAuthority ? null : await sharedPoolSubscriptionAuthoritySnapshotsInTransaction( tx as unknown as Database, input.workspaceId, ); const [insertedUpdate] = await tx .insert(schema.sessionSystemUpdates) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, kind: "background_command_result", classification, sourceId: command.id, dedupeKey: `background-command-result:${command.id}`, summary, payload, personalConnectionDelegations: causalAuthority?.personalConnectionDelegations ?? [], mcpAccountBindings: causalAuthority?.mcpAccountBindings ?? null, xaiProviderAccountAuthoritySnapshot: causalAuthority?.xaiProviderAccountAuthoritySnapshot ?? sharedCommandPool!.xai, claudeProviderAccountAuthoritySnapshot: causalAuthority?.claudeProviderAccountAuthoritySnapshot ?? sharedCommandPool!.claude, subscriptionAuthority: causalAuthority?.subscriptionAuthority ?? null, lineage: { commandId: command.id, provider: command.provider, ...causalAuthority?.lineage, }, state: "pending", }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionSystemUpdates.workspaceId, schema.sessionSystemUpdates.sessionId, schema.sessionSystemUpdates.dedupeKey, ], }) .returning(); if (!insertedUpdate) { throw new SessionControlInvariantError( `Background command ${command.id} terminal input already exists before settlement`, ); } await copySubscriptionAuthorityCompatInTransaction(tx as unknown as Database, [ { kind: "session_system_update", workspaceId: input.workspaceId, id: insertedUpdate.id }, ]); const preview = internalUpdateEventMember(insertedUpdate); const [pendingEvent] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 2, type: "system.update.pending", payload: { updateId: preview.id, kind: preview.kind, classification: preview.classification, sourceId: preview.sourceId, sourceIdTruncated: preview.sourceIdTruncated, summary: preview.summary, summaryTruncated: preview.summaryTruncated, }, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!pendingEvent) throw new Error("Failed to append background command pending event"); const commandWait = await sessionInputWaitStateTx( tx, input.workspaceId, input.sessionId, session, ); // An idle-containment notice never wakes a wait: nothing used the box, // and waking would end a wait for a person, spend a model turn and // invite a restart every window. It is delivered with the next turn. const waitingForInput = commandWait.disposition === "held" && !(command.state === "lost" && reason === IDLE_COMMAND_CONTAINMENT_REASON); const autoResumed = waitingForInput ? await autoResumeGoalPausedByCapInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, cause: { kind: "background_command_result", updateId: insertedUpdate.id }, now, }) : null; const [resumedEvent] = autoResumed ? await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: session.lastSequence + 3, type: "goal.resumed", payload: autoResumed.payload, occurredAt: now, }, "payload", "payloadCodecVersion", ), ) .returning() : []; if (autoResumed && !resumedEvent) { throw new Error("Failed to append goal.resumed event for background command"); } const realtimeActive = await sessionRealtimeIsActiveInTransaction( tx, input.workspaceId, input.sessionId, ); const shouldWake = waitingForInput && !session.admissionBlock && session.status !== "failed" && session.activeTurnId === null && controlActive && !realtimeActive; if (shouldWake) { const temporalWorkflowId = session.temporalWorkflowId ?? `session-${session.id}`; const wake = await registerInternalUpdateWakeInTransaction(tx, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId, }); // The caller signals this after commit; the dispatcher remains the // repair path when it cannot. The wake is a passive queue change: this // branch requires an idle session, so there is no turn to interrupt. wakes.push({ accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId, wakeRevision: wake.wakeRevision, interruptionRequested: false, }); } await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + (autoResumed ? 3 : 2), ...(shouldWake ? { status: "queued" as const } : {}), updatedAt: now, }) .where(eq(schema.sessions.id, session.id)); events.push( mapEvent(finishedEvent), mapEvent(pendingEvent), ...(resumedEvent ? [mapEvent(resumedEvent)] : []), ); }, }; } export type SessionBackgroundCommandTerminalSettlement = { command: SessionBackgroundCommand; events: SessionEvent[]; /** Committed wakes of a session waiting on this result. Signal them after * commit so the wait resumes now instead of on the dispatcher's next tick. */ wakes: SessionWorkflowWake[]; }; export async function settleConnectedMachineSessionBackgroundCommand( db: Database, input: { failure?: SessionBackgroundCommand["failure"]; backgroundChildrenStopped?: boolean | undefined; accountId: string; workspaceId: string; sessionId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; outcome: "exited" | "lost"; exitCode: number | null; reason: string; }, ): Promise { const mutation = backgroundCommandTerminalMutation(input); const command = await settleConnectedMachineSessionBackgroundCommandWithMutation( db, input, mutation, ); return command ? { command, events: [...mutation.events], wakes: [...mutation.wakes] } : null; } export async function settleClaimedConnectedMachineBackgroundCommand( db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim }, ): Promise<{ settled: boolean; events: SessionEvent[]; wakes: SessionWorkflowWake[] }> { const mutation = backgroundCommandTerminalMutation({ accountId: input.claim.accountId, workspaceId: input.claim.workspaceId, sessionId: input.claim.sessionId, }); const settled = await settleClaimedConnectedMachineBackgroundCommandWithMutation( db, input, mutation, ); return { settled, events: settled ? [...mutation.events] : [], wakes: settled ? [...mutation.wakes] : [], }; } /** Shared push/reaper terminal commit after output capture. A concurrent attached * owner finishing the same command is success, not a reconciliation failure. */ export async function settleCollectedConnectedMachineBackgroundCommand( db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; proof: ConnectedMachineBackgroundCommandProof; receipt?: ConnectedCommandOutputReceipt | undefined; publish?: ((events: SessionEvent[]) => Promise) | undefined; /** Signals a committed wake of a session waiting on this result. */ wake?: ((wake: SessionWorkflowWake) => Promise) | undefined; }, ): Promise { const terminal = async () => { const command = await getSessionBackgroundCommand(db, input.claim); return command?.state === "exited" || command?.state === "lost" ? command : null; }; let alreadyTerminal = false; if (!input.claim.proof) { try { await recordConnectedMachineBackgroundCommandProof(db, input); } catch (error) { if (!(await terminal())) throw error; alreadyTerminal = true; } } const settlement = alreadyTerminal ? { settled: false, events: [], wakes: [] } : await settleClaimedConnectedMachineBackgroundCommand(db, input); const command = settlement.settled ? null : await terminal(); if (!settlement.settled && !command) throw new Error("Connected command settlement lost its exact claim or proof"); try { if ( input.proof.outcome === "exited" && input.receipt && input.proof.exitCode !== null && (settlement.settled || (command?.state === "exited" && command.exitCode === input.proof.exitCode)) ) { await recordConnectedCommandOutputConsumption(db, { ...input.claim, receipt: input.receipt, exitCode: input.proof.exitCode, }); } } finally { // A custody-checkpoint error must never suppress already committed fanout. try { if (settlement.events.length) await input.publish?.(settlement.events); } finally { await signalBackgroundCommandWakes(settlement.wakes, input.wake); } } return settlement.settled; } /** How long a settlement caller waits for its wake signals before it moves on. */ export const BACKGROUND_COMMAND_WAKE_SIGNAL_TIMEOUT_MS = 5_000; /** * Signal the committed wakes of a terminal background-command settlement, one * per session and revision, concurrently and for at most `timeoutMs`. A failed, * slow or missing signal is not an error: the outbox row stays undelivered and * the periodic wake dispatcher delivers it. `onError` sees each failure. */ export async function signalBackgroundCommandWakes( wakes: readonly SessionWorkflowWake[] | undefined, wake: ((wake: SessionWorkflowWake) => Promise) | null | undefined, options: { timeoutMs?: number; onError?: (error: unknown, wake: SessionWorkflowWake) => void; } = {}, ): Promise { if (!wake || !wakes?.length) return; const unique = new Map(); for (const pending of wakes) { const key = `${pending.workspaceId}:${pending.sessionId}`; const seen = unique.get(key); if (!seen || seen.wakeRevision < pending.wakeRevision) unique.set(key, pending); } const timeoutMs = options.timeoutMs ?? BACKGROUND_COMMAND_WAKE_SIGNAL_TIMEOUT_MS; let timer: ReturnType | undefined; const timedOut = new Promise((resolve) => { timer = setTimeout(resolve, timeoutMs); }); const report = (error: unknown, pending: SessionWorkflowWake) => { try { options.onError?.(error, pending); } catch { // Reporting is best effort too. } }; const unsettled = new Set(unique.values()); try { await Promise.race([ Promise.all( [...unique.values()].map((pending) => Promise.resolve() .then(() => wake(pending)) .then( () => undefined, (error: unknown) => report(error, pending), ) .finally(() => unsettled.delete(pending)), ), ), timedOut, ]); } finally { clearTimeout(timer); } for (const pending of unsettled) { report(new Error(`wake signal still pending after ${timeoutMs} ms`), pending); } } /** * Mark this child's now-stale pending notices on the parent `superseded` and * return their ids. Rules (producer-side, under the parent session lock): * a newer `child_progress` from the same child supersedes every older pending * one; a `child_requires_action_resolved` supersedes the pending * `child_requires_action` of the same exact (child, turn, generation), because * one accepted response advances that blocked boundary and a later re-freeze * is a new generation with a new notice. Any other kind supersedes nothing. */ async function supersedeStaleChildLifecycleNoticesInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; inserted: Pick< typeof schema.sessionSystemUpdates.$inferSelect, "id" | "kind" | "sourceId" | "payload" | "payloadCodecVersion" >; }, ): Promise { if (input.inserted.kind === "child_progress") { const rows = await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "child_progress"), eq(schema.sessionSystemUpdates.sourceId, input.inserted.sourceId), eq(schema.sessionSystemUpdates.state, "pending"), ne(schema.sessionSystemUpdates.id, input.inserted.id), ), ) .returning({ id: schema.sessionSystemUpdates.id }); return rows.map((row) => row.id).sort(); } if (input.inserted.kind === "child_requires_action_resolved") { const payload = SessionSystemUpdatePayload.parse( fromPostgresLosslessJson(input.inserted.payload, input.inserted.payloadCodecVersion), ); if (payload.type !== "child_requires_action_resolved") return []; const rows = await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "child_requires_action"), eq(schema.sessionSystemUpdates.sourceId, input.inserted.sourceId), eq(schema.sessionSystemUpdates.state, "pending"), sql`${schema.sessionSystemUpdates.payload} ->> 'childTurnId' = ${payload.childTurnId}`, sql`${schema.sessionSystemUpdates.payload} ->> 'childTurnGeneration' = ${String(payload.childTurnGeneration)}`, ), ) .returning({ id: schema.sessionSystemUpdates.id }); return rows.map((row) => row.id).sort(); } if (input.inserted.kind === "child_terminal_result") { // The child reached a terminal boundary: its still-pending progress and // capacity-wait notices describe a state that no longer exists. A pending // child_requires_action is deliberately NOT superseded here: terminal // delivery is unordered against notice creation (a stale idle result // delivered late by the reaper may land after the child got a new prompt // and froze again), and every terminal path already emits its own exact // (child, turn, generation) resolution, which is the ordered supersession. // (A pending resolution stays: it is already informational.) const rows = await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), inArray(schema.sessionSystemUpdates.kind, ["child_progress", "child_waiting_capacity"]), eq(schema.sessionSystemUpdates.sourceId, input.inserted.sourceId), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .returning({ id: schema.sessionSystemUpdates.id }); return rows.map((row) => row.id).sort(); } return []; } function childLifecycleSupersessionReason( kind: string, ): "superseded_by_newer_progress" | "superseded_by_resolution" | "superseded_by_terminal" { if (kind === "child_progress") return "superseded_by_newer_progress"; if (kind === "child_terminal_result") return "superseded_by_terminal"; return "superseded_by_resolution"; } /** * One durable machine input by id, under the ordinary workspace RLS scope. * The row outlives delivery, so a late bounded projection of an already * announced `system.update.pending` event (Slack notification delivery) * resolves the exact typed notice instead of re-deriving it from the * lossy event preview. Read-only: it never mutates or consumes the update. */ export async function getSessionSystemUpdateById( db: Database, workspaceId: string, sessionId: string, updateId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.id, updateId), ), ) .limit(1); return row ? mapSessionSystemUpdate(row) : null; }); } /** * Whether the parent already holds a `child_requires_action_resolved` notice * for one exact blocked boundary. Read-only, under the ordinary workspace RLS * scope, and answered entirely from the PARENT's own rows: the child session is * never read. * * A resolution supersedes a still-pending `child_requires_action` in the same * commit, but a notice already claimed into a parent turn is `delivered` and * keeps that state forever. A late reader (Slack delivery running behind a * widened retry window) therefore cannot decide staleness from `state` alone. * One accepted response advances that exact (child, turn, generation) boundary * - a re-freeze is a new generation and a new notice - so the presence of the * resolution row in any state is the durable "no longer blocked" fact. */ export async function childRequiresActionResolutionExists( db: Database, workspaceId: string, sessionId: string, boundary: { childSessionId: string; childTurnId: string; childTurnGeneration: number; }, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.sessionSystemUpdates.id }) .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.kind, "child_requires_action_resolved"), eq(schema.sessionSystemUpdates.sourceId, boundary.childSessionId), sql`${schema.sessionSystemUpdates.payload} ->> 'childTurnId' = ${boundary.childTurnId}`, sql`${schema.sessionSystemUpdates.payload} ->> 'childTurnGeneration' = ${String( boundary.childTurnGeneration, )}`, ), ) .limit(1); return row !== undefined; }); } export async function listOutstandingSessionSystemUpdates( db: Database, workspaceId: string, sessionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .orderBy(asc(schema.sessionSystemUpdates.createdAt), asc(schema.sessionSystemUpdates.id)); return rows.map(mapSessionSystemUpdate); }); } /** Internal updates atomically attached when this inference was claimed. */ export async function listSessionSystemUpdatesForTurn( db: Database, workspaceId: string, sessionId: string, turnId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.sessionSystemUpdates) .where( and( eq(schema.sessionSystemUpdates.workspaceId, workspaceId), eq(schema.sessionSystemUpdates.sessionId, sessionId), eq(schema.sessionSystemUpdates.deliveredTurnId, turnId), eq(schema.sessionSystemUpdates.state, "delivered"), ), ) .orderBy( // A Steer is the authoritative replacement direction even when its // transaction started before, but committed after, a concurrently // materialized goal continuation. Keep all coalesced work in one // metered inference, but render the winning Steer last so transaction // timestamps cannot let an older goal prompt override it. sql`case when ${schema.sessionSystemUpdates.kind} = 'agent_steer_instruction' then 1 else 0 end`, asc(schema.sessionSystemUpdates.createdAt), asc(schema.sessionSystemUpdates.id), ); return rows.map(mapSessionSystemUpdate); }); } function mapSessionSystemUpdate( row: typeof schema.sessionSystemUpdates.$inferSelect, ): SessionSystemUpdate { return { id: row.id, sessionId: row.sessionId, kind: row.kind as SessionSystemUpdateKind, classification: row.classification as SystemUpdateClassification, sourceId: row.sourceId, dedupeKey: row.dedupeKey, summary: fromPostgresLosslessText(row.summary, row.summaryCodecVersion), payload: SessionSystemUpdatePayload.parse( fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), ), lineage: row.lineage, state: row.state as SessionSystemUpdateState, deliveredTurnId: row.deliveredTurnId, deliveredHistoryItemId: row.deliveredHistoryItemId, deliveredAt: row.deliveredAt?.toISOString() ?? null, createdAt: row.createdAt.toISOString(), }; } const SESSION_EVENT_RAW_DELTA_TYPE_SET: ReadonlySet = new Set( SESSION_EVENT_RAW_DELTA_TYPES, ); export function sessionEventRawLaneEnabled( value = process.env.OPENGENI_SESSION_EVENT_RAW_LANE_ENABLED, ): boolean { return !["0", "false", "off", "disabled"].includes(value?.trim().toLowerCase() ?? ""); } /** Raw streaming fragments advance the durable sequence, not monitoring activity. */ function sessionEventTypesAdvanceActivity(inputs: ReadonlyArray<{ type: string }>): boolean { return inputs.some((input) => !SESSION_EVENT_RAW_DELTA_TYPE_SET.has(input.type)); } function sessionMutationAdvancesActivity(update: { resources?: ResourceRef[]; removedRepositories?: SessionRemovedRepository[]; tools?: ToolRef[]; firstPartyMcpTools?: FirstPartyMcpToolName[]; agentConfig?: ResolvedAgentConfig | null; instructions?: string | null; skills?: SessionSkill[]; toolPolicy?: SessionToolPolicy; toolPolicyVersion?: number; expectedToolPolicyVersion?: number; model?: string; metadata?: Record; status?: SessionStatus; activeTurnId?: string | null; }): boolean { return Object.values(update).some((value) => value !== undefined); } async function withWorkspaceSessionEventActivityRls( db: Database, workspaceId: string, advancesActivity: boolean, fn: (db: Database) => Promise, ): Promise { return advancesActivity ? await withWorkspaceSessionActivityRls(db, workspaceId, fn) : await withWorkspaceRls(db, workspaceId, fn); } async function retryWorkspaceSessionEventActivityPersistence( db: Database, workspaceId: string, advancesActivity: boolean, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise, ): Promise { return advancesActivity ? await retrySessionActivityRls(db, workspaceId, options, fn) : await retryWorkspacePersistence(db, workspaceId, options, fn); } /** * A raw attempt event can become semantic only after its attempt fence is * locked (for example, a late delta is retained as rejected audit evidence). * Abort that no-activity transaction before any event write and repeat it at * the outer session-activity boundary. The mutation callback is deliberately * transaction-local and idempotent, so the rollback cannot leak an effect. */ class SessionSemanticWriteEscalation extends Error { readonly name = "SessionSemanticWriteEscalation"; } export async function appendSessionEvents( db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[], ): Promise { if (inputs.length === 0) { return []; } const persistence = { stage: "session_events.append_generic", eventTypes: inputs.map((input) => input.type), maxAttempts: 3, }; return await retryWorkspaceSessionEventActivityPersistence( db, workspaceId, sessionEventTypesAdvanceActivity(inputs), persistence, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { const turnIds = inputs .map((input) => input.turnId) .filter((id): id is string => typeof id === "string"); const attemptIds = inputs .map((input) => input.turnAttemptId) .filter((id): id is string => typeof id === "string"); const locks = await lockSessionEventWriteRows(tx as unknown as Database, { rowProjection: "event", workspaceId, controlLock: "none", sessionIds: [sessionId], turnIds, attemptIds, }); const row = locks.sessions[0]; if (!row) { throw new Error(`Session not found: ${sessionId}`); } let sequence = row.lastSequence; const values = inputs.map((input) => ({ accountId: row.accountId, workspaceId: row.workspaceId, sessionId, sequence: ++sequence, type: input.type, payload: input.payload ?? {}, clientEventId: input.clientEventId ?? null, turnId: input.turnId ?? null, turnGeneration: input.turnGeneration ?? null, turnAttemptId: input.turnAttemptId ?? null, turnAssociation: input.turnAssociation ?? (input.turnId ? "current" : null), duplicateOfEventId: input.duplicateOfEventId ?? null, duplicateReason: input.duplicateReason ?? null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt: input.occurredAt ?? new Date(), })); const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(); // Semantic inserts project sequence and activity in the cursor trigger. // Keep the generic raw writer's compatibility projection unchanged. if (!sessionEventTypesAdvanceActivity(values)) { await tx .update(schema.sessions) .set({ lastSequence: sequence }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); } return inserted.map(mapEvent); }); }, ); } export type AcceptSessionApprovalDecisionResult = | { action: "accepted"; event: SessionEvent; events: SessionEvent[]; workflowWakeRevision: number; } | { action: "conflict"; sessionStatus: SessionStatus; reason: SessionApprovalConflictReason; /** What the person reads: why this decision cannot be taken. */ message: string; }; /** * Why a decision was refused. A decision for an approval that is still * undecided is never refused merely because the session is resuming from a * sibling decision of the same pause. */ export type SessionApprovalConflictReason = | "already_decided" | "already_finished" | "turn_ended" | "not_pending"; function approvalConflict( sessionStatus: SessionStatus, reason: SessionApprovalConflictReason, decided?: unknown, ): Extract { const message = reason === "already_decided" ? decided === "reject" ? "This action was already declined." : "This action was already approved." : reason === "already_finished" ? "This action already finished." : reason === "turn_ended" ? "This approval closed: the agent's turn ended before it was decided." : "This approval is no longer waiting for a decision."; return { action: "conflict", sessionStatus, reason, message }; } /** The question round a decision answers; none for an approval without questions. */ function approvalDecisionRound(payload: Record): number | undefined { return typeof payload.elicitationRound === "number" ? payload.elicitationRound : undefined; } /** The question round an approval currently asks; none when it asks no question. */ function pendingApprovalRound(pending: unknown): number | undefined { const elicitation = pending && typeof pending === "object" ? (pending as { elicitation?: unknown }).elicitation : undefined; if (elicitation === undefined) return undefined; const parsed = McpElicitationApprovalRequest.safeParse(elicitation); return parsed.success ? parsed.data.round : undefined; } /** * The newest recorded decision for one approval and question round, within * the live turn when there is one. Call ids are unique within a turn, and an * MCP server asking again under the same id asks a new round, so this is the * decision the person already made for exactly what they see. */ async function latestApprovalDecisionForRound( tx: Database, input: { workspaceId: string; sessionId: string; approvalId: string; round: number | undefined; /** The live turn: call ids are only unique within one turn. */ turnId?: string; }, ): Promise<{ event: typeof schema.sessionEvents.$inferSelect; payload: Record; } | null> { const rows = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "user.approvalDecision"), input.turnId === undefined ? undefined : eq(schema.sessionEvents.turnId, input.turnId), sql`${schema.sessionEvents.payload} ->> 'approvalId' = ${input.approvalId}`, ), ) .orderBy(desc(schema.sessionEvents.sequence)) .limit(16); for (const row of rows) { const payload = sessionEventPayloadRecord(row.payload, row.payloadCodecVersion); if (payload.approvalId !== input.approvalId) continue; if (approvalDecisionRound(payload) !== input.round) continue; return { event: row, payload }; } return null; } /** The answer to an approval's MCP server questions does not fit their forms. */ export class SessionApprovalAnswerError extends Error { override readonly name = "SessionApprovalAnswerError"; } /** * The decision payload to record for one pending approval. An approval with * MCP server questions records the complete answer (the forms' defaults plus * what the person entered), checked against each form; a rejection carries no * answer. Approving must name the question's round: the server can ask again * under the same approval id, so an approval sent for an earlier question, or * from a surface that never showed this one, must not answer it. A rejection * needs no round; declining is always safe to deliver. `content` or a round * for an approval without questions is refused. */ function approvalDecisionPayloadWithAnswer( pending: unknown, payload: Record, ): Record { const elicitation = pending && typeof pending === "object" ? (pending as { elicitation?: unknown }).elicitation : undefined; const { content, elicitationRound, ...withoutAnswer } = payload; if (elicitation === undefined) { if (content !== undefined || elicitationRound !== undefined) { throw new SessionApprovalAnswerError("This approval has no questions to answer"); } return payload; } const request = McpElicitationApprovalRequest.parse(elicitation); // A rejection needs no round from the client, but records the round it // declined so a later question under the same call id is never taken as // already declined. if (payload.decision !== "approve") return { ...withoutAnswer, elicitationRound: request.round }; if (elicitationRound !== request.round) { throw new SessionApprovalAnswerError( elicitationRound === undefined ? `${request.server} asked a question about this call; answer it with elicitationRound ${request.round}` : `${request.server} has asked a newer question about this call; answer that one`, ); } const given = content === undefined ? undefined : McpElicitationContent.safeParse(content); if (given && !given.success) { throw new SessionApprovalAnswerError("The answer is not a set of form values"); } const resolution = resolveMcpElicitationContent(request, given?.data); if (!resolution.ok) throw new SessionApprovalAnswerError(resolution.problem); return { ...withoutAnswer, elicitationRound: request.round, content: resolution.content }; } /** * Accept one decision for an approval still open in the live turn's latest * pause, whether the session waits or is resuming from a sibling decision. * The same decision again is idempotent; a different one is refused as * already decided. The session and active turn are locked with the append so * concurrent Pause, Steer, and duplicate decisions stay serialized with the * worker's settlement. */ export async function acceptSessionApprovalDecision( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; payload: Record; /** Validated/encrypted by the API; never copied into the decision event. */ mcpCredentialUpdates?: UpdateSessionMcpServerCredentialsInput[]; /** Bounded decider kind for the parent's resolution notice; `human` when omitted. */ respondedByKind?: ChildRequiresActionRespondedByKind; /** * The decider is signed in where an app-action change may be confirmed: * the app itself, or an embed the deployment opted in; never a key, chat * integration or other token carrying their identity. Only such a * decision confirms an app-action change. */ decidedBySignedInPerson?: boolean; clientEventId?: string | null; interactionIntervention?: { interventionId: string; operationId: string; expectedVersion: number; outcome: "completed" | "dismissed"; }; }, ): Promise { // Defense in depth for internal callers: this field is ingress-only even // when a caller accidentally passes the complete public request payload. const { mcpCredentialUpdates: _writeOnlyCredentials, ...requestedPayload } = input.payload; let payload = requestedPayload; return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const sessionIds = await sessionIdsWithParentTx( tx as unknown as Database, input.workspaceId, input.sessionId, ); const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "none", sessionIds, }); const session = locks.sessions.find((row) => row.id === input.sessionId); if (!session) throw new Error(`Session not found: ${input.sessionId}`); if (input.clientEventId) { const [existing] = await tx .select() .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.clientEventId, input.clientEventId), ), ) .limit(1); if (existing) { const existingPayload = sessionEventPayloadRecord( existing.payload, existing.payloadCodecVersion, ); if ( existing.type !== "user.approvalDecision" || existingPayload.approvalId !== payload.approvalId || existingPayload.decision !== payload.decision ) { throw new Error("clientEventId belongs to a different approval decision"); } const workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, reason: "approval_decision", }, ); return { action: "accepted", event: mapEvent(existing), events: [], workflowWakeRevision, } as const; } } const [turnPreview] = session.activeTurnId ? await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sessionId), eq(schema.sessionTurns.id, session.activeTurnId), ), ) .limit(1) : []; const turn = turnPreview ? ( await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: [turnPreview.id], }) ).turns[0] : undefined; if (turnPreview && !turn) { throw new Error(`Active turn disappeared: ${turnPreview.id}`); } const sessionStatus = session.status as SessionStatus; const approvalId = payload.approvalId; if (typeof approvalId !== "string") { return approvalConflict(sessionStatus, "not_pending"); } // Every approval of the turn's latest pause stays decidable until its // call settles, also while the turn resumes from a sibling decision: // a pause's decisions are applied together, and one recorded while // the turn resumes is applied by the next resume. const liveTurn = turn && session.activeTurnId === turn.id && !isTerminalSessionTurnStatus(turn.status as SessionTurnStatus) ? turn : undefined; const [runState] = liveTurn ? await tx .select({ turnId: schema.agentRunStates.turnId, pendingApprovals: schema.agentRunStates.pendingApprovals, pendingApprovalsCodecVersion: schema.agentRunStates.pendingApprovalsCodecVersion, }) .from(schema.agentRunStates) .where( and( eq(schema.agentRunStates.workspaceId, input.workspaceId), eq(schema.agentRunStates.sessionId, input.sessionId), eq(schema.agentRunStates.turnId, liveTurn.id), ), ) .orderBy(desc(schema.agentRunStates.stateVersion)) .limit(1) : []; const pendingApproval = runState ? fromPostgresLosslessJson( runState.pendingApprovals, runState.pendingApprovalsCodecVersion, ).find((pending) => approvalIdentifier(pending) === approvalId) : undefined; const [pendingCall] = liveTurn && pendingApproval !== undefined ? await tx .select({ interruptionKind: schema.sessionPendingToolCalls.interruptionKind, hasResult: sql`${schema.sessionPendingToolCalls.resultItem} is not null`, }) .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.turnId, liveTurn.id), eq(schema.sessionPendingToolCalls.callId, approvalId), ), ) .limit(1) : []; const callSettled = pendingCall?.hasResult === true; const waiting = sessionStatus === "requires_action" && liveTurn?.status === "requires_action"; // The same decision again (a double click, a retry after a lost // response) is the decision already recorded: accepted, nothing new. const round = pendingApproval !== undefined ? pendingApprovalRound(pendingApproval) : approvalDecisionRound(payload); const prior = await latestApprovalDecisionForRound(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, approvalId, round, ...(liveTurn ? { turnId: liveTurn.id } : {}), }); if (prior) { // A decision the waiting pause should already have applied, for a // call that is still open, was lost (a worker from before this // change resumed only its own trigger): take the new one instead. const [trigger] = waiting && liveTurn && pendingCall && !callSettled ? await tx .select({ sequence: schema.sessionEvents.sequence }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.id, liveTurn.triggerEventId), ), ) .limit(1) : []; const lost = trigger !== undefined && prior.event.sequence <= trigger.sequence; if (!lost) { // A repeat that carries credentials to store is a different // response: the recorded one already decided, so refuse it // rather than report its credentials as stored. if ( prior.payload.decision !== payload.decision || (input.mcpCredentialUpdates?.length ?? 0) > 0 ) { return approvalConflict(sessionStatus, "already_decided", prior.payload.decision); } const workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, reason: "approval_decision", }, ); return { action: "accepted", event: mapEvent(prior.event), events: [], workflowWakeRevision, } as const; } } if (!liveTurn) return approvalConflict(sessionStatus, "turn_ended"); if (pendingApproval === undefined) return approvalConflict(sessionStatus, "not_pending"); if (callSettled) return approvalConflict(sessionStatus, "already_finished"); if (!waiting) { // Resuming: only a call the next resume can still apply. A model // tool's open call, or a programmatic call still waiting on review. const resumable = pendingCall !== undefined ? pendingCall.interruptionKind === "approval" || pendingCall.interruptionKind === "interaction_intervention" : isGitHubGatewayApprovalId(approvalId) ? // A gh request held by the GitHub gateway: still undecided. ( await tx .select({ id: schema.connectorActionRequests.id }) .from(schema.connectorActionRequests) .where( and( eq(schema.connectorActionRequests.workspaceId, input.workspaceId), eq(schema.connectorActionRequests.sessionId, input.sessionId), eq(schema.connectorActionRequests.turnId, liveTurn.id), eq(schema.connectorActionRequests.approvalId, approvalId), eq(schema.connectorActionRequests.status, "pending"), ), ) .limit(1) ).length > 0 : // Programmatic approval ids are operation UUIDs. UUID_PATTERN.test(approvalId) && ( await tx .select({ operationId: schema.sessionAttemptCodemodeCalls.operationId }) .from(schema.sessionAttemptCodemodeCalls) .where( and( eq(schema.sessionAttemptCodemodeCalls.workspaceId, input.workspaceId), eq(schema.sessionAttemptCodemodeCalls.sessionId, input.sessionId), eq(schema.sessionAttemptCodemodeCalls.turnId, liveTurn.id), eq(schema.sessionAttemptCodemodeCalls.operationId, approvalId), eq(schema.sessionAttemptCodemodeCalls.state, "waiting_for_approval"), ), ) .limit(1) ).length > 0; if (!resumable) return approvalConflict(sessionStatus, "not_pending"); } // The call runs on the turn's frozen accounts, never the approver's: // approving one that runs on someone's own account is theirs alone. // Checked before the answer, so a non-owner always learns who decides. if (payload.decision === "approve") { const owner = await pendingApprovalAccountOwner(tx as unknown as Database, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: liveTurn.id, approvalId, }); if (owner !== null && owner.subjectId !== input.subjectId) { throw new SessionApprovalForbiddenError(owner); } } payload = approvalDecisionPayloadWithAnswer(pendingApproval, payload); if (input.interactionIntervention) { const expectedInteractionDecision = input.interactionIntervention.outcome === "completed" ? "approve" : "reject"; if (payload.decision !== expectedInteractionDecision) { throw new Error("Interaction outcome does not match its approval decision"); } const [intervention] = await tx .select({ originatingSessionId: schema.interactionInterventions.originatingSessionId, originatingToolCallId: schema.interactionInterventions.originatingToolCallId, }) .from(schema.interactionInterventions) .where( and( eq(schema.interactionInterventions.workspaceId, input.workspaceId), eq( schema.interactionInterventions.id, input.interactionIntervention.interventionId, ), ), ) .limit(1); if ( !intervention || intervention.originatingSessionId !== input.sessionId || intervention.originatingToolCallId !== approvalId ) { throw new Error("Interaction intervention does not belong to this approval"); } const resolved = await resolveInteractionInterventionInTransaction( tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, actorSubjectId: input.subjectId, interventionId: input.interactionIntervention.interventionId, operationId: input.interactionIntervention.operationId, expectedVersion: input.interactionIntervention.expectedVersion, outcome: input.interactionIntervention.outcome, }, ); if ( (payload.decision === "approve" && resolved.intervention.status !== "completed") || (payload.decision === "reject" && resolved.intervention.status === "completed") ) { // A response exactly on the deadline can discover expiration only // while holding the row lock. Roll the whole transaction back so // the session never approves a tool whose intervention expired. throw new InteractionResourceStateError( "Interaction intervention expired before this response", ); } } await applySessionResponseMcpCredentialUpdatesInTransaction( tx as unknown as Database, input, ); const [event] = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: liveTurn.id, turnGeneration: liveTurn.executionGeneration, turnAssociation: "current", sequence: session.lastSequence + 1, type: "user.approvalDecision", payload, clientEventId: input.clientEventId ?? null, }, "payload", "payloadCodecVersion", ), ) .returning(); if (!event) throw new Error("Failed to append approval decision"); const approvalDecision = payload.decision; if (approvalDecision === "approve" || approvalDecision === "reject") { await enqueueChildRequiresActionResolvedOutboxTx( tx as unknown as Database, input.workspaceId, session, { turnId: liveTurn.id, turnGeneration: liveTurn.executionGeneration, requestId: null, approvalId, outcome: approvalDecision === "approve" ? "approved" : "rejected", respondedByKind: input.respondedByKind ?? "human", }, ); } if (approvalDecision === "approve" || approvalDecision === "reject") { const [connectorRequest] = await tx .update(schema.connectorActionRequests) .set({ status: approvalDecision === "approve" ? "approved" : "rejected", decision: approvalDecision, decisionBySubjectId: boundedConnectorActionText( input.subjectId, "approval actor", 1024, ), decisionByKind: input.respondedByKind ?? "human", decisionBySignedInPerson: input.decidedBySignedInPerson === true, decisionEventId: event.id, decidedAt: event.occurredAt, updatedAt: new Date(), }) .where( and( eq(schema.connectorActionRequests.workspaceId, input.workspaceId), eq(schema.connectorActionRequests.sessionId, input.sessionId), eq(schema.connectorActionRequests.turnId, liveTurn.id), eq(schema.connectorActionRequests.approvalId, approvalId), eq(schema.connectorActionRequests.status, "pending"), ), ) .returning(); if (connectorRequest) { await insertConnectorActionAudit(tx as unknown as Database, { row: connectorRequest, action: "connector.action.approval_decided", subjectId: input.subjectId, extra: { decision: approvalDecision, ...(connectorRequest.inputRound > 0 ? { inputRound: connectorRequest.inputRound } : {}), }, }); } } await tx .update(schema.sessions) .set({ lastSequence: session.lastSequence + 1, updatedAt: new Date(), }) .where(eq(schema.sessions.id, session.id)); const workflowWakeRevision = await enqueueSessionWorkflowWakeInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId: input.workspaceId, sessionId: session.id, temporalWorkflowId: session.temporalWorkflowId ?? `session-${session.id}`, reason: "approval_decision", }, ); const mapped = mapEvent(event); return { action: "accepted", event: mapped, events: [mapped], workflowWakeRevision, } as const; }), ); } export type ExpireSessionInteractionInterventionResult = { action: "expired" | "stale" | "not_found"; events: SessionEvent[]; /** Content-free facts for telemetry on the expired transition only. */ intervention?: { kind: string; createdAt: Date }; }; /** * What the scheduler's approval timeout would answer for this exact * requires_action turn: the first pending tool approval, else the first pending * structured human-input request that a system response may settle (a Skill * review needs a person, so it is never timed out). Null means the timeout has * nothing it may settle, so no timer is offered for it. */ async function scheduledHumanWaitTargetInRlsContext( scopedDb: Database, workspaceId: string, turn: { id: string; sessionId: string; executionGeneration: number }, ): Promise< | { kind: "approval"; approvalId: string; elicitationRound?: number } | { kind: "input"; requestId: string; denyQuestionIds: string[] | null } | null > { const [runState] = await scopedDb .select({ pendingApprovals: schema.agentRunStates.pendingApprovals, pendingApprovalsCodecVersion: schema.agentRunStates.pendingApprovalsCodecVersion, }) .from(schema.agentRunStates) .where( and( eq(schema.agentRunStates.workspaceId, workspaceId), eq(schema.agentRunStates.sessionId, turn.sessionId), eq(schema.agentRunStates.turnId, turn.id), ), ) .orderBy(desc(schema.agentRunStates.stateVersion)) .limit(1); const pendingApprovals = runState ? fromPostgresLosslessJson(runState.pendingApprovals, runState.pendingApprovalsCodecVersion) : []; const pendingApproval = (Array.isArray(pendingApprovals) ? pendingApprovals : []).find( (pending) => { const id = approvalIdentifier(pending); return typeof id === "string" && id.length > 0; }, ); const approvalId = pendingApproval ? approvalIdentifier(pendingApproval) : undefined; if (typeof approvalId === "string") { // An MCP server can ask again under the same approval id after a // timeout's decline; each of its questions times out on its own. const question = McpElicitationApprovalRequest.safeParse( (pendingApproval as { elicitation?: unknown }).elicitation, ); return { kind: "approval", approvalId, ...(question.success ? { elicitationRound: question.data.round } : {}), }; } const requests = await scopedDb .select({ id: schema.sessionHumanInputRequests.id, questions: schema.sessionHumanInputRequests.questions, }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, workspaceId), eq(schema.sessionHumanInputRequests.sessionId, turn.sessionId), eq(schema.sessionHumanInputRequests.turnId, turn.id), eq(schema.sessionHumanInputRequests.turnGeneration, turn.executionGeneration), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), ), ) .orderBy( asc(schema.sessionHumanInputRequests.createdAt), asc(schema.sessionHumanInputRequests.id), ) .limit(16); const request = requests.find( (candidate) => !candidate.questions.some((question) => question.skillReview != null), ); if (!request) return null; // Secret approval cards can't be skipped; the timeout denies them, as it // rejects a tool approval. const approvalCards = request.questions.every( (question) => secretUseApprovalIdFromQuestionId(question.id) !== null, ); return { kind: "input", requestId: request.id, denyQuestionIds: approvalCards ? request.questions.map((question) => question.id) : null, }; } /** * The scheduled-run approval timeout deadline of this requires_action turn, when * the task set one and there is something it may settle. */ async function scheduledHumanWaitDeadlineInRlsContext( scopedDb: Database, workspaceId: string, turn: { id: string; sessionId: string; executionGeneration: number; scheduledTaskRunId: string | null; }, ): Promise<{ runId: string; expiresAt: string } | null> { if (!turn.scheduledTaskRunId) return null; const [wait] = await scheduledRunHumanWaitsInRlsContext(scopedDb, workspaceId, { turnId: turn.id, }); if (!wait?.expiresAt || wait.runId !== turn.scheduledTaskRunId) return null; const target = await scheduledHumanWaitTargetInRlsContext(scopedDb, workspaceId, turn); return target ? { runId: wait.runId, expiresAt: wait.expiresAt } : null; } export type ExpireScheduledRunHumanWaitResult = { action: "expired" | "stale" | "not_found"; events: SessionEvent[]; }; /** * The scheduler's approval timeout for one scheduled run's turn: when the * task's frozen `approvalTimeoutSeconds` elapsed with no person answering, * reject the first pending approval (or skip the first pending structured * question) through the exact same acceptance boundary a person uses, as a * clearly labelled system decision with a deterministic client event id. It * re-derives the deadline from durable facts and never acts early; a race with * a person's answer settles as `stale`. Remaining approvals surface as a new * wait whose deadline has already passed, so they are rejected in turn. */ export async function expireScheduledRunHumanWait( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; runId: string; }, ): Promise { const snapshot = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [turn] = await scopedDb .select({ id: schema.sessionTurns.id, sessionId: schema.sessionTurns.sessionId, executionGeneration: schema.sessionTurns.executionGeneration, scheduledTaskRunId: schema.sessionTurns.scheduledTaskRunId, }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.id, input.turnId), ), ) .limit(1); if (!turn || turn.sessionId !== input.sessionId || turn.scheduledTaskRunId !== input.runId) { return null; } const [wait] = await scheduledRunHumanWaitsInRlsContext(scopedDb, input.workspaceId, { turnId: turn.id, }); if (!wait?.expiresAt) return null; const target = await scheduledHumanWaitTargetInRlsContext(scopedDb, input.workspaceId, turn); return target ? { turn, wait, target } : null; }, ); if (!snapshot) return { action: "not_found", events: [] }; if (Date.parse(snapshot.wait.expiresAt!) > Date.now()) return { action: "stale", events: [] }; const { turn, wait, target } = snapshot; const minutes = Math.max(1, Math.round((wait.timeoutSeconds ?? 0) / 60)); const clientEventId = `${SCHEDULED_HUMAN_WAIT_TIMEOUT_CLIENT_EVENT_PREFIX}${createHash("sha256") .update( `${turn.id}\0${turn.executionGeneration}\0${target.kind}\0${ target.kind === "approval" ? target.approvalId : target.requestId }${ target.kind === "approval" && target.elicitationRound !== undefined ? `\0${target.elicitationRound}` : "" }`, "utf8", ) .digest("hex") .slice(0, 32)}`; if (target.kind === "approval") { const result = await acceptSessionApprovalDecision(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, subjectId: "system:scheduled-approval-timeout", respondedByKind: "system", payload: { approvalId: target.approvalId, decision: "reject", message: `Rejected automatically by the scheduler: no person decided within this scheduled task's approval timeout (${minutes} min).`, }, clientEventId, }); return result.action === "accepted" ? { action: "expired", events: result.events } : { action: "stale", events: [] }; } const result = await acceptSessionHumanInputResponse(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, requestId: target.requestId, response: target.denyQuestionIds ? { outcome: "answered", answers: target.denyQuestionIds.map((questionId) => ({ questionId, values: ["deny"], })), } : { outcome: "skipped" }, respondedBy: "system:scheduled-approval-timeout", respondedByKind: "system", clientEventId, }); return result.action === "accepted" ? { action: "expired", events: result.events } : { action: "stale", events: [] }; } function deterministicSystemUuid(seed: string): string { const bytes = createHash("sha256").update(seed, "utf8").digest().subarray(0, 16); bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50; bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } /** * Expire one model-owned intervention through the same exact approval boundary * as a human rejection. The resource settlement and rejection event commit * together inside acceptSessionApprovalDecision; a race with a human response * becomes an event-free stale result. */ export async function expireSessionInteractionIntervention( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; interventionId: string; }, ): Promise { const intervention = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.interactionInterventions.id, kind: schema.interactionInterventions.kind, createdAt: schema.interactionInterventions.createdAt, status: schema.interactionInterventions.status, version: schema.interactionInterventions.version, expiresAt: schema.interactionInterventions.expiresAt, originatingSessionId: schema.interactionInterventions.originatingSessionId, originatingToolCallId: schema.interactionInterventions.originatingToolCallId, }) .from(schema.interactionInterventions) .where( and( eq(schema.interactionInterventions.workspaceId, input.workspaceId), eq(schema.interactionInterventions.id, input.interventionId), ), ) .limit(1); return row ?? null; }, ); if ( !intervention || intervention.originatingSessionId !== input.sessionId || !intervention.originatingToolCallId ) { return { action: "not_found", events: [] }; } if (intervention.status !== "open" || intervention.expiresAt.getTime() > Date.now()) { return { action: "stale", events: [] }; } const result = await acceptSessionApprovalDecision(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, subjectId: "system:expired", respondedByKind: "system", payload: { approvalId: intervention.originatingToolCallId, decision: "reject", }, clientEventId: `system:interaction-intervention-expired:${intervention.id}`, interactionIntervention: { interventionId: intervention.id, operationId: deterministicSystemUuid( `opengeni:interaction-intervention-expire:${intervention.id}`, ), expectedVersion: intervention.version, outcome: "dismissed", }, }); return result.action === "accepted" ? { action: "expired", events: result.events, intervention: { kind: intervention.kind, createdAt: intervention.createdAt }, } : { action: "stale", events: [] }; } /** * Durable attempt fence for activity-produced events. A cancelled or replaced * attempt may still flush SDK callbacks after Temporal cancellation; those late * events remain associated with their producer in logs but are not admitted to * the current durable timeline once the turn row moved generation or terminal. */ export async function appendSessionEventsForTurnAttempt( db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], observer?: SessionEventAppendObserver, mutate?: SessionEventMutationInput, ): Promise<{ events: SessionEvent[]; accepted: boolean; canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[]; }> { if (inputs.length === 0) { return { events: [], accepted: true, canonicalStartupMilestones: [] }; } const result = await mutateAndAppendSessionEventsForTurnAttempt( db, workspaceId, sessionId, turnId, executionGeneration, attemptId, inputs, mutate, observer, ); return { events: result.events, accepted: result.accepted, canonicalStartupMilestones: result.canonicalStartupMilestones, }; } /** * A connection card's events with the notice that tells the person they are * needed (`connectionCardNotice`), after the card so the card stays first. */ export function withConnectionCardNotice( events: readonly T[], ): Array { return events.flatMap((event) => { if (event.type !== "tool.auth_needed") return [event]; const parsed = ToolAuthNeededPayload.safeParse(event.payload); const notice = parsed.success ? connectionCardNotice(parsed.data) : null; return notice ? [event, { type: "session.notification.posted" as const, payload: notice }] : [event]; }); } /** * Append a capability card for the calling turn unless that turn already shows * a current card for the same capability (and, for a card that names the * machine it asks for, the same machine, and for a card with a purpose such as * the Chrome setup card, the same purpose). The lookup runs inside the attempt * write fence, which locks the session row, so parallel callers in one turn * cannot both append. Cards for other capabilities are never consulted. * Only the same kind of card counts: a first connection, or a reconnect of the * same connection. With `sinceLatestMessage`, a current card of any turn since * the person's latest message counts instead of only this turn's: repeated * requests do not stack cards while the person has not written, and a card * from before their latest message, which may be stale, is not reused. A chat * with no message from a person (a scheduled run) reuses only this turn's. */ export async function appendTurnCapabilityCardOnce( db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, capabilityId: string, input: AppendEventInput, requestedSandboxId: string | null = null, options: { sinceLatestMessage?: boolean } = {}, ): Promise<{ events: SessionEvent[]; accepted: boolean; existingEventId: string | null }> { let existingEventId: string | null = null; const payloadPurpose = (input.payload as { purpose?: unknown } | undefined)?.purpose; const purpose = typeof payloadPurpose === "string" ? payloadPurpose : ""; const payloadText = (key: string) => { const value = (input.payload as Record | undefined)?.[key]; return typeof value === "string" ? value : ""; }; const scope = options.sinceLatestMessage ? sql`and coalesce(sequence > ( select max(message.sequence) from session_events message where message.workspace_id = ${workspaceId}::uuid and message.session_id = ${sessionId}::uuid and message.type = 'user.message' ), turn_id = ${turnId}::uuid)` : sql`and turn_id = ${turnId}::uuid`; const result = await mutateAndAppendSessionEventsForTurnAttempt( db, workspaceId, sessionId, turnId, executionGeneration, attemptId, // The card needs the person: its notice reaches the inbox and the phone. withConnectionCardNotice([input]), { rowProjection: "event", mutate: async (tx) => { const [existing] = await rawRows<{ id: string }>( tx, sql` select id from session_events where workspace_id = ${workspaceId}::uuid and session_id = ${sessionId}::uuid ${scope} and type = 'tool.auth_needed' and duplicate_of_event_id is null and (turn_association is null or turn_association = 'current') and payload -> 'capability' ->> 'id' = ${capabilityId} and coalesce(payload ->> 'requestedSandboxId', '') = ${requestedSandboxId ?? ""} and coalesce(payload ->> 'purpose', '') = ${purpose} and coalesce(payload ->> 'reason', '') = ${payloadText("reason")} and coalesce(payload ->> 'connectionId', '') = ${payloadText("connectionId")} order by sequence limit 1 `, ); existingEventId = existing?.id ?? null; return existingEventId === null; }, }, ); return { events: result.events, accepted: result.accepted || existingEventId !== null, existingEventId, }; } export type SessionEventAppendClass = "raw" | "semantic" | "mixed"; /** * Post Opengeni's own approval card for a blocked secret use, in the chat of * the exact attempt that was blocked. The card is a `secret_use_approval` * human-input request: its `session.humanInput.requested` event shows it in * the chat and Slack thread and opens the person's inbox item and phone * notification, and it stays answerable after the turn. A request that * already has a pending card is not posted again, so an identical blocked * use never notifies twice. Returns whether the person has been asked; false * only when this attempt no longer owns the chat or the request was decided. */ export async function postSecretUseApprovalCard( db: Database, input: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; approval: SecretUseApprovalRow; }, ): Promise<{ asked: boolean; requestId: string | null; events: SessionEvent[] }> { const card = secretUseApprovalHumanInput(secretUseApprovalView(input.approval)); const toolCallId = secretUseApprovalQuestionId(input.approval.id); const requestId = crypto.randomUUID(); let existingId: string | null = null; const result = await mutateAndAppendSessionEventsForTurnAttempt( db, input.workspaceId, input.sessionId, input.turnId, input.executionGeneration, input.attemptId, [ { type: "session.humanInput.requested", payload: { request: { id: requestId, questions: card.questions, allowSkip: false, expiresAt: null, origin: "secret_use_approval", }, }, }, ], { rowProjection: "event", // The attempt fence holds the session row, which also serializes the // answer path: the request's state read here is current. mutate: async (tx, fence) => { existingId = null; const [existing] = await tx .select({ id: schema.sessionHumanInputRequests.id }) .from(schema.sessionHumanInputRequests) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), eq(schema.sessionHumanInputRequests.sessionId, input.sessionId), eq(schema.sessionHumanInputRequests.toolCallId, toolCallId), eq(schema.sessionHumanInputRequests.origin, "secret_use_approval"), eq(schema.sessionHumanInputRequests.status, "pending"), ), ) .limit(1); if (existing) { existingId = existing.id; return false; } if (!fence.allowed || !fence.session) return false; const [approval] = await tx .select({ status: schema.secretUseApprovals.status }) .from(schema.secretUseApprovals) .where( and( eq(schema.secretUseApprovals.workspaceId, input.workspaceId), eq(schema.secretUseApprovals.id, input.approval.id), ), ) .limit(1); if (approval?.status !== "pending") return false; const inserted = await tx .insert(schema.sessionHumanInputRequests) .values({ id: requestId, accountId: fence.session.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, turnGeneration: input.executionGeneration, creationAttemptId: input.attemptId, toolCallId, origin: "secret_use_approval", questions: card.questions, allowSkip: false, expiresAt: null, }) .onConflictDoNothing() .returning({ id: schema.sessionHumanInputRequests.id }); return inserted.length > 0; }, }, ); if (result.mutationApplied) return { asked: true, requestId, events: result.events }; return { asked: existingId !== null, requestId: existingId, events: [] }; } export type SessionEventAppendPhase = | "transaction" | "mutation" | "turn_attempt_fence" | "idempotency" | "event_insert" | "projection" | "sequence_update"; export type SessionEventAppendPhaseOutcome = | "ok" | "rejected" | "mutation_skipped" | "projection_skipped" | "escalated" | "error"; export type SessionEventAppendPhaseObservation = { phase: SessionEventAppendPhase; eventClass: SessionEventAppendClass; eventCount: number; outcome: SessionEventAppendPhaseOutcome; durationSeconds: number; }; export type SessionEventAppendObserver = { onPhase?: (observation: SessionEventAppendPhaseObservation) => void; }; export function sessionEventAppendClass( inputs: ReadonlyArray<{ type: string }>, ): SessionEventAppendClass { const rawCount = inputs.filter((input) => SESSION_EVENT_RAW_DELTA_TYPE_SET.has(input.type), ).length; if (rawCount === inputs.length) return "raw"; if (rawCount === 0) return "semantic"; return "mixed"; } export function observeSessionEventAppendPhase( observer: SessionEventAppendObserver | undefined, observation: SessionEventAppendPhaseObservation, ): void { try { observer?.onPhase?.(observation); } catch { // Telemetry must never affect durable event admission or ordering. } } async function runSessionEventAppendPhase( observer: SessionEventAppendObserver | undefined, input: Omit, operation: () => Promise, outcome: (value: T) => SessionEventAppendPhaseOutcome = () => "ok", ): Promise { const startedAt = performance.now(); try { const value = await operation(); observeSessionEventAppendPhase(observer, { ...input, outcome: outcome(value), durationSeconds: Math.max(0, (performance.now() - startedAt) / 1_000), }); return value; } catch (error) { observeSessionEventAppendPhase(observer, { ...input, outcome: error instanceof SessionSemanticWriteEscalation ? "escalated" : "error", durationSeconds: Math.max(0, (performance.now() - startedAt) / 1_000), }); throw error; } } /** * Commit one exact-attempt mutation and its timeline projection together. The * canonical lock prefix runs before the mutation. Callers receive its result: * owned-state mutations must require an allowed fence, while already-incurred * facts may remain durable after ownership loss. A callback returning false * must leave state unchanged; throwing rolls back both mutation and projection. */ export async function mutateAndAppendSessionEventsForTurnAttempt( db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], mutate: SessionEventMutationInput | undefined, observer?: SessionEventAppendObserver, ): Promise<{ events: SessionEvent[]; accepted: boolean; mutationApplied: boolean; canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[]; }> { if (inputs.length === 0) { throw new Error("Atomic attempt mutation requires a timeline projection event"); } const eventTypes = [...new Set(inputs.map((input) => input.type))].sort(); const phaseInput = { eventClass: sessionEventAppendClass(inputs), eventCount: inputs.length, }; const initiallyAdvancesActivity = sessionEventTypesAdvanceActivity(inputs); const rawLaneEnabled = sessionEventRawLaneEnabled(); const persistence = { stage: "session_events.append_for_turn_attempt", eventTypes, maxAttempts: 3, correlationId: crypto.randomUUID(), }; const persist = async (semanticActivity: boolean) => { const startedAt = performance.now(); try { const result = await runIdempotentPersistenceTransaction( persistence, async () => await withWorkspaceSessionEventActivityRls( db, workspaceId, semanticActivity, async (tx) => { // Canonical prefix BEFORE the caller's mutation. The mutation // locks a session-owned row (the Codemode journal row on // terminal settlement); taking it first and the session prefix // second inverted the order of every prefix holder that then // locks the same row (a Codemode re-submit or claim), which // deadlocked POST /codemode/calls in production (40P01). const admission = await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "turn_attempt_fence" }, async () => { const input = { workspaceId, sessionId, turnId, executionGeneration, attemptId, sessionLock: semanticActivity || !rawLaneEnabled ? ("no_key_update" as const) : ("key_share" as const), }; // Preserve plain callbacks' full-row contract. Explicit // checkpoints use the same fence without copying frozen // configuration and authority catalogs across the wire. if (typeof mutate === "function") { const fence = await lockTurnAttemptWriteFenceTx(tx, input); return { fence, applyMutation: () => mutate(tx, fence) }; } const fence = await lockTurnAttemptWriteFenceTx(tx, { ...input, rowProjection: "event", }); return { fence, applyMutation: () => mutate ? mutate.mutate(tx, fence) : Promise.resolve(true), }; }, ({ fence }) => (fence.allowed ? "ok" : "rejected"), ); const fence = admission.fence; const session = fence.session; if (!session) throw new Error(`Session not found: ${sessionId}`); if (!semanticActivity && !fence.allowed) { throw new SessionSemanticWriteEscalation(); } const mutationApplied = await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "mutation" }, admission.applyMutation, (applied) => (applied ? "ok" : "mutation_skipped"), ); if (!mutationApplied) { return { events: [], accepted: false, mutationApplied: false, canonicalStartupMilestones: [], }; } let sequence = session.lastSequence; const now = new Date(); const usageSourceKey = (input: AppendEventInput): string | null => { if ( input.type !== "agent.model.usage" || !input.payload || typeof input.payload !== "object" ) { return null; } const value = (input.payload as Record).sourceKey; return typeof value === "string" && value.length > 0 ? value : null; }; const incomingUsageKeys = [ ...new Set( inputs.map(usageSourceKey).filter((value): value is string => value !== null), ), ]; const existingUsageRows = await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "idempotency" }, async () => fence.allowed && incomingUsageKeys.length > 0 ? await tx .select({ id: schema.sessionEvents.id, payload: schema.sessionEvents.payload, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, workspaceId), eq(schema.sessionEvents.turnId, turnId), // session_events_usage_source_key_idx: a plain // column stays indexable under row-level security. inArray(schema.sessionEvents.usageSourceKey, incomingUsageKeys), eq(schema.sessionEvents.sessionId, sessionId), eq(schema.sessionEvents.type, "agent.model.usage"), eq(schema.sessionEvents.turnAssociation, "current"), ), ) : [], ); const canonicalUsageIds = new Map(); for (const row of existingUsageRows) { const value = row.payload && typeof row.payload === "object" ? (row.payload as Record).sourceKey : null; if (typeof value === "string" && value.length > 0) { canonicalUsageIds.set(value, row.id); } } const values = inputs.map((input) => { const id = crypto.randomUUID(); if (!fence.allowed) { return { id, accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: "turn.event.rejected_late", payload: { rejectedType: input.type, rejectedPayload: input.payload ?? {}, reason: fence.reason, expectedExecutionGeneration: executionGeneration, rejectedAttemptId: attemptId, currentExecutionGeneration: fence.turn?.executionGeneration ?? null, currentAttemptId: fence.turn?.activeAttemptId ?? null, currentTurnStatus: fence.turn?.status ?? null, currentActiveTurnId: session.activeTurnId, }, clientEventId: input.clientEventId ?? null, turnId, turnGeneration: executionGeneration, turnAttemptId: attemptId, turnAssociation: "late_rejected" as const, duplicateOfEventId: null, duplicateReason: null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt: input.occurredAt ?? now, }; } const sourceKey = usageSourceKey(input); const duplicateOfEventId = sourceKey ? (canonicalUsageIds.get(sourceKey) ?? null) : null; if (sourceKey && !duplicateOfEventId) { canonicalUsageIds.set(sourceKey, id); } return { id, accountId: session.accountId, workspaceId, sessionId, sequence: ++sequence, type: input.type, payload: input.payload ?? {}, clientEventId: input.clientEventId ?? null, turnId, turnGeneration: executionGeneration, turnAttemptId: attemptId, turnAssociation: duplicateOfEventId ? ("duplicate" as const) : ("current" as const), duplicateOfEventId, duplicateReason: duplicateOfEventId ? "duplicate_provider_response_usage" : null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt: input.occurredAt ?? now, }; }); const advancesActivity = sessionEventTypesAdvanceActivity(values); const rawLaneIsolated = !advancesActivity && rawLaneEnabled; if (rawLaneIsolated) { // Migration 0379 keeps legacy SQL writers fail-closed while // allowing this exact cursor-owned raw range to avoid a // per-row compatibility lookup. The AFTER statement trigger // still validates and advances the range atomically. await tx.execute( sql`select set_config( 'opengeni.session_event_raw_cursor_range_v1', ${JSON.stringify({ accountId: session.accountId, workspaceId, sessionId, firstSequence: session.lastSequence + 1, lastSequence: sequence, })}, true )`, ); } const inserted = await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "event_insert" }, async () => await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(), ); if (mutate && typeof mutate !== "function") { await mutate.project?.(tx, fence, inserted.map(mapEvent)); } const canonicalStartupMilestones = await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "projection" }, async () => { const milestones = fence.allowed ? await canonicalTurnStartupMilestonesForInsertedEvents( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId, turnCreatedAt: fence.turn!.createdAt, inserted, terminalTurnFailed: false, }, ) : []; if (fence.allowed) { await projectSessionRealtimeDelegationProgressInTransaction( tx as unknown as Database, { accountId: session.accountId, workspaceId, sessionId, turnId, events: inserted.map((event) => ({ id: event.id, sequence: event.sequence, type: event.type, payload: event.payload, })), now, }, ); const resetProviderRecovery = (providerRecoveryCountFromTurnMetadata(fence.turn!.metadata) > 0 || fence.turn!.metadata?.[PROVIDER_RECOVERY_SUSPENDED_AT] !== undefined) && hasCompletedCurrentModelRequest(inserted); const resetCapacityRecovery = fence.turn!.metadata?.[CODEX_CAPACITY_RECOVERY_KEY] !== undefined && hasCompletedCurrentModelRequest(inserted, true); if (resetProviderRecovery || resetCapacityRecovery) { let metadata = fence.turn!.metadata ?? {}; if (resetProviderRecovery) metadata = metadataWithoutProviderRecoveryCount(metadata); if (resetCapacityRecovery) metadata = clearCodexCapacityRecovery(metadata); const [resetTurn] = await tx .update(schema.sessionTurns) .set({ metadata, version: fence.turn!.version + 1, updatedAt: now, }) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), eq(schema.sessionTurns.id, turnId), eq(schema.sessionTurns.status, "running"), eq(schema.sessionTurns.executionGeneration, executionGeneration), eq(schema.sessionTurns.activeAttemptId, attemptId), ), ) .returning({ id: schema.sessionTurns.id }); if (!resetTurn) { throw new Error( `Completed provider request lost its active turn fence: ${turnId}`, ); } } } return milestones; }, ); await runSessionEventAppendPhase( observer, { ...phaseInput, phase: "sequence_update" }, async () => !advancesActivity && !rawLaneIsolated ? await tx .update(schema.sessions) .set({ lastSequence: sequence, }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ), ) : undefined, () => (advancesActivity || rawLaneIsolated ? "projection_skipped" : "ok"), ); return { events: inserted.map(mapEvent), accepted: fence.allowed, mutationApplied: true, canonicalStartupMilestones, }; }, ), ); observeSessionEventAppendPhase(observer, { ...phaseInput, phase: "transaction", outcome: !result.mutationApplied ? "mutation_skipped" : result.accepted ? "ok" : "rejected", durationSeconds: Math.max(0, (performance.now() - startedAt) / 1_000), }); return result; } catch (error) { observeSessionEventAppendPhase(observer, { ...phaseInput, phase: "transaction", outcome: error instanceof SessionSemanticWriteEscalation ? "escalated" : "error", durationSeconds: Math.max(0, (performance.now() - startedAt) / 1_000), }); throw error; } }; try { return await persist(initiallyAdvancesActivity); } catch (error) { if (initiallyAdvancesActivity || !(error instanceof SessionSemanticWriteEscalation)) { throw error; } return await persist(true); } } export type SettleCodemodeOperationWithOutputInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; operationId: string; claimId: string; producerId: string; settlement: | { state: "completed"; result: AttemptToolResult } | { state: "failed" | "outcome_unknown"; errorCode: string; errorMessage: string; }; }; /** * The Codemode terminal journal row and its visible tool-call output are one * PostgreSQL commit. A worker crash can lose only live NATS fanout, which the * ordinary durable event replay repairs; it cannot leave a completed call * permanently spinning in the timeline. */ export async function adoptCodemodeApprovalWithOutput( db: Database, input: Parameters[1], ) { const events: SessionEvent[] = []; const operation = await withSessionActivityRlsContext(db, input, (scoped) => adoptCodemodeApproval(scoped, input, async (tx, terminal) => { const appended = await appendSessionEventsForTurnAttempt( tx, input.workspaceId, input.sessionId, input.turnId, input.executionGeneration, input.attemptId, [ { type: "agent.toolCall.output", clientEventId: `opengeni:codemode-terminal:${terminal.operationId}`, turnId: input.turnId, turnGeneration: input.executionGeneration, turnAttemptId: input.attemptId, producerId: terminal.caller.subjectId, payload: { id: terminal.operationId, origin: "codemode", subjectId: terminal.caller.subjectId, error: true, output: { isError: true, content: [ { type: "text", text: terminal.errorMessage ?? "Action ended before execution." }, ], _meta: { codemodeState: terminal.state, errorCode: terminal.errorCode }, }, }, }, ], ); if (!appended.accepted) throw new Error("Continuation lost its execution fence"); events.push(...appended.events); }), ); return { operation, events }; } export async function settleCodemodeOperationWithOutput( db: Database, input: SettleCodemodeOperationWithOutputInput, ): Promise<{ committed: boolean; events: SessionEvent[]; accepted: boolean }> { const settlement = input.settlement; const failed = settlement.state !== "completed"; const output: AttemptToolResult = settlement.state === "completed" ? settlement.result : { content: [ { type: "text", text: settlement.errorMessage.slice(0, 4_096), }, ], isError: true, _meta: { codemodeState: settlement.state, errorCode: settlement.errorCode.slice(0, 128), }, }; const result = await mutateAndAppendSessionEventsForTurnAttempt( db, input.workspaceId, input.sessionId, input.turnId, input.executionGeneration, input.attemptId, [ { type: "agent.toolCall.output", turnId: input.turnId, turnGeneration: input.executionGeneration, turnAttemptId: input.attemptId, producerId: input.producerId, payload: { id: input.operationId, output, ...(failed ? { error: true } : {}), origin: "codemode", subjectId: input.producerId, }, }, ], { rowProjection: "event", mutate: async (tx) => settlement.state === "completed" ? await completeCodemodeOperationInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, attemptId: input.attemptId, operationId: input.operationId, claimId: input.claimId, result: settlement.result, }) : await failCodemodeOperationInTransaction(tx, { accountId: input.accountId, workspaceId: input.workspaceId, attemptId: input.attemptId, operationId: input.operationId, claimId: input.claimId, state: settlement.state, errorCode: settlement.errorCode, errorMessage: settlement.errorMessage, }), }, ); return { committed: result.mutationApplied, events: result.events, accepted: result.accepted, }; } export async function appendSessionEventToSandboxGroup( db: Database, workspaceId: string, sandboxGroupId: string, input: AppendEventInput, ): Promise { return await withWorkspaceSessionEventActivityRls( db, workspaceId, sessionEventTypesAdvanceActivity([input]), async (scopedDb) => await scopedDb.transaction(async (tx) => { await lockSessionEventWriteRows(tx as unknown as Database, { rowProjection: "event", workspaceId, controlLock: "none", }); const sessionIds = await tx .select({ id: schema.sessions.id }) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.sandboxGroupId, sandboxGroupId), ), ) .orderBy(asc(schema.sessions.id)); const locks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: sessionIds.map((row) => row.id), turnIds: input.turnId ? [input.turnId] : [], attemptIds: input.turnAttemptId ? [input.turnAttemptId] : [], }); const rows = locks.sessions .filter((row) => row.sandboxGroupId === sandboxGroupId) .sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime()); if (rows.length === 0) { return []; } const occurredAt = input.occurredAt ?? new Date(); const values = rows.map((row) => ({ accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.id, sequence: row.lastSequence + 1, type: input.type, payload: input.payload ?? {}, clientEventId: input.clientEventId ?? null, turnId: input.turnId ?? null, turnGeneration: input.turnGeneration ?? null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt, })); const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(); if (!sessionEventTypesAdvanceActivity([input])) { const lockedSessionIds = rows.map((row) => row.id); const updated = await tx .update(schema.sessions) .set({ lastSequence: sql`${schema.sessions.lastSequence} + 1` }) .where( and( eq(schema.sessions.workspaceId, workspaceId), inArray(schema.sessions.id, lockedSessionIds), ), ) .returning({ id: schema.sessions.id }); if (updated.length !== lockedSessionIds.length) { throw new Error("Sandbox-group event sequence update did not match locked sessions"); } } return inserted.map(mapEvent); }), ); } export async function appendSessionEventsAndUpdateSession( db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[], update: { resources?: ResourceRef[]; tools?: ToolRef[]; model?: string; metadata?: Record; status?: SessionStatus; activeTurnId?: string | null; }, ): Promise { if (inputs.length === 0) { return []; } return await withWorkspaceSessionEventActivityRls( db, workspaceId, sessionMutationAdvancesActivity(update) || sessionEventTypesAdvanceActivity(inputs), async (scopedDb) => await scopedDb.transaction(async (tx) => { const turnIds = inputs .map((input) => input.turnId) .filter((id): id is string => typeof id === "string"); const attemptIds = inputs .map((input) => input.turnAttemptId) .filter((id): id is string => typeof id === "string"); const locks = await lockSessionEventWriteRows(tx as unknown as Database, { rowProjection: "event", workspaceId, controlLock: "none", sessionIds: [sessionId], turnIds, attemptIds, }); const row = locks.sessions[0]; if (!row) { throw new Error(`Session not found: ${sessionId}`); } let sequence = row.lastSequence; const now = new Date(); const values = inputs.map((input) => ({ accountId: row.accountId, workspaceId: row.workspaceId, sessionId, sequence: ++sequence, type: input.type, payload: input.payload ?? {}, clientEventId: input.clientEventId ?? null, turnId: input.turnId ?? null, turnGeneration: input.turnGeneration ?? null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt: input.occurredAt ?? now, })); const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(); const advancesActivity = sessionMutationAdvancesActivity(update) || sessionEventTypesAdvanceActivity(values); await tx .update(schema.sessions) .set({ lastSequence: sequence, ...(update.resources !== undefined ? { resources: update.resources } : {}), ...(update.tools !== undefined ? { tools: update.tools } : {}), ...(update.model !== undefined ? { model: update.model } : {}), ...(update.metadata !== undefined ? { metadata: update.metadata } : {}), ...(update.status !== undefined ? { status: update.status } : {}), ...(update.activeTurnId !== undefined ? { activeTurnId: update.activeTurnId } : {}), ...(advancesActivity ? { updatedAt: now } : {}), }) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ); return inserted.map(mapEvent); }), ); } type LockedSessionUpdateContext = { updateSessionMcpServerCredentials: ( updates: UpdateSessionMcpServerCredentialsInput[], ) => Promise; updateSessionMcpApprovalPolicy: ( serverId: string, requireApproval: SessionMcpApprovalPolicy, ) => Promise; listPendingSessionTurns: () => Promise; getLockedSession: (sessionId: string) => Promise; /** The locked chat's organization agent binding, or null. */ orgAgentState: { agentId: string; version: number; promptVersion: number | null; overrides: Record | null; } | null; /** The locked chat's MCP server rows, with their encrypted per-chat headers. */ listSessionMcpServerRows: () => Promise; /** Remove and write MCP server rows for a publish move (per-chat headers kept as given). */ replaceSessionMcpServersForOrgAgentMove: (input: { removeIds: readonly string[]; upsert: readonly OrgAgentMoveSessionMcpServerRow[]; }) => Promise; }; /** A session MCP server row as a publish move reads and writes it. */ export type OrgAgentMoveSessionMcpServerRow = { id: string; name: string | null; url: string; allowedTools: string[] | null; timeoutMs: number | null; cacheToolsList: boolean; requireApproval: boolean | string[] | null; connectionRef: McpServerConnectionRef | null; headersEncrypted: Record; }; type LockedSessionUpdateResult = { events: AppendEventInput[]; update?: { resources?: ResourceRef[]; /** Repository removal records (migration 1140), written with `resources`. */ removedRepositories?: SessionRemovedRepository[]; tools?: ToolRef[]; firstPartyMcpTools?: FirstPartyMcpToolName[]; /** Trusted host normalization; never accepted directly from a public update body. */ firstPartyMcpPermissions?: Permission[]; sandboxBackend?: "none"; /** Agent configuration (migration 0559); written with the tool-policy CAS. */ agentConfig?: ResolvedAgentConfig | null; /** Session instructions (the `agent.instructions` alias). */ instructions?: string | null; /** The Skills the session carries itself; written with the tool-policy CAS. */ skills?: SessionSkill[]; toolPolicy?: SessionToolPolicy; toolPolicyVersion?: number; expectedToolPolicyVersion?: number; model?: string; metadata?: Record; status?: SessionStatus; activeTurnId?: string | null; /** * A publish move: the version the chat runs and what it changed, written * only while the chat still runs `expectedVersion`. Never the prompt * version; the next turn delivers newer Instructions. */ orgAgent?: { expectedVersion: number; version: number; overrides: Record | null; }; }; }; /** * Serialize a callback with the session/event lock prefix and append its result. * Callers must declare whether the callback can produce semantic activity. A * raw-only declaration skips the commit gate and is verified before any event * or session-row write; conditional semantic callbacks may legitimately no-op. */ export async function appendSessionEventsWithLockedSessionUpdate( db: Database, workspaceId: string, sessionId: string, build: ( session: Session, context: LockedSessionUpdateContext, ) => LockedSessionUpdateResult | Promise, options: { activity: "raw-only" | "semantic"; lockParentSession?: boolean; }, ): Promise { return await withWorkspaceSessionEventActivityRls( db, workspaceId, options.activity === "semantic", async (scopedDb) => await scopedDb.transaction(async (tx) => { const firstLocks = await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "share", sessionIds: [sessionId], }); const firstSessionRow = firstLocks.sessions.find((row) => row.id === sessionId); if (!firstSessionRow) { throw new Error(`Session not found: ${sessionId}`); } // Child-policy updates must serialize with a concurrent parent-policy // update. The target lock establishes the parent id, then the second // call acquires the complete UUID-ordered set under the already-held // workspace/control prefix. const lockSessionIds = options.lockParentSession ? [sessionId, firstSessionRow.parentSessionId].filter((id): id is string => Boolean(id)) : [sessionId]; const locks = lockSessionIds.length === 1 ? firstLocks : await lockSessionEventWriteRows(tx as unknown as Database, { workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: lockSessionIds, }); const sessionRow = locks.sessions.find((row) => row.id === sessionId); if (!sessionRow) { throw new Error(`Session not found: ${sessionId}`); } // The callback receives complete Sessions; the rows are locked, so // their Skill folders read here are the ones this update replaces. const lockedSkills = await readSessionSkills( tx as unknown as Database, workspaceId, locks.sessions.map((row) => row.id), ); const withLockedSkills = (row: (typeof locks.sessions)[number]): SessionRowWithSkills => { const skills = lockedSkills.get(row.id); if (!skills) throw new Error(`Session not found: ${row.id}`); return { ...row, skills }; }; const mappedSession = await mapSessionWithControl( tx as unknown as Database, withLockedSkills(sessionRow), [], undefined, undefined, undefined, locks.control ?? undefined, ); const built = await build(mappedSession, { updateSessionMcpServerCredentials: async (updates) => await updateSessionMcpServerCredentialsInTransaction(tx, { workspaceId, sessionId, updates, }), updateSessionMcpApprovalPolicy: async (serverId, requireApproval) => await updateSessionMcpApprovalPolicyInTransaction(tx as unknown as Database, { workspaceId, sessionId, serverId, requireApproval, }), listPendingSessionTurns: async () => { const rows = await tx .select() .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), eq(schema.sessionTurns.sessionId, sessionId), inArray(schema.sessionTurns.status, ["queued", "running", "requires_action"]), ), ) .orderBy(asc(schema.sessionTurns.position), asc(schema.sessionTurns.createdAt)); return rows.map(mapSessionTurn); }, orgAgentState: sessionRow.agentId && sessionRow.agentVersion != null ? { agentId: sessionRow.agentId, version: Number(sessionRow.agentVersion), promptVersion: sessionRow.agentPromptVersion == null ? null : Number(sessionRow.agentPromptVersion), overrides: sessionRow.agentOverrides && typeof sessionRow.agentOverrides === "object" ? sessionRow.agentOverrides : null, } : null, listSessionMcpServerRows: async () => ( await tx .select() .from(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), ), ) .orderBy( asc(schema.sessionMcpServers.createdAt), asc(schema.sessionMcpServers.serverId), ) ).map((row) => ({ id: row.serverId, name: row.name ?? null, url: row.url, allowedTools: row.allowedTools ?? null, timeoutMs: row.timeoutMs ?? null, cacheToolsList: row.cacheToolsList, requireApproval: row.requireApproval ?? null, connectionRef: row.connectionRef ?? null, headersEncrypted: row.headersEncrypted ?? {}, })), replaceSessionMcpServersForOrgAgentMove: async ({ removeIds, upsert }) => { if (removeIds.length > 0) { await tx .delete(schema.sessionMcpServers) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), inArray(schema.sessionMcpServers.serverId, [...removeIds]), ), ); } const now = new Date(); for (const server of upsert) { const values = { name: server.name, url: server.url, allowedTools: server.allowedTools, timeoutMs: server.timeoutMs, cacheToolsList: server.cacheToolsList, requireApproval: server.requireApproval, connectionRef: server.connectionRef, headersEncrypted: server.headersEncrypted, updatedAt: now, }; const [updated] = await tx .update(schema.sessionMcpServers) .set({ ...values, credentialVersion: sql`${schema.sessionMcpServers.credentialVersion} + 1`, }) .where( and( eq(schema.sessionMcpServers.workspaceId, workspaceId), eq(schema.sessionMcpServers.sessionId, sessionId), eq(schema.sessionMcpServers.serverId, server.id), ), ) .returning({ id: schema.sessionMcpServers.id }); if (!updated) { await tx.insert(schema.sessionMcpServers).values({ accountId: sessionRow.accountId, workspaceId, sessionId, serverId: server.id, ...values, }); } } }, getLockedSession: async (lockedSessionId) => { const row = locks.sessions.find((candidate) => candidate.id === lockedSessionId); return row ? await mapSessionWithControl( tx as unknown as Database, withLockedSkills(row), [], undefined, undefined, undefined, locks.control ?? undefined, ) : null; }, }); const update = built.update ?? {}; const advancesActivity = sessionMutationAdvancesActivity(update) || sessionEventTypesAdvanceActivity(built.events); if (options.activity === "raw-only" && advancesActivity) { throw new Error( "Raw-only locked session event append cannot contain semantic events or session updates", ); } if (built.events.length === 0) { return []; } await lockSessionEventWriteRows(tx as unknown as Database, { rowProjection: "event", workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", turnIds: built.events .map((input) => input.turnId) .filter((id): id is string => typeof id === "string"), attemptIds: built.events .map((input) => input.turnAttemptId) .filter((id): id is string => typeof id === "string"), }); let sequence = sessionRow.lastSequence; const now = new Date(); const values = built.events.map((input) => ({ accountId: sessionRow.accountId, workspaceId: sessionRow.workspaceId, sessionId, sequence: ++sequence, type: input.type, payload: input.payload ?? {}, clientEventId: input.clientEventId ?? null, turnId: input.turnId ?? null, turnGeneration: input.turnGeneration ?? null, producerId: input.producerId ?? null, producerSeq: input.producerSeq ?? null, occurredAt: input.occurredAt ?? now, })); const inserted = await tx .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(values), "payload", "payloadCodecVersion", ), ) .returning(); const updated = await tx .update(schema.sessions) .set({ lastSequence: sequence, ...(update.resources !== undefined ? { resources: update.resources } : {}), ...(update.removedRepositories !== undefined ? { removedRepositories: update.removedRepositories } : {}), ...(update.tools !== undefined ? { tools: update.tools } : {}), ...(update.firstPartyMcpTools !== undefined ? { firstPartyMcpTools: update.firstPartyMcpTools } : {}), ...(update.firstPartyMcpPermissions !== undefined ? { firstPartyMcpPermissions: canonicalSecretPermissions( update.firstPartyMcpPermissions, ), } : {}), ...(update.sandboxBackend !== undefined ? { sandboxBackend: update.sandboxBackend } : {}), ...(update.agentConfig !== undefined ? { agentConfig: update.agentConfig } : {}), ...(update.instructions !== undefined ? { instructions: update.instructions } : {}), ...(update.toolPolicy !== undefined ? { toolPolicy: update.toolPolicy } : {}), ...(update.toolPolicyVersion !== undefined ? { toolPolicyVersion: update.toolPolicyVersion } : {}), ...(update.model !== undefined ? { model: update.model } : {}), ...(update.metadata !== undefined ? { metadata: update.metadata } : {}), ...(update.status !== undefined ? { status: update.status } : {}), ...(update.activeTurnId !== undefined ? { activeTurnId: update.activeTurnId } : {}), ...(update.orgAgent !== undefined ? { agentVersion: update.orgAgent.version, agentOverrides: update.orgAgent.overrides, } : {}), ...(advancesActivity ? { updatedAt: now } : {}), }) .where( and( eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId), ...(update.expectedToolPolicyVersion !== undefined ? [eq(schema.sessions.toolPolicyVersion, update.expectedToolPolicyVersion)] : []), ...(update.orgAgent !== undefined ? [eq(schema.sessions.agentVersion, update.orgAgent.expectedVersion)] : []), ), ) .returning({ id: schema.sessions.id }); if (updated.length === 0) { const [current] = await tx .select({ toolPolicyVersion: schema.sessions.toolPolicyVersion }) .from(schema.sessions) .where( and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId)), ) .limit(1); throw new SessionToolPolicyVersionConflictError( Number(current?.toolPolicyVersion ?? update.expectedToolPolicyVersion ?? 1), ); } if (update.skills !== undefined) { // Written with the tool-policy CAS above, under the same row lock. await tx .update(schema.sessionSkillSets) .set({ skills: update.skills }) .where( and( eq(schema.sessionSkillSets.workspaceId, workspaceId), eq(schema.sessionSkillSets.id, sessionId), ), ); } return inserted.map(mapEvent); }), ); } export function sessionSubject(workspaceId: string, sessionId: string): string { return `workspaces.${workspaceId}.sessions.${sessionId}.events`; } async function sessionControlProjections( db: Database, workspaceId: string, sessionIds: string[], workspaceControl?: WorkspaceControlRow, ): Promise> { // Read projections (GET session, session lists) are not control writers. // Like discovery, they read the control row without joining the writer lock // graph: a projection that took FOR SHARE would queue behind a waiting Pause // under the fair control prefix and would let a burst of reads delay it, // while buying no consistency the separate session-row statement has. // Writers that already hold the prefix pass their locked row through. const controls = await evaluateSessionControls(db, workspaceId, sessionIds, { ...(workspaceControl ? { workspaceControl } : { lock: "none" as const }), }); return new Map( [...controls].map(([sessionId, control]) => [ sessionId, serializeEffectiveSessionControl(control), ]), ); } /** `Session.orgAgent` for a chat that runs an organization agent version. */ async function sessionOrgAgentProjection( db: Database, row: Pick< typeof schema.sessions.$inferSelect, "accountId" | "workspaceId" | "agentId" | "agentVersion" | "agentOverrides" >, ): Promise { if (row.agentVersion == null || !row.agentId) return null; const agentId = row.agentId; const keys = await withRlsContext( db, { accountId: row.accountId, workspaceId: row.workspaceId }, (tx) => readOrgAgentKeysInTransaction(tx, row.accountId, [agentId]), ).catch(() => new Map()); const identity = keys.get(agentId); if (!identity) return null; return { id: agentId, key: identity.key, name: identity.name, version: Number(row.agentVersion), overrides: row.agentOverrides && typeof row.agentOverrides === "object" ? row.agentOverrides : null, }; } async function mapSessionWithControl( db: Database, row: SessionRowWithSkills, mcpServers: SessionMcpServerMetadata[] = [], pin: Pick = mapSessionPin(null), attention: Pick = { unread: false, activelyWorking: false, attentionVersion: 0, }, archive: ReturnType = mapSessionArchive(null), workspaceControl?: WorkspaceControlRow, tenancyViewer?: { subjectId: string }, presentation: "full" | "model_gate" = "full", ): Promise { const controls = await sessionControlProjections(db, row.workspaceId, [row.id], workspaceControl); const control = controls.get(row.id); if (!control) throw new Error(`Effective control missing for session ${row.id}`); const [effective] = await withEffectiveSessionPolicy( db, row.workspaceId, await withCurrentSessionInputWait(db, row.workspaceId, [row]), ); const mapped = mapSession( effective!, control, mcpServers, pin, attention, archive, tenancyViewer, ); mapped.codexCurrentSelection = null; mapped.dispatchWait = null; if (row.agentVersion != null && row.agentId) { mapped.orgAgent = await sessionOrgAgentProjection(db, row); } if (presentation === "model_gate") return mapped; if (row.status === "queued" && row.activeTurnId === null && control.state === "active") { // Read only the existing delivery ledger. Neither a claimed wake nor a // Temporal acknowledgement proves that a worker has admitted a turn. const [wake] = await db .select({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision, deliveredRevision: schema.sessionWorkflowWakeOutbox.deliveredRevision, attempts: schema.sessionWorkflowWakeOutbox.attempts, nextAttemptAt: schema.sessionWorkflowWakeOutbox.nextAttemptAt, lastError: schema.sessionWorkflowWakeOutbox.lastError, }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, row.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, row.id), ), ) .limit(1); const pending = wake && wake.wakeRevision > wake.deliveredRevision; mapped.dispatchWait = { state: pending ? "pending" : wake ? "acknowledged" : "unavailable", attempts: pending ? wake.attempts : 0, nextAttemptAt: pending ? wake.nextAttemptAt.toISOString() : null, lastError: pending ? wake.lastError : null, }; } // A selection belongs to the active turn; without one there is none to read. const selections = row.activeTurnId ? await getSubscriptionCoreCodexCurrentSelections(db, { accountId: row.accountId, workspaceId: row.workspaceId, sessionIds: [row.id], }) : null; mapped.codexCurrentSelection = selections?.get(row.id) ?? null; return mapped; } function mapSessionTenancy( row: typeof schema.sessions.$inferSelect, subjectId: string, ): SessionTenancyPublicProjection { const hasFork = row.forkedFromSessionId !== null; if ( hasFork !== (row.forkedFromVisibility !== null && row.forkedFromAuthorityEpoch !== null && row.forkedAt !== null) ) { throw new Error(`Session fork provenance is incomplete: ${row.id}`); } return { visibility: sessionVisibilityToPublic(row.visibility as "user_private" | "workspace_shared"), authorityEpoch: Number(row.authorityEpoch), ownedByCurrentUser: row.ownerSubjectId === subjectId, fork: hasFork ? { sourceVisibility: sessionVisibilityToPublic( row.forkedFromVisibility as "user_private" | "workspace_shared", ), sourceAuthorityEpoch: Number(row.forkedFromAuthorityEpoch), forkedAt: row.forkedAt!.toISOString(), } : null, }; } type MapSessionDecorations = [ effectiveControl: Session["effectiveControl"], mcpServers?: SessionMcpServerMetadata[], pin?: Pick, attention?: Pick, archive?: ReturnType, tenancyViewer?: { subjectId: string }, ]; function mapSession(row: SessionRowWithSkills, ...decorations: MapSessionDecorations): Session { // mapSessionFields sets `skills` whenever it is given them. return mapSessionFields( row, StoredSessionSkills.parse(row.skills ?? []), ...decorations, ) as Session; } /** * A session's configuration without its Skill folders, for internal callers * that never use them and read the row without them. */ function mapSessionWithoutSkills( row: SessionRow, ...decorations: MapSessionDecorations ): Omit { return mapSessionFields(row, undefined, ...decorations); } function mapSessionFields( row: SessionRow, skills: Session["skills"] | undefined, effectiveControl: Session["effectiveControl"], mcpServers: SessionMcpServerMetadata[] = [], pin: Pick = mapSessionPin(null), attention: Pick = { unread: false, activelyWorking: false, attentionVersion: 0, }, archive: ReturnType = mapSessionArchive(null), tenancyViewer?: { subjectId: string }, ): Omit & Partial> { const bundledSkillIds = bundledSkillSelectionFromMetadata(row.metadata); return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, status: row.status as SessionStatus, ...(row.importedArchiveImportId && row.importedArchiveImportedAt ? { importedArchive: { importId: row.importedArchiveImportId, importedAt: row.importedArchiveImportedAt.toISOString(), readOnly: true as const, }, } : {}), retention: sessionRetentionFromRow(row), unattended: resolveSessionUnattended({ setting: row.unattendedSetting ?? null, createdUnattended: sessionMetadataUnattended(row.metadata), forked: row.forkedFromSessionId !== null, }), admissionBlock: projectSessionAdmissionBlock(row.admissionBlock), initialMessage: fromPostgresLosslessText(row.initialMessage, row.initialMessageCodecVersion), title: cleanStoredSessionTitle(row.title, row.titleSource), titleSource: (row.titleSource as "user" | "agent" | null) ?? null, description: row.description ?? null, avatar: storedSessionAvatar(row.avatar), // A workspace agent only: an organization agent chat reports `orgAgent`. agentId: row.agentVersion == null ? (row.agentId ?? null) : null, instructions: row.instructions ?? null, policyRole: row.policyRole ?? null, agentAccess: sessionAgentAccessFromRow(row), scopeSubjectId: sessionEndUserFromRow(row), memoryScope: sessionMemoryScopeFromRow(row), resources: row.resources as ResourceRef[], ...sessionRemovedRepositoriesProjection(row.removedRepositories), // Same key position as always, so serialized sessions keep their bytes. ...(skills !== undefined ? { skills } : {}), ...(bundledSkillIds !== undefined ? { bundledSkillIds } : {}), tools: row.tools as ToolRef[], toolPolicy: row.toolPolicy as SessionToolPolicy, toolPolicyVersion: Number(row.toolPolicyVersion), mcpApprovalPolicies: row.mcpApprovalPolicies, // A person makes a fork to continue the work, so a fork reads as attended // even though the fork routine copies the source row's metadata. // Otherwise a chat that started unattended through its setting carries the // same frozen marker as the create option, so everything that follows how // the chat started reads one place. metadata: row.forkedFromSessionId ? withSessionUnattendedMetadata(row.metadata, false) : row.startedUnattended === true ? withSessionUnattendedMetadata(row.metadata, true) : row.metadata, ...(tenancyViewer ? { tenancy: mapSessionTenancy(row, tenancyViewer.subjectId) } : {}), createdBy: initiatorFromStorage( row.createdByKind, row.createdBySubjectId, row.createdByContext ?? {}, ), createdByContext: row.createdByContext ?? {}, model: row.model, reasoningEffort: row.reasoningEffort as ReasoningEffort, latencyMode: row.latencyMode as LatencyMode, sandboxBackend: row.sandboxBackend as SandboxBackend, sandboxOs: row.sandboxOs as SandboxOs, sandboxGroupId: row.sandboxGroupId, // The first-class swappable-sandbox pointer (M2). null == use the group // sandbox; active_epoch is the swap fence. Defensive Number() coercion keeps // the fence exact even if the column type ever drifts (the lease-epoch lesson). activeSandboxId: row.activeSandboxId ?? null, activeEpoch: Number(row.activeEpoch), workingDir: row.workingDir ?? null, // The rig + frozen rig version the session rides (M3). Both null for a // rig-less session; frozen at create so a later promote never moves them. rigId: row.rigId ?? null, rigVersionId: row.rigVersionId ?? null, channelId: row.channelId ?? null, firstPartyMcpPermissions: (row.firstPartyMcpPermissions as Permission[] | null) ?? null, firstPartyMcpTools: row.firstPartyMcpTools as FirstPartyMcpToolName[], mcpServers, parentSessionId: row.parentSessionId ?? null, rootSessionId: row.rootSessionId, ...(row.failureHandled ? { failureHandled: true } : {}), ...(row.questionWithAgent ? { questionWithAgent: true } : {}), nestedAgentDepth: row.nestedAgentDepth, maxNestedAgentDepthOverride: row.maxNestedAgentDepthOverride ?? null, effectiveMaxNestedAgentDepth: row.effectiveMaxNestedAgentDepth, nestedAgentDepthPolicySource: row.nestedAgentDepthPolicySource as NestedAgentDepthPolicySource, nestedAgentDepthPolicySessionId: row.nestedAgentDepthPolicySessionId ?? null, createIdempotencyKey: row.createIdempotencyKey ?? null, temporalWorkflowId: row.temporalWorkflowId, activeTurnId: row.activeTurnId, lastInputTokens: row.lastInputTokens ?? null, queueVersion: row.queueVersion, queueHeadPosition: Number(row.queueHeadPosition), queueTailPosition: Number(row.queueTailPosition), effectiveControl, inputWait: effectiveControl.state === "active" ? (row.currentInputWait ?? null) : null, ...(row.currentWaitingOn ? { waitingOn: row.currentWaitingOn } : {}), lastSequence: row.lastSequence, // Public adapters project these from subscription-core bindings and leases, // never the frozen columns of the retired allocator. codexPinnedCredentialId: null, codexLastCredentialId: null, codexCompactionMode: row.codexCompactionMode === "remote_v2" || row.codexCompactionMode === "portable" ? row.codexCompactionMode : "portable", codeSearchEnabled: row.codeSearchEnabled === true, agent: parseStoredSessionAgentConfig(row.agentConfig), ...pin, ...attention, ...sessionRowArchive(row), ...archive, // Only while a connection card waits, so other sessions keep their bytes. ...(row.awaitingConnectionSince ? { awaitingConnectionSince: new Date(row.awaitingConnectionSince).toISOString() } : {}), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapEvent(row: typeof schema.sessionEvents.$inferSelect): SessionEvent { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, sequence: row.sequence, type: row.type as SessionEventType, payload: fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), occurredAt: row.occurredAt.toISOString(), clientEventId: row.clientEventId, turnId: row.turnId, turnGeneration: row.turnGeneration, turnAttemptId: row.turnAttemptId, turnAssociation: row.turnAssociation as SessionEvent["turnAssociation"], duplicateOfEventId: row.duplicateOfEventId, duplicateReason: row.duplicateReason, }; } function mapProjectedEvent(row: SessionEventProjectionRow): SessionEvent { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, sequence: row.sequence, type: row.type as SessionEventType, payload: fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), occurredAt: row.occurredAt instanceof Date ? row.occurredAt.toISOString() : new Date(row.occurredAt).toISOString(), clientEventId: row.clientEventId, turnId: row.turnId, turnGeneration: row.turnGeneration, turnAttemptId: row.turnAttemptId, turnAssociation: row.turnAssociation as SessionEvent["turnAssociation"], duplicateOfEventId: row.duplicateOfEventId, duplicateReason: row.duplicateReason, }; } function utf8JsonBytes(value: unknown): number { return Buffer.byteLength(JSON.stringify(value), "utf8"); } /** Present only when the session has removal records, so other sessions read unchanged. */ function sessionRemovedRepositoriesProjection( value: unknown, ): Pick { const removedRepositories = parseSessionRemovedRepositories(value); return removedRepositories.length > 0 ? { removedRepositories } : {}; } function mapSessionTurn(row: typeof schema.sessionTurns.$inferSelect): SessionTurn { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, triggerEventId: row.triggerEventId, temporalWorkflowId: row.temporalWorkflowId, status: row.status as SessionTurnStatus, source: row.source as SessionTurnSource, position: row.position, prompt: fromPostgresLosslessText(row.prompt, row.promptCodecVersion), annotations: TimelineAnnotations.parse(row.annotations), resources: row.resources as ResourceRef[], tools: row.tools as ToolRef[], toolsProvided: row.toolsProvided, model: row.model, reasoningEffort: row.reasoningEffort as ReasoningEffort, latencyMode: (row.latencyMode as LatencyMode | null | undefined) ?? "standard", sandboxBackend: row.sandboxBackend as SandboxBackend, sandboxOs: (row.sandboxOs as SandboxOs | null) ?? null, metadata: row.metadata, version: row.version, executionGeneration: row.executionGeneration, activeAttemptId: row.activeAttemptId, lineage: row.lineage, initiator: initiatorFromStorage( row.initiatorKind, row.initiatorSubjectId, row.initiatorContext ?? {}, ), initiatorContext: row.initiatorContext ?? {}, personalConnections: parsedPersonalConnectionDelegations( row.personalConnectionDelegations, `session_turns:${row.workspaceId}:${row.sessionId}:${row.id}`, ).map(({ serverId, providerDomain }) => ({ serverId, providerDomain })), personalResources: row.personalResourceAttachmentSummary ? PersonalResourceAttachmentSummary.parse(row.personalResourceAttachmentSummary) : null, cancelledBy: row.cancelledBy, cancelReason: row.cancelReason, startedAt: row.startedAt ? row.startedAt.toISOString() : null, finishedAt: row.finishedAt ? row.finishedAt.toISOString() : null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapSessionTurnForExecution( row: typeof schema.sessionTurns.$inferSelect, ): SessionTurnForExecution { return { ...mapSessionTurn(row), mcpAccountBindings: parseAcceptedMcpAccountBindings(row.mcpAccountBindings), initiatingHumanSubjectId: row.initiatingHumanSubjectId ?? null, scheduledTaskRunId: row.scheduledTaskRunId ?? null, billingOrigin: storedBillingOrigin(row.billingOrigin), personalConnectionDelegations: parsedPersonalConnectionDelegations( row.personalConnectionDelegations, `session_turns:${row.workspaceId}:${row.sessionId}:${row.id}`, ), xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1.parse( row.xaiProviderAccountAuthoritySnapshot, ), claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1.parse( row.claudeProviderAccountAuthoritySnapshot, ), goalSnapshot: SessionGoalSnapshot.parse(row.goalSnapshot), }; } async function latestStartedSessionTurnRow( db: Database, workspaceId: string, sessionId: string, ): Promise { const latest = latestStartedSessionTurnQuery(db, workspaceId, sessionId).as( "latest_started_turn", ); const [row] = await db .select({ turn: schema.sessionTurns }) .from(latest) .innerJoin(schema.sessionTurns, eq(schema.sessionTurns.id, latest.id)); return row?.turn ?? null; } /** A stored file row as the public file contract reads it. */ export function fileAssetFromRow(row: typeof schema.files.$inferSelect): FileAsset { return mapFile(row); } function mapFile(row: typeof schema.files.$inferSelect): FileAsset { return { scope: row.privateOwnerSubjectIds ? "personal" : "workspace", // Private files made before owners were recorded belong to their one private owner. ownerSubjectId: row.ownerSubjectId ?? (row.privateOwnerSubjectIds?.length === 1 ? row.privateOwnerSubjectIds[0]! : null), // Only an Only me file works in other workspaces. ...(row.privateOwnerSubjectIds ? { reachWorkspaceIds: row.reachWorkspaceIds ?? null } : {}), id: row.id, workspaceId: row.workspaceId, status: row.status as FileStatus, filename: row.filename, safeFilename: row.safeFilename, contentType: row.contentType, sizeBytes: row.sizeBytes, sha256: row.sha256, bucket: row.bucket, objectKey: row.objectKey, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), ...appShotOfRow(row.appShot), }; } /** A stored capture as the contract reads it; anything malformed is left out. */ function appShotOfRow(value: unknown): { appShot?: AppShotCapture } { if (value === null || value === undefined) return {}; const parsed = AppShotCapture.safeParse(value); return parsed.success ? { appShot: parsed.data } : {}; } function mapRetainedScreenshotArtifact( artifact: typeof schema.retainedScreenshotArtifacts.$inferSelect, file: typeof schema.files.$inferSelect, ): RetainedScreenshotArtifact { return { artifactId: artifact.artifactId, accountId: artifact.accountId, workspaceId: artifact.workspaceId, sessionId: artifact.sessionId, turnId: artifact.turnId, attemptId: artifact.attemptId, settlementKey: artifact.settlementKey, toolCallId: artifact.toolCallId, toolOutputId: artifact.toolOutputId, status: artifact.status as RetainedScreenshotArtifactStatus, quotaState: artifact.quotaState as RetainedScreenshotQuotaState, mediaType: artifact.mediaType, sizeBytes: artifact.sizeBytes, sha256: artifact.sha256, width: artifact.width, height: artifact.height, retentionExpiresAt: artifact.retentionExpiresAt, readyAt: artifact.readyAt, cleanupReason: artifact.cleanupReason, lastError: artifact.lastError, maintenanceClaimId: artifact.maintenanceClaimId, maintenanceClaimedAt: artifact.maintenanceClaimedAt, createdAt: artifact.createdAt, updatedAt: artifact.updatedAt, file: mapFile(file), }; } function mapScheduledTask(row: typeof schema.scheduledTasks.$inferSelect): ScheduledTask { const existingSessionTarget = row.runMode === "existing_session"; return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, name: row.name, ownerSubjectId: row.ownerSubjectId, visibility: row.visibility === "user_private" ? "private" : "workspace", status: row.status as ScheduledTaskStatus, schedule: row.schedule as ScheduledTaskScheduleSpec, temporalScheduleId: row.temporalScheduleId, runMode: row.runMode as ScheduledTaskRunMode, overlapPolicy: row.overlapPolicy as ScheduledTaskOverlapPolicy, action: (row.action ?? { kind: "agent_turn" }) as ScheduledTaskAction, agentConfig: row.agentConfig as ScheduledTaskAgentConfig, createdBy: initiatorFromStorage( row.createdByKind, row.createdBySubjectId, row.createdByContext as TurnInitiatorContext, ), createdByContext: row.createdByContext as TurnInitiatorContext, authorityRevision: row.authorityRevision, executionDigest: row.executionDigest, reusableSessionId: existingSessionTarget ? null : row.reusableSessionId, targetSessionId: existingSessionTarget ? row.reusableSessionId : null, rigId: row.rigId ?? null, vaultPolicy: row.vaultPolicy ?? { mode: "all" }, metadata: row.metadata, // Projected only when set, so unlocked tasks keep their exact shape. ...(row.creatorLocked ? { creatorLocked: true as const } : {}), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } /** * The pinned accounts an admitted run went without, read from its accepted * execution. Only this credential-free list is projected; the snapshot itself * stays private worker authority. */ function scheduledTaskRunDegradedAccounts( snapshot: unknown, ): Pick { if (!snapshot || typeof snapshot !== "object") return {}; const parsed = ScheduledTaskDegradedAccounts.safeParse( (snapshot as { degradedAccounts?: unknown }).degradedAccounts, ); return parsed.success && parsed.data.length > 0 ? { degradedAccounts: parsed.data } : {}; } function mapScheduledTaskRun(row: typeof schema.scheduledTaskRuns.$inferSelect): ScheduledTaskRun { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, taskId: row.taskId, taskAuthorityRevision: row.taskAuthorityRevision, taskExecutionDigest: row.taskExecutionDigest, status: row.status as ScheduledTaskRunStatus, triggerType: row.triggerType as ScheduledTaskTriggerType, scheduledAt: row.scheduledAt ? row.scheduledAt.toISOString() : null, firedAt: row.firedAt.toISOString(), sessionId: row.sessionId, triggerEventId: row.triggerEventId, actionKind: row.actionKind as ScheduledTaskActionKind, knowledgeSyncRunId: row.knowledgeSyncRunId, knowledgeSummary: row.knowledgeSummary as ScheduledTaskRun["knowledgeSummary"], ...(row.syncSummary ? { syncSummary: row.syncSummary as ScheduledTaskRun["syncSummary"] } : {}), completedAt: row.completedAt?.toISOString() ?? null, error: row.error, admissionDiagnostic: row.admissionDiagnostic == null ? null : ConnectionAccountSelectionDiagnostic.parse(row.admissionDiagnostic), ...scheduledTaskRunDegradedAccounts(row.acceptedExecutionSnapshot), admissionRefusal: row.admissionRefusal == null ? null : ScheduledTaskAdmissionRefusal.parse(row.admissionRefusal), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapAccount(row: typeof schema.managedAccounts.$inferSelect): ManagedAccount { return { id: row.id, name: row.name, externalSource: row.externalSource, externalId: row.externalId, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapImportBatch(row: typeof schema.importBatches.$inferSelect): ImportBatch { return { id: row.id, source: row.source, snapshotDate: row.snapshotDate.toISOString(), snapshotRef: row.snapshotRef, attributionNote: row.attributionNote, importedCount: row.importedCount, skippedCount: row.skippedCount, quarantinedCount: row.quarantinedCount, logoFailureCount: row.logoFailureCount, staleCount: row.staleCount, details: row.details, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } type CatalogExposureState = "trusted" | "legacy_active" | "blocked"; function catalogExposureState( item: typeof schema.capabilityCatalogItems.$inferSelect, installation: typeof schema.capabilityInstallations.$inferSelect | null, ): CatalogExposureState { if ( capabilityCatalogItemIsTrustedForExposure({ source: item.source as CapabilitySource, stale: item.stale, authKind: item.authKind as CapabilityCatalogItem["authKind"], metadata: item.metadata, }) ) { return "trusted"; } // Rolling compatibility for installations enabled before registry probe // provenance existed. This is deliberately narrower than the normal trust // gate: only an already-active, non-stale, known-auth row with enable-time // connectivity evidence can continue. A present-but-non-real probe is an // explicit negative verdict and can never be grandfathered. if ( item.source !== registryCapabilitySource || item.stale || Object.prototype.hasOwnProperty.call(item.metadata, "mcpProbe") || !item.authKind || item.authKind === "unknown" || installation?.status !== "active" || !mcpConnectivityOk(installation.metadata) ) { return "blocked"; } const hasCredentialBinding = !!encryptedHeadersConfig(installation.config.headersEncrypted) || !!connectionRefConfig(installation.config.connectionRef); if (item.authModel && !hasCredentialBinding) { return "blocked"; } return "legacy_active"; } /** * A workspace's Microsoft Dynamics entry keeps its MCP address only in * `endpoint_url`: `mcp_url` takes part in the registry's cross-workspace * uniqueness, which two workspaces using one environment would break. */ function workspaceDynamicsMcpUrl(row: typeof schema.capabilityCatalogItems.$inferSelect) { return row.workspaceId && row.kind === "mcp" && row.endpointUrl && microsoftDynamicsProductForMcpUrl(row.endpointUrl) ? row.endpointUrl : null; } function mapCapabilityCatalogItem( row: typeof schema.capabilityCatalogItems.$inferSelect, exposure: "trusted" | "legacy_active" | "unverified" = capabilityCatalogItemIsTrustedForExposure({ source: row.source as CapabilitySource, stale: row.stale, authKind: row.authKind as CapabilityCatalogItem["authKind"], metadata: row.metadata, }) ? "trusted" : "unverified", ): CapabilityCatalogItem { const catalogTrust = exposure === "legacy_active" ? { state: "legacy_active" as const, reason: "active_installation_compatibility" as const, } : exposure === "trusted" ? { state: "trusted" as const, reason: row.source === registryCapabilitySource ? ("verified_probe" as const) : ("trusted_source" as const), } : { state: "unverified" as const, reason: "missing_verification" as const, }; const runtime = row.kind === "mcp" && row.endpointUrl ? { available: true, mcpServerId: mcpServerIdForCapability(row.id, row.metadata), transport: row.transport ?? "streamable-http", notes: row.authModel ? "Requires credential headers supplied in the enable request." : null, catalogTrust, } : { available: false, notes: row.kind === "mcp" ? "Remote streamable HTTP endpoint is required for runtime use." : null, catalogTrust, }; return { id: row.id, ...(row.accountId ? { accountId: row.accountId } : {}), ...(row.workspaceId ? { workspaceId: row.workspaceId } : {}), kind: row.kind as CapabilityKind, source: row.source as CapabilitySource, name: row.name, description: row.description, category: row.category, tags: row.tags, homepageUrl: row.homepageUrl, endpointUrl: row.endpointUrl, installUrl: row.installUrl, authModel: row.authModel, providerDomain: row.providerDomain, surfaceType: row.surfaceType, transport: row.transport, mcpUrl: row.mcpUrl ?? workspaceDynamicsMcpUrl(row), authKind: row.authKind as CapabilityCatalogItem["authKind"], credentialFacts: row.credentialFacts, tier: row.tier as CapabilityCatalogItem["tier"], provenance: row.provenance, logoAssetPath: row.logoAssetPath, importBatchId: row.importBatchId, stale: row.stale, staleAt: row.staleAt?.toISOString() ?? null, tools: [], runtime, // Lifecycle is projected with installation/connection truth by // @opengeni/core. A storage row on its own is only available for setup. lifecycle: { status: "available", readiness: runtime.available ? "setup_required" : "unavailable", detail: runtime.notes, managedBy: "workspace", }, actions: [], enabled: false, enabledReason: null, // Overwritten by applyCapabilityEnablement in @opengeni/core, which knows // the installation; a freshly-read catalog row carries no connection. connectionRef: null, metadata: row.metadata, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } /** * Each workspace projection opens its own RLS scope. On a pool handle those are * independent transactions and may run concurrently. On a transaction handle * they are savepoints on one backend that share its transaction-local tenant * settings, so they must run one at a time: concurrent savepoints overwrite each * other's scope, and the first failure ends the caller's transaction while the * rest still issue SAVEPOINT on the released backend. */ async function mapWorkspaceProjections( db: Database, rows: readonly Row[], project: (row: Row) => Promise, ): Promise { if (!isTransactionHandle(db)) return await Promise.all(rows.map(project)); const workspaces: Workspace[] = []; for (const row of rows) workspaces.push(await project(row)); return workspaces; } async function workspaceControlProjection( db: Database, workspaceId: string, ): Promise { const control = await findWorkspaceControlProjection(db, workspaceId); if (!control) throw new Error(`Workspace ${workspaceId} has no inference control`); return control; } async function findWorkspaceControlProjection( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, (scopedDb) => readWorkspaceControlProjection(scopedDb, workspaceId), ); } /** The caller owns the workspace scope and its tenancy fence. */ async function readWorkspaceControlProjection( db: Database, workspaceId: string, ): Promise { const [control] = await db .select() .from(schema.workspaceInferenceControls) .where(eq(schema.workspaceInferenceControls.workspaceId, workspaceId)) .limit(1); if (!control) return null; return { timer: control.timerId ? { id: control.timerId, action: control.timerAction as "pause" | "resume", dueAt: control.timerDueAt!.toISOString(), pauseForSeconds: control.timerPauseForSeconds, } : null, serverTime: new Date().toISOString(), state: control.workspaceState as "active" | "paused", revision: Number(control.revision), reason: control.reason, changedBy: control.changedBy, changedAt: control.changedAt?.toISOString() ?? null, }; } async function workspaceKindProjection( db: Database, row: Pick, ): Promise { return await withRlsContext(db, { accountId: row.accountId, workspaceId: row.id }, (scopedDb) => readWorkspaceKindProjection(scopedDb, row), ); } /** The caller owns the workspace scope and its tenancy fence. */ async function readWorkspaceKindProjection( db: Database, row: Pick, ): Promise { const [kind] = await rawRows<{ kind: string }>( db, sql`select get_workspace_kind(${row.accountId}::uuid, ${row.id}::uuid) as kind`, ); if (kind?.kind !== "personal" && kind?.kind !== "shared") { throw new Error(`Workspace ${row.id} has no canonical kind`); } return kind.kind; } function mapWorkspace( row: typeof schema.workspaces.$inferSelect, inferenceControl: Workspace["inferenceControl"], kind: Workspace["kind"], ): Workspace { return { id: row.id, accountId: row.accountId, kind, name: row.name, slug: row.slug, externalSource: row.externalSource, externalId: row.externalId, agentInstructions: row.agentInstructions ?? null, settings: (row.settings ?? {}) as Record, inferenceControl, defaultRigId: row.defaultRigId ?? null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapCapabilityInstallation( row: typeof schema.capabilityInstallations.$inferSelect, ): CapabilityInstallation { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, capabilityId: row.capabilityId, kind: row.kind as CapabilityKind, status: row.status as CapabilityInstallationStatus, config: projectInstallationConfig(row.config), metadata: row.metadata, enabledAt: row.enabledAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } /** * Stored credential-header ciphertext never leaves the database through the * generic installation mapping — callers see only the sorted header names. * The runtime reads ciphertext through listEnabledMcpCapabilityServers and * the enable flow through getStoredCapabilityHeaderCiphertext. */ function projectInstallationConfig(config: Record): Record { const headersEncrypted = encryptedHeadersConfig(config.headersEncrypted); if (!headersEncrypted) { return config; } const { headersEncrypted: _omitted, ...rest } = config; return { ...rest, headerNames: Object.keys(headersEncrypted).sort() }; } function mapSlackBotPostOperation( row: typeof schema.slackBotPostOperations.$inferSelect, ): SlackBotPostOperation { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, connectionId: row.connectionId, operationId: row.operationId, clientMessageId: row.clientMessageId, targetKind: row.targetKind, targetId: row.targetId, requestDigest: row.requestDigest, status: row.status, claimHolderId: row.claimHolderId, claimExpiresAt: row.claimExpiresAt, claimMode: row.claimMode, attemptCount: row.attemptCount, lastFailureCode: row.lastFailureCode, slackChannelId: row.slackChannelId, slackMessageTimestamp: row.slackMessageTimestamp, completedAt: row.completedAt, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } function mapSlackBotUpdateOperation( row: typeof schema.slackBotUpdateOperations.$inferSelect, ): SlackBotUpdateOperation { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, connectionId: row.connectionId, operationId: row.operationId, slackChannelId: row.slackChannelId, slackMessageTimestamp: row.slackMessageTimestamp, requestDigest: row.requestDigest, status: row.status, claimHolderId: row.claimHolderId, claimExpiresAt: row.claimExpiresAt, attemptCount: row.attemptCount, lastFailureCode: row.lastFailureCode, completedAt: row.completedAt, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } function mapSlackBotDeleteOperation( row: typeof schema.slackBotDeleteOperations.$inferSelect, ): SlackBotDeleteOperation { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, connectionId: row.connectionId, operationId: row.operationId, principalType: row.principalType, principalId: row.principalId, toolName: row.toolName as "slack_bot_delete_message", channelId: row.channelId, messageTimestamp: row.messageTimestamp, requestDigest: row.requestDigest, status: row.status, claimHolderId: row.claimHolderId, claimExpiresAt: row.claimExpiresAt, attemptCount: row.attemptCount, lastFailureCode: row.lastFailureCode, slackChannelId: row.slackChannelId, slackMessageTimestamp: row.slackMessageTimestamp, completedAt: row.completedAt, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } function mapKnowledgeMemory(row: typeof schema.knowledgeMemories.$inferSelect): KnowledgeMemory { return { id: row.id, workspaceId: row.workspaceId, status: row.status as KnowledgeMemoryStatus, kind: row.kind as KnowledgeMemoryKind, scope: row.scope, scopeType: row.scopeType, scopeSubjectId: row.scopeSubjectId ?? null, scopeSessionId: row.scopeSessionId ?? null, text: fromPostgresLosslessText(row.text, row.textCodecVersion), sourceRefs: Array.isArray(row.sourceRefs) ? (row.sourceRefs as KnowledgeSourceRef[]) : [], confidence: confidenceFromStorage(row.confidence), metadata: row.metadata, createdBySessionId: row.createdBySessionId, reviewedBy: row.reviewedBy, reviewedAt: row.reviewedAt ? row.reviewedAt.toISOString() : null, pinned: row.pinned, usageCount: row.usageCount, lastUsedAt: row.lastUsedAt ? row.lastUsedAt.toISOString() : null, supersedesId: row.supersedesId, supersededById: row.supersededById, validFrom: row.validFrom.toISOString(), validUntil: row.validUntil ? row.validUntil.toISOString() : null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapSocialConnection( row: Omit, ): SocialConnection { return { id: row.id, version: row.version, accountId: row.accountId, workspaceId: row.workspaceId, provider: row.provider as SocialProvider, accountHandle: row.accountHandle, accountName: row.accountName, externalAccountId: row.externalAccountId, ownership: row.subjectId ? "personal" : "workspace", status: row.status as SocialConnectionStatus, scopes: row.scopes, credentialRef: row.credentialRef, tokenMetadata: row.tokenMetadata, metadata: row.metadata, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function socialConnectionSubjectVisibility(subjectId?: string | null): SQL { return subjectId ? or( isNull(schema.socialConnections.subjectId), eq(schema.socialConnections.subjectId, subjectId), )! : isNull(schema.socialConnections.subjectId); } async function withSocialConnectionSubjectRls( db: Database, workspaceId: string, subjectId: string | null | undefined, fn: (db: Database) => Promise, ): Promise { return subjectId ? await withWorkspaceSubjectRls(db, workspaceId, subjectId, fn) : await withWorkspaceRls(db, workspaceId, fn); } function withHolder( key: ApiKey, row: typeof schema.apiKeys.$inferSelect, holders: Awaited>, ): ApiKey { if (row.credentialKind !== "organization") return key; const holder = row.serviceAccountId ? holders.get(row.serviceAccountId) : undefined; return { ...key, serviceAccount: holder ? { ...holder } : null }; } function mapApiKey(row: typeof schema.apiKeys.$inferSelect, workspaceIds?: string[]): ApiKey { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, name: row.name, description: row.description, prefix: row.prefix, permissions: row.permissions as Permission[], ...organizationApiKeyPolicyProjection(row, workspaceIds), expiresAt: row.expiresAt ? row.expiresAt.toISOString() : null, revokedAt: row.revokedAt ? row.revokedAt.toISOString() : null, lastUsedAt: row.lastUsedAt ? row.lastUsedAt.toISOString() : null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapGitHubInstallation( row: typeof schema.githubInstallations.$inferSelect, ): GitHubInstallation { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, installationId: row.installationId, githubAccountId: row.githubAccountId, accountLogin: row.accountLogin, accountType: row.accountType, repositoryScope: row.repositoryScope as GitHubRepositoryScope, linkedBySubjectId: row.linkedBySubjectId, githubActorId: row.githubActorId, githubActorLogin: row.githubActorLogin, authorityKind: row.authorityKind as GitHubInstallationAuthorityKind | null, authorityCheckedAt: row.authorityCheckedAt?.toISOString() ?? null, authorityExpiresAt: row.authorityExpiresAt?.toISOString() ?? null, authorityNonce: row.authorityNonce, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } function mapUsageEvent(row: typeof schema.usageEvents.$inferSelect): UsageEvent { return { ...(typeof row.initiatorContext?.tenantLabel === "string" ? { tenantLabel: row.initiatorContext.tenantLabel } : {}), id: row.id, workspaceId: row.workspaceId, accountId: row.accountId, subjectId: row.subjectId, eventType: row.eventType as UsageEvent["eventType"], quantity: row.quantity, unit: row.unit, sourceResourceType: row.sourceResourceType, sourceResourceId: row.sourceResourceId, idempotencyKey: row.idempotencyKey, occurredAt: row.occurredAt.toISOString(), recordedAt: row.recordedAt.toISOString(), exportedToBillingAt: row.exportedToBillingAt ? row.exportedToBillingAt.toISOString() : null, billingProviderEventId: row.billingProviderEventId, }; } function mapSocialPost(row: typeof schema.socialPosts.$inferSelect): SocialPost { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, connectionId: row.connectionId, provider: row.provider as SocialProvider, externalPostId: row.externalPostId, url: row.url, authorHandle: row.authorHandle, text: row.text, publishedAt: row.publishedAt.toISOString(), metrics: row.metrics, raw: row.raw, createdAt: row.createdAt.toISOString(), }; } function stringArrayConfig(value: unknown): string[] | undefined { if (!Array.isArray(value)) { return undefined; } const values = value.filter( (item): item is string => typeof item === "string" && item.trim().length > 0, ); return values.length > 0 ? [...new Set(values.map((item) => item.trim()))] : undefined; } function sessionMcpApprovalPolicyConfig(value: unknown): SessionMcpApprovalPolicy | undefined { const parsed = SessionMcpApprovalPolicySchema.safeParse(value); return parsed.success ? parsed.data : undefined; } /** Resolve explicit configuration before the provider recommendation. */ export function resolveMcpApprovalRecommendation( rawConfigValue: unknown, rawMetadataValue: unknown, ): SessionMcpApprovalPolicy | undefined { return sessionMcpApprovalPolicyConfig(rawConfigValue ?? rawMetadataValue); } /** @deprecated Compatibility alias. Recommendations never impose an approval floor. */ export function requireApprovalWithFloor( rawConfigValue: unknown, rawMetadataValue: unknown, _isGlobalRow: boolean, ): SessionMcpApprovalPolicy | undefined { return resolveMcpApprovalRecommendation(rawConfigValue, rawMetadataValue); } function cleanDbString(value: string | undefined | null): string | undefined { const trimmed = value?.trim(); return trimmed ? trimmed : undefined; } function requireDbString(value: string, field: string): string { const trimmed = cleanDbString(value); if (!trimmed) { throw new Error(`${field} is required`); } return trimmed; } function confidenceToStorage(value: number): number { if (!Number.isFinite(value)) { return 50; } return Math.round(Math.min(Math.max(value, 0), 1) * 100); } function confidenceFromStorage(value: number): number { return Number((Math.min(Math.max(value, 0), 100) / 100).toFixed(2)); } function positiveIntegerConfig(value: unknown): number | undefined { if (typeof value === "number" && Number.isInteger(value) && value > 0) { return value; } if (typeof value === "string" && /^\d+$/.test(value) && Number(value) > 0) { return Number(value); } return undefined; } function booleanConfig(value: unknown): boolean | undefined { return typeof value === "boolean" ? value : undefined; } function encryptedHeadersConfig(value: unknown): Record | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) { return undefined; } const entries = Object.entries(value as Record).filter( (entry): entry is [string, string] => typeof entry[1] === "string" && entry[1].length > 0, ); return entries.length > 0 ? Object.fromEntries(entries) : undefined; } function mcpConnectivityOk(metadata: Record): boolean { const value = metadata.mcpConnectivity; return ( !!value && typeof value === "object" && "status" in value && (value.status === "ok" || value.status === "auth_deferred") ); } function connectionRefConfig(value: unknown): McpServerConnectionRef | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) { return undefined; } const record = value as Record; if (typeof record.providerDomain !== "string" || record.providerDomain.length === 0) { return undefined; } const ref: McpServerConnectionRef = { providerDomain: record.providerDomain }; if (record.authoritySource === "host") { ref.authoritySource = "host"; } if (typeof record.connectionId === "string" && record.connectionId.length > 0) { ref.connectionId = record.connectionId; } if (typeof record.provider === "string" && record.provider.length > 0) { ref.provider = record.provider; } if ( typeof record.kind === "string" && ["oauth2", "api_key", "app_install", "delegated"].includes(record.kind) ) { ref.kind = record.kind as ConnectionKind; } if (Array.isArray(record.scopes)) { const scopes = record.scopes.filter( (scope): scope is string => typeof scope === "string" && scope.length > 0, ); if (scopes.length > 0) { ref.scopes = scopes; } } if (typeof record.resource === "string" && record.resource.length > 0) { ref.resource = record.resource; } if (Array.isArray(record.selectedResources)) { const selectedResources = record.selectedResources.flatMap((candidate) => { if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) { return []; } const resource = candidate as Record; return resource.kind === "repository" && typeof resource.id === "string" && resource.id.length > 0 ? [{ kind: "repository" as const, id: resource.id }] : []; }); if (selectedResources.length > 0) { ref.selectedResources = selectedResources; } } if (record.subjectScope === "workspace" || record.subjectScope === "subject") { ref.subjectScope = record.subjectScope; } if ( record.accountSelection === "all_eligible" && record.connectionId === undefined && record.authoritySource !== "host" && record.selectedResources === undefined ) { ref.accountSelection = "all_eligible"; } return ref; } function shortHash(value: string): string { let hash = 0x811c9dc5; for (let index = 0; index < value.length; index += 1) { hash ^= value.charCodeAt(index); hash = Math.imul(hash, 0x01000193); } return (hash >>> 0).toString(36).padStart(7, "0").slice(0, 7); } function connectionBrokerDeps(): ConnectionBrokerDeps { return { loadCredential: loadConnectionCredentialForBroker, recordRefresh: recordConnectionTokenRefresh, setStatus: setConnectionStatus, recordUsed: recordConnectionUsed, refresh: refreshOAuthConnectionCredentialCore, encrypt: encryptEnvironmentValue, keyBytes: environmentsEncryptionKeyBytes, now: () => new Date(), authorizeAcceptedUse: resolveAcceptedConnectionUse, }; } export function buildConnectionTokenResolver( db: Database, settings: Settings, deps: ConnectionBrokerDeps = connectionBrokerDeps(), options: ConnectionTokenResolverOptions = {}, ): ReturnType { return buildConnectionTokenResolverCore(db, settings, deps, options); } export { buildCodexTokenResolver, withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun, type CodexCredentialPlanRecheck, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver"; export { ConnectionNotRefreshableError, ConnectionRefreshHttpError, isPrivateAddress, normalizeBearerScheme, refreshOAuthConnectionCredential, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionCredentialLookupInput, type ConnectionNeedsReauth, type ConnectionStatusGuard, type ConnectionTokenRefreshInput, type ConnectionTokenResolverOptions, type CredentialReferenceResolution, type PermanentConnectionRefreshFailure, type RefreshTransportOptions, type ResolveConnectionCredentialInput, type ResolveConnectionCredentialResult, } from "./connection-token-resolver"; export { CapabilityComponentVersionConflictError, cleanupOrphanedCapabilityComponents, effectiveCapabilityOwnerSql, type CapabilityComponentOwnerIdentity, } from "./capability-components"; export { checkpointPluginPackageOperation, deferPluginPackageOperation, finalizePluginPackageInstall, getInstalledPluginPackage, getPluginPackageUninstallPreview, PluginUninstallPreviewChangedError, installPluginMcpReference, listInstalledPluginPackages, PluginInstallationVersionConflictError, PluginInstallationVersionRequiredError, PluginOperationIdempotencyError, preparePluginPackageInstall, uninstallPluginPackage, type InstalledPluginPackage, type InstalledPluginPackageSummary, type PluginBomComponent, type PreparedPluginPackage, } from "./plugin-packages"; export * from "./workspace-artifacts"; export * from "./mcp-oauth"; export * from "./mcp-auto-connect"; export * from "./id-jag-issuer"; export * from "./tool-gateway-approvals"; export * from "./site-tool-allowances"; export * from "./workspace-member-execution-defaults"; export * from "./recordings"; export * from "./recording-live"; export { cosineSimilarity, memberVoiceprints, recordingVoiceChannel, suggestSpeakersByVoice, voiceMatchingVoiceprints, VOICE_SUGGESTION_THRESHOLD, type KnownVoice, type RecordingSpeakerVoice, type RecordingVoiceChannel, } from "./recording-voices"; export * from "./editable-artifacts"; export * from "./editable-artifact-materialization"; export * from "./attempt-tool-catalogs"; export * from "./model-context-snapshots"; export * from "./session-content-blobs"; export * from "./session-content-compaction"; export * from "./session-content-garbage"; export * from "./session-secret-redaction"; export * from "./session-archive"; export * from "./session-unattended"; export * from "./codemode-operations"; export * from "./codemode-approvals"; export * from "./tool-action-reviews"; export * from "./browser-sessions"; export * from "./browser-deadline-checkpoints"; export * from "./sandbox-interaction-idle"; export * from "./computer-sessions"; export * from "./browser-identities"; export * from "./browser-state-artifacts"; export * from "./browser-auth"; export * from "./browser-downloads"; export * from "./attached-browser-devices"; export * from "./interaction-revisions"; export * from "./interaction-placement-loss"; export * from "./canonical-human-identities"; export * from "./managed-auth-session-sets"; export * from "./organization-recovery"; export * from "./active-sandbox"; export * from "./personal-machine-access"; export * from "./session-tenancy"; export * from "./governed-learning-activation"; export * from "./event-triggers"; export * from "./mcp-event-subscriptions"; export * from "./event-source-feeds"; export * from "./automation-templates"; export * from "./organization-model-providers"; export * from "./organization-compatible-model-endpoints"; export * from "./organization-anthropic-api-keys"; export * from "./workspace-model-key-list-price"; export * from "./organization-model-defaults"; export * from "./session-admin-access"; export * from "./subscription-core-claude-oauth"; export { setWorkspacePauseTimerInTransaction, fireWorkspacePauseTimerInTransaction, } from "./session-control"; export async function listDueWorkspacePauseTimers(db: Database, limit = 100) { return await rawRows<{ workspace_id: string; timer_id: string }>( db, sql`select * from opengeni_private.list_due_workspace_pause_timers(${limit})`, ); } export * from "./feedback"; export * from "./console"; export * from "./console-roles"; export * from "./session-final-reply"; export * from "./knowledge-entries"; export * from "./knowledge-indexing"; import type { ConnectorToolPermission } from "@opengeni/contracts"; export * from "./knowledge-document-preparation"; export async function listConnectorToolPermissionPolicies( db: Database, input: { accountId: string; workspaceId: string; connectionId: string }, ) { return withRlsContext(db, input, async (tx) => tx .select() .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.connectionId), ), ) .orderBy(asc(schema.connectorActionPolicies.id)), ); } /** A reset notice lasts until that exact policy version is changed by the user. */ export async function listChangedConnectorToolPermissions( db: Database, input: { accountId: string; workspaceId: string; connectionId: string; serverId: string }, ): Promise { return withRlsContext(db, input, async (tx) => { const rows = await tx .selectDistinct({ toolName: schema.connectorActionPolicies.toolName }) .from(schema.connectorActionPolicies) .innerJoin( schema.auditEvents, and( eq(schema.auditEvents.workspaceId, input.workspaceId), eq(schema.auditEvents.action, "connector.action.policy_reset"), sql`${schema.auditEvents.targetId} = ${schema.connectorActionPolicies.id}::text`, sql`${schema.auditEvents.metadata}->>'version' = ${schema.connectorActionPolicies.version}::text`, ), ) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.connectionId), eq(schema.connectorActionPolicies.serverId, input.serverId), eq(schema.connectorActionPolicies.policy, "ask"), ), ) .limit(2048); return rows.map((row) => row.toolName); }); } /** All tools in a group change together, and never exceed the attempt snapshot bound. */ export async function updateConnectorToolPermissionPolicies( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; connectionId: string; serverId: string; toolNames: string[]; policy: ConnectorToolPermission | null; actionName?: string; expectedRevision?: string; }, ): Promise { await withRlsContext(db, input, async (scoped) => scoped.transaction(async (tx) => { await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`connector-tool-permissions:${input.workspaceId}`}, 0))`, ); const existing = await tx .select() .from(schema.connectorActionPolicies) .where(eq(schema.connectorActionPolicies.workspaceId, input.workspaceId)); if ( input.expectedRevision !== undefined && input.expectedRevision !== connectorToolPolicyRevision(existing, input.connectionId, input.serverId) ) { throw new ConnectorToolPermissionConflictError(); } const names = [...new Set(input.toolNames)].sort((left, right) => left.localeCompare(right)); // A whole-tool choice replaces its action exceptions. Reset removes only // the selected overrides and reveals the inherited recommendation again. const removed = input.policy !== null && input.actionName !== undefined ? [] : await tx .delete(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.connectionId), eq(schema.connectorActionPolicies.serverId, input.serverId), inArray(schema.connectorActionPolicies.toolName, names), ...(input.actionName !== undefined ? [eq(schema.connectorActionPolicies.actionName, input.actionName)] : []), ...(input.policy !== null ? [ne(schema.connectorActionPolicies.actionName, "*")] : []), ), ) .returning(); if (removed.length) await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "connector.action.preferences_replaced", targetType: "connector_action_policy", targetId: input.connectionId, metadata: { serverId: input.serverId, policyIds: removed.map((row) => row.id), reset: input.policy === null, }, }, "metadata", "metadataCodecVersion", ), ); if (input.policy === null) return; const added = names.filter( (name) => !existing.some( (row) => row.connectionId === input.connectionId && row.serverId === input.serverId && row.toolName === name && row.actionName === (input.actionName ?? "*"), ), ); if (existing.length - removed.length + added.length > 2048) throw new Error("The workspace tool permission limit has been reached"); for (const toolName of names) { await upsertConnectorActionPolicy(tx, { ...input, policy: input.policy, toolName, actionName: input.actionName ?? "*", }); } }), ); } /** * Gives one connection the tool choices another connection of the same * provider account holds (its counterpart under the other integration * backend), each in its own login's home workspace. With `serverId`, only that * connector's choices are mirrored: the target's are replaced by the source's, * so a reset is mirrored too. Without it, everything is copied only when the * target has no choices yet: a choice already made there wins. Copies keep who * made each choice and when. Returns how many choices the target now carries * from the source. */ export async function copyConnectorToolPermissionPolicies( db: Database, input: { accountId: string; subjectId: string; from: { workspaceId: string; connectionId: string }; to: { workspaceId: string; connectionId: string }; serverId?: string; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.to.workspaceId }, async (scoped) => scoped.transaction(async (tx) => { // Both workspaces' choice locks, in a fixed order, so the source is // read as last committed: an older edit's copy never lands after a // newer one's. for (const workspaceId of [ ...new Set([input.from.workspaceId, input.to.workspaceId]), ].sort()) await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`connector-tool-permissions:${workspaceId}`}, 0))`, ); // The source login's home, read under that workspace's tenant scope // inside this transaction (as a turn reads a followed login's choices). const source = ( await withRlsContext( tx, { accountId: input.accountId, workspaceId: input.from.workspaceId }, async (home) => await home .select() .from(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.from.workspaceId), eq(schema.connectorActionPolicies.connectionId, input.from.connectionId), ), ) .orderBy(asc(schema.connectorActionPolicies.id)), undefined, "none", ) ).filter((row) => input.serverId === undefined || row.serverId === input.serverId); if (input.serverId === undefined && source.length === 0) return 0; const existing = await tx .select() .from(schema.connectorActionPolicies) .where(eq(schema.connectorActionPolicies.workspaceId, input.to.workspaceId)); const target = existing.filter( (row) => row.connectionId === input.to.connectionId && (input.serverId === undefined || row.serverId === input.serverId), ); if (input.serverId === undefined && target.length > 0) return 0; if (existing.length - target.length + source.length > 2048) throw new Error("The workspace tool permission limit has been reached"); const removed = target.length ? await tx .delete(schema.connectorActionPolicies) .where( inArray( schema.connectorActionPolicies.id, target.map((row) => row.id), ), ) .returning({ id: schema.connectorActionPolicies.id }) : []; const inserted: { id: string }[] = []; for (let offset = 0; offset < source.length; offset += 128) inserted.push( ...(await tx .insert(schema.connectorActionPolicies) .values( source.slice(offset, offset + 128).map((row) => ({ accountId: input.accountId, workspaceId: input.to.workspaceId, connectionId: input.to.connectionId, serverId: row.serverId, toolName: row.toolName, actionName: row.actionName, policy: row.policy, createdBySubjectId: row.createdBySubjectId, updatedBySubjectId: row.updatedBySubjectId, createdAt: row.createdAt, updatedAt: row.updatedAt, })), ) .returning({ id: schema.connectorActionPolicies.id })), ); if (removed.length || inserted.length) await tx.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.to.workspaceId, subjectId: input.subjectId, action: "connector.action.preferences_replaced", targetType: "connector_action_policy", targetId: input.to.connectionId, metadata: { ...(input.serverId !== undefined ? { serverId: input.serverId } : {}), policyIds: removed.map((row) => row.id), carriedPolicyIds: inserted.map((row) => row.id), carriedFromConnectionId: input.from.connectionId, reset: false, }, }, "metadata", "metadataCodecVersion", ), ); return inserted.length; }), ); } /** Resolve only the selected immutable customer model connection; no deployment fallback. */ export async function loadDirectModelProviderConnection( db: Database, settings: Settings, workspaceId: string, modelId: string, connectionMetadata?: readonly ConnectionMetadataWithVerification[], ) { if (!isDirectModelId(modelId)) return null; const metadata = ( connectionMetadata ?? (await listConnectionsMetadata(db, workspaceId, null)) ).find((candidate) => directModelConnectionSpec(candidate)?.modelId === modelId); if (!metadata) throw new Error("This model connection is no longer available"); const connection = await loadConnectionCredentialForBroker(db, settings, { workspaceId, connectionId: metadata.id, providerDomain: metadata.providerDomain, kind: "api_key", allowSubjectOwned: false, }); if ( !connection || directModelConnectionSpec(connection)?.modelId !== modelId || typeof connection.credential.apiKey !== "string" || !connection.credential.apiKey.trim() ) { throw new Error("This model connection changed; reconnect and select its model"); } await assertModelConnectionAllowsTurn(db, { workspaceId, subjectId: "worker:model-access", modelId, workspaceProviderConnectionId: connection.id, }); return { ...metadata, apiKey: connection.credential.apiKey }; } export { apiIntegrationToolEffect } from "./api-integration-approvals"; export { subscriptionCoreProvider, subscriptionCoreProviderIds, } from "./subscription-core-providers"; export { placeSubscriptionCoreTurnWithFailover, evaluateSubscriptionCorePlacementWithFailover, type SubscriptionCoreFailoverPlacement, } from "./subscription-core/failover"; export { type SubscriptionCoreFailoverModel } from "./subscription-core/failover-world"; export { readSubscriptionCoreFailoverProvider } from "./subscription-core/failover-readiness"; export { recordSubscriptionCoreServingPolicyForTurnAttempt, readSubscriptionCoreServingPolicyForTurn, readSubscriptionCoreTurnFailoverBudget, SubscriptionCoreServingFailoverLimitError, SUBSCRIPTION_CORE_SERVING_FAILOVER_LIMIT, } from "./subscription-core/serving-policy"; export { readSubscriptionHistoryProvenance } from "./subscription-core/serving-runtime"; export * from "./session-usage-limits"; export * from "./boot-connect"; export * from "./teams-conversations"; export * from "./teams-private-session"; export * from "./teams-routing"; export { recordMachinePromotionProof } from "./promotion-abuse";