export * from "./billing-credit-notifications.js"; export { continueSessionWaitingWork, getSessionMachineAccess } from "./session-machine-access.js"; export { canonicalSecretPermissions } from "./canonical-secret-permissions.js"; export * from "./site-session-access.js"; export * from "./app-sync.js"; export * from "./app-webhooks.js"; export * from "./app-server.js"; export * from "./site-tool-data.js"; export * from "./app-package-exports.js"; export * from "./organization-connectors.js"; import { type OrganizationConnectorRow } from "./organization-connectors.js"; export { turnUsageByTurn, withTurnUsage } from "./turn-credit-usage.js"; export { listExhaustedScheduledTasks, retireExhaustedScheduledTask, listScheduledTaskScheduleReconciliations, acknowledgeScheduledTaskScheduleReconciliation, deferScheduledTaskScheduleReconciliation, } from "./scheduled-task-lifecycle.js"; export * from "./scheduled-task-blockers.js"; export * from "./session-target.js"; export * from "./session-resource-removal.js"; export * from "./session-repository-attach.js"; export * from "./github-gateway.js"; export * from "./active-session-history.js"; import type { ActiveSessionHistoryFootprint } from "./active-session-history.js"; export * from "./session-search-records.js"; export * from "./session-first-request-tools.js"; export * from "./console-sign-in-audit.js"; export * from "./model-call-timing.js"; export * from "./sandbox-stop-notice.js"; export * from "./turn-timing-profile.js"; export * from "./turn-timing-profile-store.js"; export * from "./model-provider-execution-inputs.js"; export * from "./workspace-model-catalog-inputs.js"; import { type ModelCallTiming } from "./model-call-timing.js"; export * from "./human-input-secret-answers.js"; export * from "./secret-use-approvals.js"; export * from "./personal-connection-approval.js"; export * from "./credential-profiles.js"; export * from "./connected-machine-audience.js"; export * from "./disconnect-audit.js"; import { type ActiveSandboxPointer } from "./active-sandbox.js"; import { type SubscriptionReconnectAccount } from "@opengeni/contracts/subscription-capacity-wait"; import { type PreparedSecretAnswer } from "./human-input-secret-answers.js"; import { type SecretUseApprovalRow } from "./secret-use-approvals.js"; import type { VaultDbContext } from "./vaults.js"; export * from "./organization-slack-bots.js"; export * from "./slack-agents.js"; export * from "./agents.js"; export * from "./organization-agent-runtime.js"; export * from "./organization-agents.js"; export * from "./organization-agent-compute.js"; export { WorkspaceNotFoundError } from "./database.js"; export * from "./slack-agent-proposals.js"; export * from "./slack-agent-updates.js"; export * from "./voice-transcription-settlement.js"; import { type ConnectionMetadataWithVerification } from "./connection-metadata.js"; import { type DisconnectAuditActor } from "./disconnect-audit.js"; export { getConnectionMetadata, getConnectionMetadataByIds, getProviderConnectionHomeWorkspace, listConnectionsMetadata, type ConnectionMetadataWithVerification, } from "./connection-metadata.js"; export { readCreditPromotionPolicy } from "./credit-promotion-policy.js"; export * from "./subscription-plans.js"; export * from "./billing-auto-top-up.js"; export * from "./card-verification.js"; export * from "./billing-auto-top-up-notifications.js"; export { applyCreditLedgerEntry, applyCreditLedgerEntryOnce } from "./credit-ledger.js"; export { getBillingCustomer } from "./billing-customer.js"; export * from "./subscription-plan-maintenance.js"; import { type CreditUsage } from "./credit-balances.js"; export { apiSpendableCreditMicros, byokFeeSpendableMicros, chargeBillingOrigin, getBillingBalance, getByokFeeSpendableBalance, getSpendableCreditBalance, spendableCreditMicros, toolCreditUsage, VOICE_CREDIT_USAGE, type CreditUsage, } from "./credit-balances.js"; import { type TurnAttemptFenceRejectReason } from "./session-attempt-fence.js"; export type { TurnAttemptFenceRejectReason } from "./session-attempt-fence.js"; export { lockTurnAttemptWriteFenceTx } from "./session-attempt-fence.js"; import type { TurnAttemptEventFenceResult, TurnAttemptFenceResult } from "./session-attempt-fence.js"; 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.js"; export { effectiveSessionPolicyQuery } from "./session-execution-policy.js"; import { type CapabilitySetupContinuationSkipReason, AppShotCapture, type ModelCallProcessingResidencyV1, type PromptCacheDiagnostics, type PromptCacheObservation, type SessionUnattendedSetting, type SessionRemovedRepository } from "@opengeni/contracts"; import { type ResolvedConnectorActionPolicy } from "./connector-action-policy.js"; export { resolveConnectorActionPolicy, connectorActionPolicyDecision, projectConnectorToolPermission, connectorActionPoliciesForAccountRoutes, connectorToolPolicyRevision, ConnectorToolPermissionConflictError, withMinimumConnectorDecision, type ResolvedConnectorActionPolicy, } from "./connector-action-policy.js"; export { lockLiveNativeOriginalOriginTx, type ModalNativeLiveOriginScope, type ModalNativeLiveOriginProjection, type ModalNativeLiveOriginResult, } from "./modal-native-live-origin.js"; export { SubscriptionAccountChangedError } from "./subscription-account-conflict.js"; 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.js"; export { assertSubscriptionCoreAcceptedTurn, withSubscriptionCoreAcceptedTurn, type SubscriptionCoreAcceptedTurnAccessResult, type SubscriptionCoreAcceptedTurnIdentity, type SubscriptionCoreRefreshResult, type SubscriptionCorePlacementWorldRequest, type SubscriptionCorePlacementWorldResult, } from "./subscription-core-placement-world.js"; export { codexSubscriptionAuthorityV2ForAcceptanceInTransaction, codexSubscriptionAuthorityV2ForScheduledTaskInTransaction, persistSubscriptionCodexRefresh, persistSubscriptionCodexRefreshWithPlan, withSubscriptionCoreCodexRefreshLock, withSubscriptionCorePlacementWorld, type SubscriptionCoreCodexRefreshResult, } from "./subscription-core-codex-bindings.js"; import type { GoalAdmissionPausedReason } from "@opengeni/contracts"; import { type SessionAvatar } from "@opengeni/contracts"; import { type SessionLink, type SessionWaitingOn } from "@opengeni/contracts"; import { SubscriptionPersonalAuthorityV2 } from "@opengeni/contracts"; export declare const getScheduledTaskClaudeProviderAccountAuthoritySnapshot: (db: Database, workspaceId: string, taskId: string) => Promise<{ version: 1; scope: "organization"; } | { version: 1; scope: "workspace"; } | { version: 1; scope: "user"; authorityGeneration: number; }>; export declare const getSessionTurnClaudeProviderAccountAuthoritySnapshot: (db: Database, workspaceId: string, sessionId: string, turnId: string) => Promise<{ version: 1; scope: "organization"; } | { version: 1; scope: "workspace"; } | { version: 1; scope: "user"; authorityGeneration: number; }>; export declare const getSessionParentClaudeProviderAccountAuthority: (db: Database, workspaceId: string, childSessionId: string) => Promise; export { getScheduledTaskSubscriptionAuthority, receiverCodexSubscriptionAuthorityV2InTransaction, } from "./accepted-subscription-authority.js"; import { type BillingOrigin } from "@opengeni/contracts"; import { type OrganizationAccessPolicy, type UpdateOrganizationApiKeyRequest } from "@opengeni/contracts"; export { OrganizationApiKeyWorkspaceScopeError } from "./organization-api-key-access.js"; export * from "./personal-api-keys.js"; export * from "./organization-privacy-preferences.js"; export * from "./organization-inference-residency.js"; export * from "./workspace-content-flow.js"; export { createOrganizationServiceAccount, deleteOrganizationServiceAccount, effectiveKeyPermissions, getOrganizationServiceAccount, listOrganizationServiceAccounts, OrganizationServiceAccountNotFoundError, OrganizationServiceAccountRoleError, updateOrganizationServiceAccount, } from "./organization-service-accounts.js"; import { CreditDebitAttribution } from "./credit-debit-attribution.js"; export { acceptSessionFileAttachments, readSessionFileAttachments, type SessionAttachmentReadAccess, } from "./session-file-attachments.js"; export { SessionCreateConnectionSelectionUnavailableError, parseConnectionAccountIntent, } from "./mcp-account-bindings.js"; import { SandboxCheckpointSelection, SandboxRecoveryResponse, SandboxFreshWorkspaceReason, type SandboxRecoveryProjection, type SandboxRecoveryRequest, ModalRouterProviderCommand, type SessionTurnSurface } from "@opengeni/contracts"; import { type ConfigurationEffort } from "@opengeni/codex"; export { getSessionAttemptMcpApprovalPolicies } from "./session-mcp-approval.js"; export { SessionRetryConflictError, getSessionRetryReceiptInTransaction } from "./session-retry.js"; import { retainedProviderCommandPersistence as retainedProviderCommandState } from "./retained-provider-commands.js"; export declare const retryFailedSessionInTransaction: (db: SessionActivityDatabase, input: Parameters<(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; request: import("@opengeni/contracts").SessionRetryRequest; executionPolicy: TurnExecutionPolicyV1; }, sessionEffectiveSandboxRecoveryBlocked: (db: Database, session: typeof schema.sessions.$inferSelect) => Promise) => Promise>[1]) => Promise<{ outcome: "accepted" | "replayed"; turnId: string; failureEventId: string; } & { eventIds: string[]; }>; export * from "./codex-plan-entitlement.js"; export * from "./subscription-core-codex.js"; export * from "./subscription-core-codex-apps.js"; export * from "./subscription-core-codex-compat.js"; export type { CodexAccountStatus, CodexRotationSettings, EffectiveCodexSubscriptionSource, WorkspaceCodexSubscriptionMode, WorkspaceCodexSubscriptionSource, } from "./codex-account-types.js"; export * from "./subscription-core-codex-operations.js"; export * from "./subscription-core-codex-requests.js"; export * from "./subscription-core-codex-connections.js"; export * from "./subscription-core-codex-catalog.js"; export * from "./subscription-settings.js"; export { readSubscriptionCoreFunding, readSubscriptionCoreReadiness, } from "./subscription-core/funding-readiness.js"; export { subscriptionCoreTurns, readSubscriptionCoreTurnModel, type SubscriptionCoreCredential, type SubscriptionCoreLeaseRef, type SubscriptionCorePlacement, type SubscriptionCorePlacementRequest, } from "./subscription-core/turns.js"; export { subscriptionCoreRequests, type SubscriptionCoreRequestOutcome, } from "./subscription-core/requests.js"; export { subscriptionCoreSettlement, type SubscriptionCoreSettlement, } from "./subscription-core/settlement.js"; export { listSubscriptionCoreServingConnections, subscriptionCoreConnectionAllowlist, subscriptionCoreConnectionAllowsModel, subscriptionCoreWorkspaceReady, type SubscriptionCoreServingConnection, } from "./subscription-core/catalog.js"; export { SubscriptionCoreError } from "./subscription-core/errors.js"; export * from "./subscription-usage-pool.js"; export type { SubscriptionCoreProvider } from "./subscription-core/provider.js"; export { buildSubscriptionCoreTurnTokenResolver } from "./subscription-core/turn-token-resolver.js"; export * from "./subscription-core-xai-adapter.js"; export * from "./subscription-core-xai.js"; export * from "./subscription-core-claude-usage.js"; export * from "./subscription-core-claude-reads.js"; export * from "./subscription-core-claude-limit-resets.js"; export { subscriptionCoreOperations, type SubscriptionCoreFetch, type SubscriptionCoreOperationLeaseRef, type SubscriptionCoreOperationScope, } from "./subscription-core/operations.js"; export { subscriptionCoreOperationConnections, type SubscriptionCoreConnectionToken, type SubscriptionCoreOperationCandidate, type SubscriptionCoreUsageProbe, } from "./subscription-core/operation-connections.js"; export { readSubscriptionCoreWorkspaceView, renameSubscriptionCoreConnection, setSubscriptionCoreAllocator, setSubscriptionCorePrimary, setSubscriptionCoreRotation, type SubscriptionCoreConnectionReach, type SubscriptionCoreConnectionRow, type SubscriptionCoreWake, type SubscriptionCoreWorkspaceView, } from "./subscription-core/administration.js"; export { disconnectSubscriptionCoreConnection, resolveSubscriptionCoreRouteConnectionId, type SubscriptionCoreConnectRefusal, type SubscriptionCoreDisconnectAudit, type SubscriptionCoreDisconnectOutcome, } from "./subscription-core/connections.js"; export { withSubscriptionAccountAdministrators, type SubscriptionAccountAdministratorResolver, type SubscriptionAccountAdministratorStamp, } from "./subscription-core/account-administrator.js"; export * from "./subscription-core-xai-compat.js"; export * from "./subscription-core-claude-adapter.js"; export * from "./subscription-core-claude.js"; export * from "./subscription-core-claude-compat.js"; export { subscriptionCoreAdministeredConnections, SUBSCRIPTION_CORE_ADMINISTERED_READ_TIMEOUT_MS, type SubscriptionCoreAdministeredJoinedFetch, type SubscriptionCoreAdministeredProbeDeps, type SubscriptionCoreAdministeredScope, } from "./subscription-core/administered-connections.js"; export { listOwnSubscriptionCoreConnections, subscriptionCorePersonalConnections, type OwnSubscriptionCoreConnection, type SubscriptionCorePersonalConnection, } from "./subscription-core/personal-connections.js"; import { type SubscriptionCoreCodexWake } from "./subscription-core-codex-compat.js"; export { pinSubscriptionCoreSessionCodexAccount } from "./subscription-core-codex-compat.js"; export * from "./scheduled-task-access.js"; export { buildSlackApiRateLimiter } from "./slack-api-rate-limits.js"; export { admitMcpConnectionRateLimit } from "./mcp-connection-rate-limits.js"; export * from "./scheduled-human-wait.js"; import { SUBSCRIPTION_CORE_WAIT_EXHAUSTED_CODES } from "./codex-capacity-recovery.js"; import { type SessionAdmissionFence, StoredSessionAdmissionBlock } from "./session-admission-block.js"; export type { SessionAdmissionFence, StoredSessionAdmissionBlock } from "./session-admission-block.js"; import { SessionMessageSearchRequest, type SessionMessageSearchResponse } from "@opengeni/contracts"; import { ResolvedAgentConfig } from "@opengeni/contracts"; import { type SubscriptionCoreWakeScope } from "./subscription-core/waiters.js"; 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.js"; import type { SubscriptionCoreProviderWake } from "./subscription-core/session-choice.js"; import type { SubscriptionCoreWake } from "./subscription-core/administration.js"; export { EMPTY_SUBSCRIPTION_AUTHORITY_V2, copySubscriptionAuthorityCompatInTransaction, coreSubscriptionAuthorityV2ForAcceptanceInTransaction, coreSubscriptionAuthorityV2ForScheduledTaskInTransaction, subscriptionAuthorityV2OrEmpty, type SubscriptionAuthorityCarrier, } from "./subscription-core-acceptance-authority.js"; export { SessionMessageSearchCursorError } from "./session-message-search.js"; export * from "./artifact-catalog.js"; export * from "./site-data.js"; export * from "./app-activity-events.js"; export * from "./sidebar-layouts.js"; export * from "./site-publishing.js"; export { withSiteRuntimeAdmission } from "./site-runtime-admission.js"; export * from "./site-platform.js"; export * from "./insights-site-usage.js"; export * from "./scheduled-slack-bot-messages.js"; export * from "./organization-signup-use-cases.js"; export * from "./site-sql.js"; export * from "./usage-analytics.js"; export * from "./slack-file-uploads.js"; export { grantWorkspaceAccess, insertWorkspaceMembershipIfAbsent, listWorkspaceMembers, } from "./workspace-membership-access.js"; import { codexSelectionDiagnostics } from "./codex-selection-diagnostics.js"; export { codexSelectionDiagnostics } from "./codex-selection-diagnostics.js"; import { z } from "zod"; import { type ModelConnectionAccess, type ModelConnectionTarget } from "./model-connection-access.js"; export { assertModelConnectionAllowsTurn, modelAllowedByConnections, type ClaudeCoreModelRestrictions, type ConnectionModelRestrictions, } from "./workspace-model-connection-access.js"; import type { ClaudeCoreModelRestrictions } from "./workspace-model-connection-access.js"; export * from "./model-connection-access.js"; export { SubscriptionCoreAccessInvalidError, SubscriptionCoreAccessMoveRequiredError, SubscriptionCoreAccessPeopleUnlistableError, SubscriptionCoreAccessPersonNotInOrganizationError, SubscriptionCoreAccessWorkspaceNotAdministeredError, type SubscriptionCoreAccess, } from "./subscription-core/access.js"; import { type ReportArtifactActor } from "./session-goal-reports.js"; export { recordNativeDocumentInspection } from "./session-goal-reports.js"; import { type SessionGoalReportRequirement, type SessionGoalReportDelivery } from "@opengeni/contracts"; import { type BundledSkillId } from "@opengeni/contracts"; import { type SkillSourceReleaseReceipt } from "./skill-source-release.js"; import type { SkillActor, SkillWriteReceipt } from "@opengeni/contracts"; export * from "./connect-attempts.js"; export * from "./external-identities.js"; export * from "./external-identity-links.js"; export * from "./connection-setup-authority.js"; export * from "./external-link-work.js"; import { SessionNotificationPostedPayload, type ChildLifecycleSystemUpdateKind, type ChildRequiresActionRespondedByKind, SessionGoalSnapshot, ConnectionAccountSelectionDiagnostic } from "@opengeni/contracts"; import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileUploadStatus, FirstPartyMcpToolName, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExportBatch, HostLifecycleFactExportBatch, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, 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, SessionAutomationWaitSummary, SessionAgentAccess, SessionAgentAccessViewer, SessionAuthorizationListScope, SessionScopeSubjectId, SessionMemoryScope, SessionListResponse, SessionListEntryResponse, SessionListLatestTurn, 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, 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, WorkClaimSubjectFilter, WorkDiscoveryProjection } from "@opengeni/contracts"; import { adoptCodemodeApproval } from "./codemode-approvals.js"; import { type InteractionRequestCurrentTarget } from "./browser-auth.js"; import { type WorkspaceArchiveObjectRef, RequestHumanInteractionToolInput, XaiProviderAccountAuthoritySnapshotV1, ClaudeProviderAccountAuthoritySnapshotV1, type TimelineAnnotation } from "@opengeni/contracts"; import { type LatencyMode, SessionSystemUpdatePayload, TurnExecutionPolicyV1 } from "@opengeni/contracts"; import { type SandboxFleetLimits, type SandboxPlanLimit, type SandboxPlanLimits, type Settings } from "@opengeni/config"; import { CodexAppsCredentialUnavailable, type CodexFetch } from "@opengeni/codex"; export { isCodexBilledModel } from "@opengeni/codex"; import { type SQL } from "drizzle-orm"; export { frozenInitiatorForCommandActor, sameTurnSender, type FrozenTurnInitiator, } from "./turn-initiator.js"; export { isStoredVerbatimAsLosslessJsonString, LOSSLESS_TEXT_PREFIX, toPostgresLosslessJson, } from "./lossless-json.js"; import { type NewSessionDraftSnapshot } from "./new-session-drafts.js"; export { DatabaseTransactionError } from "./persistence-errors.js"; import { type SessionDiscoveryControl, type SessionCommandActor, type SessionTurnAttemptOutcome } from "./session-control.js"; import { type ConnectedMachineBackgroundCommandClaim, type ConnectedMachineBackgroundCommandProof, type ConnectedCommandOutputReceipt } from "./session-background-commands.js"; import { type SessionRealtimeContinuityEntry } from "./session-realtime-context.js"; import * as schema from "./schema.js"; import { type CodeSearchDeploymentPolicy } from "@opengeni/contracts/code-search"; import { type MemoryAgentScope, type MemoryScopeSpec } from "./memory-domain.js"; export { sql as dbSql } from "drizzle-orm"; export * from "./child-lifecycle-notices.js"; export * from "./child-terminal-wake-repair.js"; export type { QuiescenceReceiptWakeRepairCursor } from "./quiescence-receipt-wake-repair.js"; export { QUIESCENCE_REPAIR_CLOSE_GRACE_SECONDS, QUIESCENCE_REPAIR_WAKE_QUIET_SECONDS, } from "./quiescence-receipt-wake-repair.js"; import { type QuiescenceReceiptWakeRepairCursor } from "./quiescence-receipt-wake-repair.js"; export * from "./maintenance-work-probes.js"; export { configureCodeSearchDeploymentPolicy } from "./code-search-policy.js"; export * from "./session-control.js"; export { ArchivedSessionImportError, assertSessionIsNotImported, canonicalArchivedSessionImportHash, archivedSessionImportFileIds, getArchivedSessionImportId, type ArchivedSessionImportErrorCode, } from "./archived-session-imports.js"; export declare const { importArchivedSession, appendArchivedSessionEvents }: { importArchivedSession: (db: Database, input: Parameters<(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; fileOwnerSubjectId: string | null; requireLiveSubject?: boolean; apiKeyId?: string; requiredPermission?: Permission; beforeCommit?: (tx: Database) => Promise; } & { payload: import("@opengeni/contracts").ImportArchivedSessionRequest; createdBy: TurnInitiator; createdByContext?: TurnInitiatorContext; }, dependencies: { createSessionWithIdempotencyKeyResult: (db: Database, input: { accountId: string; workspaceId: string; subjectId: string; visibility: "user_private" | "workspace_shared"; createIdempotencyKey: string; initialMessage: string; resources: never[]; skills: never[]; tools: never[]; metadata: Record; createdBy: TurnInitiator; createdByContext?: TurnInitiatorContext; model: string; reasoningEffort: "low"; latencyMode: "standard"; sandboxBackend: "none"; firstPartyMcpTools: never[]; firstPartyMcpPermissions: never[]; archivedImport: true; beforeCreateCommit: (tx: Database, sessionId: string, context?: { created: boolean; }) => Promise; }) => Promise<{ denied: false; created: boolean; session: { id: string; }; } | { denied: true; }>; getFilesForSubject: (db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileIds: readonly string[]; }) => Promise; getSession: (db: Database, workspaceId: string, sessionId: string) => Promise; getWorkspaceGrant: (db: Database, subjectId: string, workspaceId: string) => Promise; isCreateConflict: (error: unknown) => boolean; isCreateUnavailable: (error: unknown) => boolean; }) => Promise<{ session: Session; importId: string; created: boolean; nextOffset: number; events: SessionEvent[]; }>>[1]) => Promise<{ session: Session; importId: string; created: boolean; nextOffset: number; events: SessionEvent[]; }>; appendArchivedSessionEvents: (db: Database, input: Parameters<(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; fileOwnerSubjectId: string | null; requireLiveSubject?: boolean; apiKeyId?: string; requiredPermission?: Permission; beforeCommit?: (tx: Database) => Promise; } & { importId: string; payload: import("@opengeni/contracts").AppendArchivedSessionEventsRequest; sessionId: string; }, dependencies: { createSessionWithIdempotencyKeyResult: (db: Database, input: { accountId: string; workspaceId: string; subjectId: string; visibility: "user_private" | "workspace_shared"; createIdempotencyKey: string; initialMessage: string; resources: never[]; skills: never[]; tools: never[]; metadata: Record; createdBy: TurnInitiator; createdByContext?: TurnInitiatorContext; model: string; reasoningEffort: "low"; latencyMode: "standard"; sandboxBackend: "none"; firstPartyMcpTools: never[]; firstPartyMcpPermissions: never[]; archivedImport: true; beforeCreateCommit: (tx: Database, sessionId: string, context?: { created: boolean; }) => Promise; }) => Promise<{ denied: false; created: boolean; session: { id: string; }; } | { denied: true; }>; getFilesForSubject: (db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileIds: readonly string[]; }) => Promise; getSession: (db: Database, workspaceId: string, sessionId: string) => Promise; getWorkspaceGrant: (db: Database, subjectId: string, workspaceId: string) => Promise; isCreateConflict: (error: unknown) => boolean; isCreateUnavailable: (error: unknown) => boolean; }) => Promise<{ sessionId: string; importId: string; nextOffset: number; replayed: boolean; events: SessionEvent[]; }>>[1]) => Promise<{ sessionId: string; importId: string; nextOffset: number; replayed: boolean; events: SessionEvent[]; }>; }; export * from "./session-model-settings.js"; export * from "./capacity-wait-attention.js"; export * from "./capacity-wait-release.js"; export * from "./session-queue-commands.js"; export { WAITED_FOR_MACHINE_OWNER_MODEL_CONTEXT } from "./machine-owner-wait.js"; export * from "./session-realtime.js"; export * from "./session-realtime-context.js"; export * from "./session-realtime-ledger.js"; export * from "./session-realtime-billing.js"; export * from "./new-session-drafts.js"; export * from "./workspace-instruction-policies.js"; export * from "./company-profile.js"; export * from "./company-profile-agent-policy.js"; export * from "./company-profile-agent-admin.js"; export * from "./workspace-learning-policy.js"; export * from "./usage-allowances.js"; export * from "./governed-learning-evaluator.js"; export * from "./slack-task-policy.js"; export * from "./preference-registry.js"; export * from "./skills.js"; export * from "./organization-shared-workspaces.js"; export * from "./learning-refusals.js"; export * from "./session-tool-results.js"; export type { SkillSourceReleaseReceipt } from "./skill-source-release.js"; export { SkillSourceRemovalAuthorityError } from "./skill-source-release.js"; export * from "./memory-governance.js"; export * from "./memory-slack-delivery.js"; export * from "./scoped-knowledge.js"; export * from "./company-brain.js"; export * from "./company-brain-governed-writes.js"; export * from "./company-brain-context-selection.js"; export * from "./task-notes.js"; export * from "./session-share-links.js"; export * from "./work-claims.js"; export * from "./managed-human-provisioning.js"; export * from "./managed-user-setup.js"; export * from "./signup-network.js"; export * from "./verified-signup-trial-switch.js"; export * from "./managed-auth-new-signups-switch.js"; export * from "./nango-integrations.js"; export * from "./organization-membership-backfill.js"; export * from "./connection-tenancy-backfill.js"; export * from "./generated-images.js"; export * from "./model-call-credit-holds.js"; export * from "./slack-user-link-access.js"; export * from "./slack-routing.js"; export * from "./slack-routing-personal-workspace.js"; export * from "./workspace-membership-permissions.js"; export * from "./video-generation.js"; export * from "./session-title-operations.js"; export * from "./user-resource-authority.js"; export * from "./connection-authority.js"; export { interruptedToolCallResult } from "./session-tool-call-settlement.js"; export { decryptEnvironmentValue, encryptEnvironmentValue } from "./environment-crypto.js"; export { loadIntegrationOAuthPendingState, storeIntegrationOAuthPendingState, consumeIntegrationOAuthPendingState, } from "./integration-oauth-pending-states.js"; export * from "./workspace-integrations.js"; export * from "./native-push.js"; export * from "./agent-calls.js"; export * from "./inbox.js"; export * from "./vaults.js"; export * from "./persistence-errors.js"; export * from "./runtime-posture.js"; export * from "./capability-integrations.js"; export * from "./integration-bindings.js"; export * from "./integration-facets.js"; export * from "./insights.js"; export * from "./insights-model-bundle.js"; export * from "./insights-usage-bundle.js"; export * from "./insights-unified.js"; export * from "./sandbox-viewer-only-drain.js"; export * from "./sandbox-fleet-limits.js"; export * from "./organization-membership-lifecycle.js"; export { rlsSubjectIdOrEmpty, subjectHasLiveWorkspaceAuthorityInScope, } from "./workspace-authority.js"; import { managedPersonalWorkspacePermissions } from "./personal-workspace-permissions.js"; export { PERSONAL_WORKSPACE_EXTERNAL_SOURCE } from "./personal-workspace-membership.js"; export { memoryTextForStorage } from "./memory-domain.js"; export { migrate, runMigrations } from "./migrate.js"; export { provisionRoles, type ProvisionResult, type ProvisionRolesOptions, } from "./provision-roles.js"; export * from "./memory-domain.js"; export * from "./model-catalog.js"; export * from "./billing-subscription-operations.js"; import { type Database, type SessionActivityDatabase } from "./database.js"; 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.js"; export { currentSessionRlsActorIdentityKey, currentSessionRlsActorContext, currentSiteViewerRlsContext, withSiteViewerRlsContext, currentSessionRlsActorInitiatingHumanSubjectId, withSessionRlsActorContext, } from "./database.js"; export { withDatabaseTimingObserver, type DatabaseTimingObservation } from "./database-timing.js"; 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.js"; export type { SessionListChangeSource, SessionListDatabaseChange, SessionListNotification, } from "./session-list-notifications.js"; export { notifyActorDraftChanged } from "./session-list-notifications.js"; export { BROKERED_CREDENTIAL_SHAPE_HINT, brokeredCredentialBundleProblem, normalizedCredentialHeaders, } from "./connection-token-resolver.js"; import { type CodexAuthDeps } from "./codex-token-resolver.js"; import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions } from "./connection-token-resolver.js"; /** Raised when a durable session tool-policy write lost its version fence. */ export declare class SessionToolPolicyVersionConflictError extends Error { readonly currentVersion: number; readonly code = "SESSION_TOOL_POLICY_CONFLICT"; constructor(currentVersion: number); } 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 declare class SessionSpawnDeniedDbError extends Error { readonly denial: SessionSpawnDenial; constructor(denial: SessionSpawnDenial); } 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 declare class HostExportPayloadError extends Error { readonly kind: HostExportKind; readonly consumerId: string; readonly leaseToken: string; readonly cursor: string; readonly schemaIssues: string[]; readonly name = "HostExportPayloadError"; constructor(kind: HostExportKind, consumerId: string, leaseToken: string, cursor: string, schemaIssues: string[]); } 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; }; /** * 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 declare function registerHostExportConsumer(db: Database, input: { kind: HostExportKind; consumerId: string; }): Promise; export declare function disableHostExportConsumer(db: Database, input: { kind: HostExportKind; consumerId: string; }): Promise; /** * Permanently remove a quiesced consumer and release its retention floor. * Unlike disable, re-registering this name later starts at the retained floor. */ export declare function retireHostExportConsumer(db: Database, input: { kind: HostExportKind; consumerId: string; }): Promise; export declare function claimHostExportBatch(db: Database, input: { kind: "session_event"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }): Promise; export declare function claimHostExportBatch(db: Database, input: { kind: "usage_event"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }): Promise; export declare function claimHostExportBatch(db: Database, input: { kind: "lifecycle_fact"; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }): Promise; export declare function claimHostExportBatch(db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; leaseHolderId: string; leaseSeconds?: number; limit?: number; maxBytes?: number; }): Promise; export declare function acknowledgeHostExportBatch(db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; }): Promise; export declare function failHostExportBatch(db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; error: string; maxFailures?: number; }): Promise; export declare function deadLetterHostExportHead(db: Database, input: { kind: HostExportKind; consumerId: string; leaseToken: string; cursor: string; reason: string; }): Promise; export declare function resumeHostExportConsumer(db: Database, input: { kind: HostExportKind; consumerId: string; }): Promise; export declare function rewindHostExportConsumer(db: Database, input: { kind: HostExportKind; consumerId: string; checkpoint: string; }): Promise; export declare function pruneHostExportOutbox(db: Database, input: { kind: HostExportKind; graceSeconds?: number; limit?: number; }): Promise; export declare function getHostExportConsumerStatus(db: Database, input: { kind: HostExportKind; consumerId: string; }): Promise; 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 declare function resolveDocumentIndexAuthority(db: Database, input: { accountId: string; workspaceId: string; documentId: string; }): Promise; /** A Workspace owner's permissions; shared with the API key creator rule. */ export declare const allWorkspacePermissions: Permission[]; 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 declare function resolveNamedManagedPersonalWorkspaceGrant(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; }): Promise; /** * 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 declare function turnCanChangeWorkspaceSettings(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise; /** * 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 declare function turnWorkspaceSettingsAccess(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise<"confirm" | "full_access" | null>; export { allAccountPermissions } from "./organization-role-permissions.js"; export type BootstrapWorkspaceInput = { accountExternalSource: string; accountExternalId: string; accountName: string; workspaceExternalSource: string; workspaceExternalId: string; workspaceName: string; subjectId: string; subjectLabel?: string; accountPermissions?: Permission[]; workspacePermissions?: Permission[]; }; export declare function bootstrapWorkspace(db: Database, input: BootstrapWorkspaceInput): Promise; export declare function ensureManagedAccessForUser(db: Database, input: { userId: string; email: string; name: string; emailVerified?: boolean; provisionFallbackOrganization?: boolean; bindPendingInvitations?: boolean; }): Promise; export type ManagedAccessProvisioningResult = { accessContext: AccessContext; organizationMemberships: ManagedOrganizationMembershipProjection[]; }; export declare function ensureManagedAccessForUserWithOrganizationMemberships(db: Database, input: { userId: string; email: string; name: string; emailVerified?: boolean; provisionFallbackOrganization?: boolean; bindPendingInvitations?: boolean; }): Promise; export declare function getWorkspace(db: Database, workspaceId: string): Promise; /** * 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 declare function getWorkspaceSettings(db: Database, workspaceId: string): Promise | null>; export declare function getManagedAccount(db: Database, accountId: string): Promise; export declare function requireWorkspace(db: Database, workspaceId: string): Promise; export declare function listWorkspacesForSubject(db: Database, subjectId: string, limit?: number): Promise; /** * 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 declare function listSharedWorkspacesForAccount(db: Database, accountId: string): Promise; /** Ids of the organization's shared workspaces, newest first; no projections. */ export declare function listOrganizationWorkspaceIds(db: Database, accountId: string, limit?: number): Promise; export declare function countWorkspacesForAccount(db: Database, accountId: string): Promise; export declare 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; export declare class WorkspaceExternalIdentityConflictError extends Error { constructor(); } export declare function findWorkspaceByExternalIdentity(db: Database, input: { accountId: string; externalSource: string; externalId: string; }): Promise; export declare class WorkspaceLimitExceededError extends Error { readonly limit: number; constructor(limit: number); } /** * 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 declare 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; }>; /** * 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 declare function createOrganizationSharedWorkspace(db: Database, input: { organizationId: string; actorSubjectId: string; name: string; slug?: string | null; agentInstructions?: string | null; operationId: string; }): Promise; export declare class WorkspaceMemberManagementError extends Error { readonly code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN"; constructor(code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN"); } /** * 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 declare function upsertWorkspaceMemberAsWorkspaceManager(db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; targetSubjectId: string; mode: "add" | "update"; subjectLabel?: string; role: string; permissions: Permission[]; }): Promise; /** Prove workspace-scoped management and same-organization active membership. */ export declare function assertWorkspaceMemberManagementCandidate(db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; targetSubjectId: string; }): Promise; /** List active same-organization humans who do not already have workspace access. */ export declare function listWorkspaceMemberManagementCandidates(db: Database, input: { accountId: string; workspaceId: string; actorSubjectId: string; }): Promise; /** * 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 declare function updateOrganizationSharedWorkspace(db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; name?: string; slug?: string | null; agentInstructions?: string | null; }): Promise; /** Same authority as metadata administration, preserving the canonical * workspace-settings merge and inference-control lock path. */ export declare function updateOrganizationSharedWorkspaceSettings(db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; patch: Record; }): Promise; /** Assign or update one active organization member in one shared workspace. */ export declare function upsertOrganizationSharedWorkspaceMember(db: Database, input: { organizationId: string; workspaceId: string; actorSubjectId: string; targetOrganizationMembershipId: string; subjectLabel?: string | null; role?: string; permissions: Permission[]; requireExisting: boolean; }): Promise; export declare function updateWorkspace(db: Database, workspaceId: string, input: { name?: string; slug?: string | null; agentInstructions?: string | null; }): Promise; export declare 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; export declare function setWorkspaceDefaultRig(db: Database, workspaceId: string, rigId: string | null): Promise; export declare function getWorkspaceGrant(db: Database, subjectId: string, workspaceId: string, provenance?: { principalKind?: AccessPrincipalKind; }): Promise; /** * 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 declare function getManagedUserByEmail(db: Database, email: string): Promise; /** * 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 declare function getManagedUserProfilesByIds(db: Database, userIds: readonly string[]): Promise>; /** * 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 declare function getVerifiedSubjectEmail(db: Database, subjectId: string): Promise; /** * 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 declare function workspaceMemberDisplayName(db: Database, input: { workspaceId: string; subjectId: string; }): Promise; export declare function deleteWorkspace(db: Database, workspaceId: string): Promise; 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; }; /** * 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 declare function deleteWorkspaceIfQuiescent(db: Database, input: { accountId: string; workspaceId: string; observer?: WorkspaceDeleteObserver; organizationAdministratorSubjectId?: string; }): Promise; /** Claim a bounded cross-workspace batch after abandoned claims expire. */ export declare function claimTemporalScheduleCleanups(db: Database, input: { claimId: string; limit?: number; claimSeconds?: number; }): Promise; /** * 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 declare function settleTemporalScheduleCleanup(db: Database, input: { id: string; claimId: string; error?: string | null; }): Promise; export declare 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; export declare class OrganizationApiKeyLimitExceededError extends Error { readonly limit: number; constructor(limit: number); } /** * 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 declare 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; export declare function listApiKeys(db: Database, workspaceId: string): Promise; export declare function listOrganizationApiKeys(db: Database, accountId: string): Promise; export declare function getOrganizationApiKey(db: Database, accountId: string, keyId: string): Promise; export declare function updateOrganizationApiKey(db: Database, accountId: string, keyId: string, input: UpdateOrganizationApiKeyRequest): Promise; export declare function countActiveApiKeysForWorkspace(db: Database, workspaceId: string): Promise; export declare function countActiveOrganizationApiKeysForAccount(db: Database, accountId: string): Promise; export declare function revokeApiKey(db: Database, workspaceId: string, apiKeyId: string): Promise; export declare function revokeOrganizationApiKey(db: Database, accountId: string, apiKeyId: string): Promise; export declare 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>; export declare function findActiveWorkspaceApiKeyById(db: Database, input: { accountId: string; workspaceId: string; apiKeyId: string; }): Promise<(ApiKey & { credentialKind: schema.ApiKeyCredentialKind; }) | null>; 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 declare class GitHubInstallationAuthorityCommitError extends Error { constructor(); } /** * 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 declare function hasAuditableGitHubInstallationAuthority(installation: GitHubInstallationAccess): boolean; /** * 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 declare function hasGitHubInstallationOwnerAuthority(installation: GitHubInstallation): boolean; export declare 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; export declare 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; export declare 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; export declare function listGitHubInstallationsForWorkspace(db: Database, workspaceId: string): Promise; export declare function listGitHubInstallationIdsForWorkspace(db: Database, workspaceId: string): Promise; export declare function listGitHubInstallationAccessForWorkspace(db: Database, workspaceId: string): Promise; export declare function areGitHubRepositoriesAllowedForWorkspace(db: Database, workspaceId: string, installationId: number, repositoryIds: number[]): Promise; /** 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 declare function listAllowedGitHubRepositoryIdsForWorkspace(db: Database, workspaceId: string, installationId: number, repositoryIds: number[]): Promise; export declare 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; /** * 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 declare function listGitHubInstallationBindingWorkspaces(db: Database, installationId: number): Promise>; /** * 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 declare const GITHUB_REMOVED_REPOSITORY_HOLD_MS: number; /** * 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 declare function applyGitHubInstallationRepositoryObservation(db: Database, input: { accountId: string; workspaceId: string; installationId: number; observation: GitHubInstallationRepositoryObservation; }): Promise; /** The residency claim a side-feature usage event records (never evidence). */ export type UsageEventProcessingResidency = { geography: string; deploymentType: string; regions: readonly string[]; }; export declare 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; 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; }; /** * Idempotent Insights fact for one authoritative model call. Soft-callers must * never let failures affect billing; this writer itself is safe to retry. */ export declare 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; export { getOrganizationModelUsage, getOrganizationUsageSummary, getOrganizationUsageWorkspacePage, organizationUsageWindow, } from "./organization-usage.js"; export declare function listUsageEvents(db: Database, input: { accountId: string; workspaceId?: string; limit?: number; }): Promise; export declare function sumUsageQuantity(db: Database, input: { accountId?: string; workspaceId?: string; eventType: string; since?: Date; }): Promise; /** {@link attributionBillingOrigin} for a caller outside an account scope. */ export declare function billingOriginForAttribution(db: Database, input: { accountId: string; workspaceId: string; attribution?: CreditDebitAttribution | null | undefined; }): Promise; /** * 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 declare 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; }>; /** * 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 declare 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; }>; export declare function hasCreditLedgerEntry(db: Database, accountId: string, idempotencyKey: string): Promise; export declare function getCreditLedgerEntry(db: Database, accountId: string, idempotencyKey: string): Promise<{ amountMicros: number; sourceType: string | null; metadata: Record; } | null>; export declare function upsertBillingCustomer(db: Database, input: { accountId: string; provider?: string; providerCustomerId: string; email?: string | null; }): Promise; export declare function recordStripeWebhookEvent(db: Database, input: { id: string; type: string; livemode: boolean; payload: unknown; }): Promise; export declare function isStripeWebhookProcessed(db: Database, id: string): Promise; export declare function markStripeWebhookProcessed(db: Database, id: string): Promise; /** * 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 declare function organizationHoldsCredits(db: Database, accountId: string): Promise; export declare function countScheduledTasksForWorkspace(db: Database, workspaceId: string): Promise; 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; 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 declare class ScheduledTaskHeadChangedError extends Error { constructor(); } 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 declare class ConnectionDisconnectIdempotencyError extends Error { readonly code = "IDEMPOTENCY_KEY_REUSED"; constructor(); } export declare class ConnectionDisconnectGenerationError extends Error { readonly code = "CONNECTION_GENERATION_CHANGED"; constructor(); } 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; 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 declare class PersonalGitHubRepositorySelectionChangedError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_CHANGED"; constructor(); } export declare class PersonalGitHubRepositorySelectionIdempotencyError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_IDEMPOTENCY_KEY_REUSED"; constructor(); } export declare class PersonalGitHubRepositorySelectionUnavailableError extends Error { readonly code = "PERSONAL_GITHUB_REPOSITORY_SELECTION_UNAVAILABLE"; constructor(); } 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 declare class PortableSkillInstallationVersionConflictError extends Error { readonly capabilityId: string; readonly expectedVersion: number; readonly actualVersion: number; readonly name = "PortableSkillInstallationVersionConflictError"; constructor(capabilityId: string, expectedVersion: number, actualVersion: number); } export declare class PortableSkillInstallationVersionRequiredError extends Error { readonly name = "PortableSkillInstallationVersionRequiredError"; } export declare class PortableSkillSourcePathConflictError extends Error { readonly name = "PortableSkillSourcePathConflictError"; } /** The Skill's metadata (for example its description) cannot be stored. */ export declare class PortableSkillMetadataError extends Error { readonly name = "PortableSkillMetadataError"; } /** * 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 declare function portableSkillFacetDescription(description: string): string; 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 declare 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; }>; 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 declare function prepareGeneratedWorkspaceFile(db: Database, input: PrepareGeneratedWorkspaceFileInput): Promise<{ file: FileAsset; uploadId: string; created: boolean; }>; export declare function getFile(db: Database, workspaceId: string, fileId: string): Promise; export declare function requireFile(db: Database, workspaceId: string, fileId: string): Promise; export type FileVisibilityChangeResult = { kind: "changed" | "unchanged"; file: FileAsset; } | { kind: "not_found"; } | { kind: "not_owner"; } | { kind: "not_changeable"; }; /** * 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 declare 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; 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 declare 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; /** * 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 declare function isFilePrivateToAnother(db: Database, input: { accountId: string; workspaceId: string; fileId: string; }): Promise; /** * 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 declare function requireFileForSubject(db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileId: string; }): Promise; /** * 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 declare function resolveDocumentOriginalFileForSubject(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; documentId: string; }): Promise; /** 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 declare 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; }>; export declare function getFilesForSubject(db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; fileIds: readonly string[]; }): Promise; /** One RLS-scoped query for all attachment metadata needed by a model turn. */ export declare function getFiles(db: Database, workspaceId: string, fileIds: readonly string[]): Promise; /** Build the canonical user row with stable attachment refs, never inline bytes. */ export declare 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; 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 declare function getRetainedFileArtifact(db: Database, workspaceId: string, fileId: string): Promise; 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 declare class RetainedScreenshotQuotaExceededError extends Error { readonly quotaBytes: number; readonly usedBytes: number; readonly requestedBytes: number; readonly code = "retained_screenshot_workspace_quota_exceeded"; constructor(quotaBytes: number, usedBytes: number, requestedBytes: number); } 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; }; /** * 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 declare function prepareRetainedScreenshotArtifact(db: Database, input: PrepareRetainedScreenshotArtifactInput): Promise<{ artifact: RetainedScreenshotArtifact; created: boolean; }>; /** Settle one exact pending/reconciling artifact ready and move its quota once. */ export declare function settleRetainedScreenshotArtifactReady(db: Database, input: { accountId: string; workspaceId: string; artifactId: string; settlementKey: string; maintenanceClaimId?: string; }): Promise; /** Record a bounded diagnostic while preserving retryable pending truth. */ export declare function recordRetainedScreenshotArtifactError(db: Database, input: { accountId: string; workspaceId: string; artifactId: string; settlementKey: string; error: string; }): Promise; /** Session-qualified lookup: a screenshot from another session is indistinguishable from absent. */ export declare function getRetainedScreenshotArtifact(db: Database, workspaceId: string, sessionId: string, artifactId: string): Promise; /** * 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 declare function getSessionRetainedScreenshotArtifacts(db: Database, workspaceId: string, sessionId: string, artifactIds: readonly string[]): Promise>; /** 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 declare function getRetainedScreenshotArtifactForToolCall(db: Database, workspaceId: string, sessionId: string, toolCallId: string): Promise; /** 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 declare function getWithheldRetainedScreenshotArtifactIdForToolCall(db: Database, workspaceId: string, sessionId: string, toolCallId: string): Promise; 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 declare function claimRetainedScreenshotMaintenance(db: Database, input: { pendingGraceMs: number; claimTimeoutMs: number; limit: number; }): Promise; /** * 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 declare function promoteRetainedScreenshotMaintenanceCleanup(db: Database, input: { accountId: string; workspaceId: string; artifactId: string; claimId: string; cleanupReason: string; }): Promise; /** * Complete a claimed reconcile/delete operation and release exactly one quota * bucket. A lost response is idempotent on the requested terminal state. */ export declare function completeRetainedScreenshotMaintenance(db: Database, input: Parameters[1]): Promise; declare function completeRetainedScreenshotMaintenanceInOwnerScope(db: Database, input: { accountId: string; workspaceId: string; artifactId: string; claimId: string; outcome: "ready" | "failed" | "expired" | "deleted"; }): Promise; export declare function getWorkspaceScreenshotQuota(db: Database, workspaceId: string): Promise<{ reservedBytes: number; readyBytes: number; } | null>; export declare function getFileUpload(db: Database, workspaceId: string, uploadId: string): Promise<{ id: string; status: FileUploadStatus; expiresAt: Date; file: FileAsset; } | null>; export declare 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; export declare function markFileUploadFailed(db: Database, workspaceId: string, uploadId: string, fileId: string, uploadStatus?: "failed" | "expired"): Promise; 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 declare function claimFileUploadCleanup(db: Database, input: { workspaceId: string; uploadId: string; fileId: string; }): Promise; 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 declare function claimExpiredFileUploadCleanup(db: Database, input: { graceMs: number; claimTimeoutMs: number; limit: number; }): Promise; /** Settle one successfully deleted cleanup claim. Idempotent on its terminal state. */ export declare function completeFileUploadCleanup(db: Database, input: { accountId: string; workspaceId: string; uploadId: string; fileId: string; terminalStatus: "failed" | "expired"; }): Promise; /** Settle one successfully deleted global expiry-reaper claim. */ export declare function completeExpiredFileUploadCleanup(db: Database, input: { accountId: string; workspaceId: string; uploadId: string; fileId: string; }): Promise; export declare function createImportBatch(db: Database, input: CreateImportBatchInput): Promise; export declare function findCompletedImportBatch(db: Database, input: { source: string; snapshotRef: string; importedCount: number; }): Promise; export declare function updateImportBatchCounts(db: Database, id: string, input: UpdateImportBatchCountsInput): Promise; export declare function upsertRegistryCapabilityCatalogItem(db: Database, input: RegistryCapabilityCatalogItemInput): Promise; export declare function listRegistryCatalogSurfaceKeys(db: Database): Promise; export declare function markStaleRegistryCatalogItems(db: Database, activeKeys: Iterable<{ providerDomain: string; mcpUrl: string; }>, importBatchId: string): Promise; export declare function upsertCapabilityCatalogItem(db: Database, input: CreateCapabilityCatalogItemInput): Promise; /** * 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 declare function setWorkspaceCapabilityCatalogItemLogo(db: Database, input: { accountId: string; workspaceId: string; id: string; logoAssetPath: string; }): Promise; export declare function listCapabilityCatalogItems(db: Database, workspaceId: string): Promise; /** * 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 declare function getGlobalCatalogOAuthProfile(db: Database, workspaceId: string, mcpUrl: string): Promise; export declare function getCapabilityCatalogItem(db: Database, workspaceId: string, capabilityId: string): Promise; /** Replay before remote resolution; callers must provide the same canonical original request used at install. */ export declare function replayPortableSkillInstall(db: Database, input: { accountId: string; workspaceId: string; actor: SkillActor; operationId: string; requestIdentity: Record; }): Promise; /** * 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 declare function installPortableSkill(db: Database, input: InstallPortableSkillInput): Promise; /** * 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 declare function listInstalledPortableSkills(db: Database, workspaceId: string, options?: { includeSessionSelected?: boolean; }): Promise; /** Return secret-free lifecycle summaries from the authoritative Skill ledger. */ export declare function listInstalledSkills(db: Database, workspaceId: string): Promise; export declare function getPortableSkillUninstallPreview(db: Database, workspaceId: string, capabilityId: string): Promise; export declare function uninstallPortableSkill(db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; expectedInstallationVersion: number; skillActor?: SkillActor; }): Promise; export declare function enableCapabilityInstallation(db: Database, input: EnableCapabilityInstallationInput): Promise; /** Who turned each MCP server on in a workspace, and whether it is on now. */ export declare function listCapabilityInstallationInstallers(db: Database, workspaceId: string): Promise>; /** * 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 declare function removeCapabilityInstallation(db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; subjectId: string; memberRemoval?: boolean; }): Promise; /** * 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 declare function deleteWorkspaceCatalogItem(db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; }): Promise; export declare function disableCapabilityInstallation(db: Database, workspaceId: string, capabilityId: string): Promise; /** Marks the turned-off installation that switches an organization connector off in one workspace. */ export declare const ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY = "organizationOverride"; export declare function isOrganizationConnectorOverride(installation: Pick): boolean; /** * 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 declare function turnOffOrganizationConnectorInWorkspace(db: Database, input: { accountId: string; workspaceId: string; capabilityId: string; }): Promise; /** * Removes this workspace's turned-off override, so the organization's * connector applies again. Any other installation is left alone (false). */ export declare function restoreOrganizationConnectorInWorkspace(db: Database, workspaceId: string, capabilityId: string): Promise; /** * An organization connector reaching this workspace, shaped as the * installation a workspace setup of it would be (header names only). */ export declare function organizationConnectorAsInstallation(connector: OrganizationConnectorRow, workspaceId: string): CapabilityInstallation; export declare function listCapabilityInstallations(db: Database, workspaceId: string): Promise; export declare function getCapabilityInstallation(db: Database, workspaceId: string, capabilityId: string): Promise; export declare 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; /** * 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 declare function listOriginMcpCapabilityServersForPersonalExtension(db: Database, originWorkspaceId: string): Promise; /** * 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 declare function organizationConnectorCatalogItem(connector: Pick, workspaceId: string | null): CapabilityCatalogItem; /** * Curated and registry catalog connectors (no workspace) trusted for * exposure, by id: the catalog an organization can add connectors from. */ export declare function listTrustedGlobalMcpCatalogItems(db: Database, accountId: string, ids: readonly string[]): Promise; /** * 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 declare function listEnabledMcpCapabilityServerIds(db: Database, workspaceId: string): Promise; /** * 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 declare function decryptedCapabilityHeaders(server: EnabledMcpCapabilityServer, encryptionKey: Uint8Array | null): Record | null | "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 declare function getStoredCapabilityHeaderCiphertext(db: Database, workspaceId: string, capabilityId: string): Promise | null>; export declare function mcpServerIdForCapability(capabilityId: string, metadata?: Record): string; export declare class ConnectionCreateIdempotencyError extends Error { constructor(); } export declare function getConnectionCreationResult(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; operationId: string; }): Promise; export declare 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; }): Promise; /** * 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 declare function connectionAccountIdentityKey(parts: readonly string[]): string; /** Another live connection of the same owner already holds this account. */ export declare class ConnectionAccountAlreadyConnectedError extends Error { constructor(); } /** Whether an error is the live-account uniqueness check (migration 1481). */ export declare function isConnectionAccountIdentityConflict(error: unknown): boolean; export declare function createConnection(db: Database, input: CreateConnectionInput): Promise; export type WorkspaceProviderApiKeyConnectionKind = "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "elevenlabs"; type WorkspaceProviderApiKeyConnectionSpec = { providerDomain: string; credentialRole: string; operationIdMetadataKey: string; operationDigestMetadataKey: string; label: string; }; export declare function workspaceProviderApiKeyConnectionSpec(providerKind: WorkspaceProviderApiKeyConnectionKind): WorkspaceProviderApiKeyConnectionSpec; export declare function upsertWorkspaceProviderApiKeyConnection(db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: UpsertWorkspaceProviderApiKeyConnectionInput): Promise; export declare function rotateWorkspaceProviderApiKeyConnection(db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: RotateWorkspaceProviderApiKeyConnectionInput): Promise; export declare function revokeWorkspaceProviderApiKeyConnections(db: Database, providerKind: WorkspaceProviderApiKeyConnectionKind, input: RevokeWorkspaceProviderApiKeyConnectionsInput): Promise; /** Compatibility wrapper for the existing Vercel AI Gateway create/replay contract. */ export declare function upsertWorkspaceVercelAiGatewayConnection(db: Database, input: UpsertWorkspaceVercelAiGatewayConnectionInput): Promise; export declare function upsertWorkspaceOpenRouterConnection(db: Database, input: UpsertWorkspaceOpenRouterConnectionInput): Promise; /** Compatibility wrapper for the existing Vercel AI Gateway rotation contract. */ export declare function rotateWorkspaceVercelAiGatewayConnection(db: Database, input: RotateWorkspaceVercelAiGatewayConnectionInput): Promise; export declare function rotateWorkspaceOpenRouterConnection(db: Database, input: RotateWorkspaceOpenRouterConnectionInput): Promise; /** Compatibility wrapper for the existing Vercel AI Gateway revoke contract. */ export declare function revokeWorkspaceVercelAiGatewayConnections(db: Database, input: RevokeWorkspaceVercelAiGatewayConnectionsInput): Promise; export declare function revokeWorkspaceOpenRouterConnections(db: Database, input: RevokeWorkspaceOpenRouterConnectionsInput): Promise; /** * 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 declare function persistProviderOAuthConnection(db: Database, input: PersistProviderOAuthConnectionInput): Promise; export declare function getPersonalGitHubRepositorySelectionState(db: Database, input: { accountId: string; originWorkspaceId: string; subjectId: string; connectionId: string; }): Promise; export declare function replacePersonalGitHubRepositorySelections(db: Database, input: PersonalGitHubRepositorySelectionMutationInput): Promise; export declare function verifyPersonalGitHubRepositorySelections(db: Database, input: PersonalGitHubRepositorySelectionMutationInput): Promise; export declare function updateConnection(db: Database, input: UpdateConnectionInput): Promise; /** * 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 declare function updateSlackBotDocumentDestination(db: Database, input: UpdateSlackBotDocumentDestinationInput): Promise; /** * 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 declare function transitionConnectionState(db: Database, input: TransitionConnectionStateInput): Promise; /** * 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 declare function disconnectConnectionIdempotently(db: Database, input: DisconnectConnectionIdempotentlyInput): Promise; export declare 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; export type SlackInstallationRoute = { accountId: string; workspaceId: string; connectionId: string; botId: string; botUserId: string; }; export declare class SlackInstallationBindingConflictError extends Error { readonly reason: "conflicting_workspace" | "conflicting_principal" | "legacy_quarantine" | "stale_reinstall"; constructor(reason: "conflicting_workspace" | "conflicting_principal" | "legacy_quarantine" | "stale_reinstall"); } export declare function listSlackInstallationBindings(db: Database, input: { accountId: string; workspaceId: string; }): Promise; 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 declare function resolveSlackInstallationRoute(db: Database, slackTeamId: string): Promise; export declare function saveSlackBotUserLink(db: Database, input: Omit): Promise; export declare function getSlackBotUserLink(db: Database, workspaceId: string, connectionId: string, slackUserId: string): Promise; /** * 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 declare 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; export declare function deleteSlackBotUserLink(db: Database, workspaceId: string, connectionId: string, slackUserId: string): Promise; export declare function enqueueSlackAppHomeRefresh(db: Database, input: Pick): Promise; export declare function claimSlackAppHomeRefresh(db: Database, claimHolderId: string, claimLeaseMs: number): Promise; export declare function renewSlackAppHomeRefreshClaim(db: Database, input: { refresh: Pick; claimHolderId: string; claimLeaseMs: number; }): Promise; export declare function settleSlackAppHomeRefresh(db: Database, input: { refresh: Pick; claimHolderId: string; errorCode?: string | null; }): Promise; export declare function releaseSlackAppHomeRefresh(db: Database, input: { refresh: Pick; claimHolderId: string; errorCode: string; retryAt: Date; }): Promise; export declare function enqueueSlackInteractionInbox(db: Database, input: Omit): Promise<{ inserted: boolean; entry: SlackInteractionInboxEntry; }>; export declare function claimSlackInteractionInbox(db: Database, claimHolderId: string, claimLeaseMs: number): Promise; export declare function settleSlackInteractionInbox(db: Database, input: { entry: Pick; claimHolderId: string; outcome: "processed" | "failed"; errorCode?: string | null; }): Promise; export declare function saveSlackInteractionInboxReactionCheckpoint(db: Database, input: { entry: Pick; claimHolderId: string; checkpoint: unknown; }): Promise; export declare function releaseSlackInteractionInbox(db: Database, input: { entry: Pick; claimHolderId: string; errorCode: string; retryAt: Date; }): Promise; export declare function getOrCreateSlackInteraction(db: Database, input: Omit & { initiatingSlackUserId?: string | null; routedWorkspaceLabel?: string | null; slackAgentId?: string | null; handoffFromSlackAgentId?: string | null; }): Promise<{ created: boolean; interaction: SlackInteraction; }>; /** * 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 declare function getSlackInteractionByConnectionRoute(db: Database, input: { accountId: string; connectionId: string; routeKey: string; }): Promise; /** * 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 declare function getSlackInteractionByRoute(db: Database, workspaceId: string, connectionId: string, routeKey: string): Promise; export declare function getSlackInteractionById(db: Database, input: { accountId: string; workspaceId: string; interactionId: string; }): Promise; export declare function reserveSlackInteractionActionHandles(db: Database, input: { interaction: Pick; sessionEventSequence: number; messageOperationId: string; expiresAt: Date; actions: Array<{ actionKind: SlackInteractionActionKind; actionKey: string; targetId?: string | null; targetValue?: string | null; }>; }): Promise; export declare function getSlackInteractionActionHandle(db: Database, input: { accountId: string; workspaceId: string; handleId: string; }): Promise; /** * 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 declare function listPendingSlackInteractionMessageActionHandles(db: Database, input: { accountId: string; workspaceId: string; interactionId: string; messageOperationId: string; }): Promise; export declare 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; /** * 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 declare function getSlackInteractionByClientEventId(db: Database, workspaceId: string, connectionId: string, clientEventId: string): Promise<{ interaction: SlackInteraction; eventSessionId: string; } | null>; /** Exact bound session only: a child never inherits its root's Slack destination. */ export declare function getSlackInteractionForSession(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; }): Promise; export declare function getSlackInteractionSessionAccess(db: Database, workspaceId: string, rootSessionId: string): Promise | 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 declare function getSlackPrivateSessionOwnerSubjectId(db: Database, workspaceId: string, sessionId: string): Promise; export declare 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; 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 declare function listSlackInteractionProgressDeliveryEvidence(db: Database, input: { accountId: string; workspaceId: string; interactionId: string; sessionId: string; }): Promise; /** * 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 declare function claimSlackInteractionProgressDelivery(db: Database, input: { accountId: string; workspaceId: string; interactionId: string; claimHolderId: string; sessionEventSequence: number; maxProgress: number; }): Promise; export declare function rekeySlackInteractionRoute(db: Database, input: Pick & { routeKey: string; slackChannelId?: string; slackThreadTs: string; ackSlackMessageTs: string; repairUnacknowledgedPrivateShortcutDelivery?: boolean; }): Promise; /** * 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 declare 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"): Promise; /** Remember the latest Slack message a chat was given and who sent it. */ export declare function recordSlackInteractionInbound(db: Database, input: Pick & { providerEventId: string; slackUserId: string; }): Promise; /** * 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 declare function getSlackProviderEventIdForTurn(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; }): Promise<{ turnFound: boolean; providerEventId: string | null; }>; /** The inbox row of one Slack event, read under the installation's HOME tenancy. */ export declare function getSlackInteractionInboxByProviderEvent(db: Database, home: { accountId: string; workspaceId: string; }, input: { connectionId: string; providerEventId: string; }): Promise; export declare function claimSlackInteractionDelivery(db: Database, claimHolderId: string, claimLeaseMs: number): Promise; export declare function reopenSlackInteractionDelivery(db: Database, input: Pick): Promise; /** * 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 declare function reopenSlackInteractionDeliveryAfter(db: Database, input: Pick & { afterSequence: number; }): Promise<"reopened" | "marked" | null>; export declare function advanceSlackInteractionDelivery(db: Database, input: Pick & { claimHolderId: string; sequence: number; ackSlackMessageTs?: string | null; }): Promise; export declare function releaseSlackInteractionDelivery(db: Database, input: Pick & { claimHolderId: string; }): Promise; export declare function deferSlackInteractionDelivery(db: Database, input: Pick & { claimHolderId: string; retryAt: Date; errorCode: string; }): Promise; export declare 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; export type SlackThreadContextMessage = { slackUserId: string; slackMessageTs: string; text: string; hasFiles: boolean; }; /** Numeric order of two Slack message timestamps (`seconds.micros`). */ export declare function compareSlackMessageTs(left: string, right: string): number; /** * 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 declare 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; }>; export declare class SlackBotLifecycleSuccessAuditError extends Error { constructor(); } 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; }; }; export declare function persistSlackBotInstallationWithSuccessAudit(db: Database, input: PersistSlackBotInstallationInput): Promise; export declare function createConnectionWithSlackBotSuccessAudit(db: Database, input: SlackBotLifecycleSuccessAuditInput & { connection: CreateConnectionInput; }): Promise; export declare function updateConnectionWithSlackBotSuccessAudit(db: Database, input: SlackBotLifecycleSuccessAuditInput & { connection: UpdateConnectionInput; }): Promise; export declare function revokeConnectionWithSlackBotSuccessAudit(db: Database, input: SlackBotLifecycleSuccessAuditInput & { connectionId: string; expectedVersion: number; /** Also record the generic `connection.disconnected` row as this actor. */ audit?: DisconnectAuditActor | null; }): Promise; 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 declare function recordSlackBotInstallCallbackFailure(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; callbackDigest: string; installMode: "connect" | "reinstall"; stage: SlackBotInstallCallbackFailureStage; reason: SlackBotInstallCallbackFailureReason; }): Promise; 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 declare 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; export declare function markSlackBotPostOperationProviderStarted(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; }): Promise; export declare function releaseSlackBotPostOperationClaim(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; outcomeUnknown: boolean; failureCode: string; }): Promise; export type CompleteSlackBotPostOperationResult = { kind: "completed"; operation: SlackBotPostOperation; newlyCompleted: boolean; } | { kind: "not_found" | "not_owned"; }; /** Completion and the single success audit receipt commit atomically. */ export declare 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; export declare function getSlackBotPostOperation(db: Database, workspaceId: string, connectionId: string, operationId: string): Promise; export type ClaimSlackBotUpdateOperationResult = { kind: "claimed" | "in_progress" | "completed"; operation: SlackBotUpdateOperation; } | { kind: "conflict" | "connection_not_found"; }; export declare function claimSlackBotUpdateOperation(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; slackChannelId: string; slackMessageTimestamp: string; requestDigest: string; claimHolderId: string; claimLeaseMs: number; }): Promise; export declare function releaseSlackBotUpdateOperationClaim(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; failureCode: string; }): Promise; export declare 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">; export type ClaimSlackBotDeleteOperationResult = { kind: "claimed" | "reconcile" | "in_progress" | "completed"; operation: SlackBotDeleteOperation; } | { kind: "conflict" | "connection_not_found"; }; export declare 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; export declare function markSlackBotDeleteOperationProviderStarted(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; }): Promise; export declare function releaseSlackBotDeleteOperationClaim(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; operationId: string; claimHolderId: string; outcomeUnknown: boolean; failureCode: string; }): Promise; export type CompleteSlackBotDeleteOperationResult = { kind: "completed"; operation: SlackBotDeleteOperation; newlyCompleted: boolean; } | { kind: "not_found" | "not_owned"; }; export declare 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; export declare function getSlackBotDeleteOperation(db: Database, workspaceId: string, connectionId: string, operationId: string): Promise; export declare function loadConnectionCredentialForBroker(db: Database, settings: Settings, input: { workspaceId: string; connectionId?: string; providerDomain: string; kind?: ConnectionKind; subjectId?: string | null; allowSubjectOwned?: boolean; expectedAuthorityGeneration?: number; }): Promise; export declare function getWorkspaceProviderApiKeyConnectionMetadata(db: Database, workspaceId: string, providerKind: WorkspaceProviderApiKeyConnectionKind): Promise<{ connectionId: string; version: number; } | null>; /** Select readiness from an already authorized, newest-first metadata read. */ export declare function workspaceProviderApiKeyConnectionMetadataFromConnections(connections: readonly ConnectionMetadata[], providerKind: WorkspaceProviderApiKeyConnectionKind): { connectionId: string; version: number; } | null; /** Metadata-only capability revision input; never selects/decrypts the API key. */ export declare function getWorkspaceVercelAiGatewayConnectionMetadata(db: Database, workspaceId: string): Promise<{ connectionId: string; version: number; } | null>; export declare function getWorkspaceOpenRouterConnectionMetadata(db: Database, workspaceId: string): Promise<{ connectionId: string; version: number; } | null>; export declare function getWorkspaceOpperConnectionMetadata(db: Database, workspaceId: string): Promise<{ connectionId: string; version: number; } | null>; export declare function workspaceOpperConnectionActive(db: Database, workspaceId: string): Promise; export declare function workspaceVercelAiGatewayConnectionActive(db: Database, workspaceId: string): Promise; export declare function workspaceOpenRouterConnectionActive(db: Database, workspaceId: string): Promise; export declare function loadWorkspaceProviderApiKey(db: Database, settings: Settings, workspaceId: string, providerKind: WorkspaceProviderApiKeyConnectionKind, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[]): Promise; /** Resolve only the reviewed workspace-shared AI Gateway credential shape. */ export declare function loadWorkspaceVercelAiGatewayApiKey(db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[]): Promise; /** Resolve only the reviewed workspace-shared OpenRouter credential shape. */ export declare function loadWorkspaceOpenRouterApiKey(db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[]): Promise; /** Resolve only the reviewed workspace-shared Opper credential shape. */ export declare function loadWorkspaceOpperApiKey(db: Database, settings: Settings, workspaceId: string, turnModelId?: string | null, connectionMetadata?: readonly ConnectionMetadataWithVerification[]): Promise; /** * 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 declare function loadWorkspaceVercelAiGatewayCredentialLease(db: Database, settings: Settings, workspaceId: string): Promise<{ connectionId: string; version: number; credentialEncrypted: string; apiKey: string; } | null>; export declare 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; export declare function setConnectionStatus(db: Database, workspaceId: string, status: ConnectionStatus, lastError: string | null, guard: { id: string; version: number; subjectId?: string | null; }): Promise; export declare function recordConnectionUsed(db: Database, workspaceId: string, connectionId: string, subjectId?: string | null): Promise; export declare function loadIntegrationOAuthClient(db: Database, settings: Settings, issuer: string): Promise; export declare function storeIntegrationOAuthClient(db: Database, input: StoreIntegrationOAuthClientInput): Promise; export declare function replaceIntegrationOAuthClient(db: Database, input: ReplaceIntegrationOAuthClientInput): Promise; export declare function replaceIntegrationOAuthClientIfCurrent(db: Database, input: ReplaceIntegrationOAuthClientIfCurrentInput): Promise; export declare function consumeIntegrationOAuthStateNonce(db: Database, input: ConsumeOAuthStateNonceInput): Promise; export declare function createKnowledgeMemory(db: Database, input: CreateKnowledgeMemoryInput): Promise; export declare function updateKnowledgeMemory(db: Database, workspaceId: string, memoryId: string, input: UpdateKnowledgeMemoryInput, embedder?: MemoryEmbedder): Promise; export declare function getKnowledgeMemory(db: Database, workspaceId: string, memoryId: string): Promise; export declare function listKnowledgeMemories(db: Database, workspaceId: string, options?: ListKnowledgeMemoryOptions): Promise; 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; pinned?: boolean | undefined; replacesId?: string | null | undefined; sessionId?: string | null | undefined; 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; deduped: boolean; dedupeReason: "exact" | "near" | null; superseded: KnowledgeMemory | null; supersededId: string | null; updated: boolean; embedded: boolean; }; export type CorrectWorkspaceMemoryInput = { accountId: string; workspaceId: string; id: string; 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"; memory: KnowledgeMemory; 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; }; export declare function saveWorkspaceMemory(db: Database, input: SaveWorkspaceMemoryInput, embedder?: MemoryEmbedder): Promise; export declare function correctWorkspaceMemory(db: Database, input: CorrectWorkspaceMemoryInput, embedder?: MemoryEmbedder): Promise; export declare function searchWorkspaceMemories(db: Database, workspaceId: string, input: WorkspaceMemorySearchInput, embedder?: MemoryEmbedder): Promise; export declare function resolveWorkspaceMemoryBlock(db: Database, workspaceId: string): Promise; export declare function createSocialConnection(db: Database, input: CreateSocialConnectionInput): Promise; /** * 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 declare function upsertSocialOAuthConnection(db: Database, input: UpsertSocialOAuthConnectionInput): Promise; /** * 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 declare function loadSocialConnectionCredential(db: Database, workspaceId: string, connectionId: string, subjectId?: string | null): Promise<{ connection: SocialConnection; credentialEncrypted: string | null; } | null>; export declare function updateSocialConnectionCredential(db: Database, input: UpdateSocialConnectionCredentialInput): Promise; export declare function listSocialConnections(db: Database, workspaceId: string, limit?: number, subjectId?: string | null): Promise; export declare function getSocialConnection(db: Database, workspaceId: string, connectionId: string, subjectId?: string | null): Promise; export declare function requireSocialConnection(db: Database, workspaceId: string, connectionId: string, subjectId?: string | null): Promise; export declare function createSocialPost(db: Database, input: CreateSocialPostInput): Promise; /** * 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 declare 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; }>; export declare function listSocialPosts(db: Database, options: { workspaceId: string; subjectId?: string | null; connectionIds?: string[]; since?: Date; limit?: number; }): Promise; export declare function createScheduledTask(db: Database, input: CreateScheduledTaskInput): Promise; /** * 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 declare function scheduledTaskMutationOwnerMatches(db: Database, input: { workspaceId: string; taskId: string; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; }): Promise; /** * 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 declare function scheduledTaskViewerSubject(db: Database, input: { workspaceId: string; createdBy?: TurnInitiator; createdByContext?: TurnInitiatorContext; createdByActor?: AgentSessionCreationActor | null; }): Promise; /** * 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 declare function meetingSummarySessionScope(db: Database, input: { workspaceId: string; sessionId: string; createdByActor?: AgentSessionCreationActor | null; }): Promise<{ recordingId: string; ownerSubjectId: string | null; } | 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 declare 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; /** * 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 declare function pausePrivateScheduledTask(db: Database, input: { workspaceId: string; taskId: string; excludeOwnerSubjectId: string | null; }): Promise; /** The stored audience of a chat this request can already see, or null. */ export declare function getVisibleSessionTenancyVisibility(db: Database, workspaceId: string, sessionId: string): Promise<"user_private" | "workspace_shared" | null>; /** * A chat's audience and, for an Only me chat, its owner; null when the * caller cannot see the chat. */ export declare function getVisibleSessionAudience(db: Database, workspaceId: string, sessionId: string): Promise<{ visibility: "user_private" | "workspace_shared"; ownerSubjectId: string | null; } | null>; export declare function updateScheduledTask(db: Database, workspaceId: string, taskId: string, input: UpdateScheduledTaskInput): Promise; export declare function getScheduledTask(db: Database, workspaceId: string, taskId: string): Promise; /** Internal delete-recovery lookup; public list/get surfaces hide tombstones. */ export declare function getScheduledTaskIncludingDeleted(db: Database, workspaceId: string, taskId: string): Promise<(ScheduledTask & { deletedAt: string | null; }) | null>; /** Task-first deletion lock; call only inside the surrounding lifecycle transaction. */ export declare function getScheduledTaskIncludingDeletedForUpdate(db: Database, workspaceId: string, taskId: string): Promise<(ScheduledTask & { deletedAt: string | null; }) | null>; /** * Lock the incident task definition inside the dispatch transaction. Account * authority belongs to the accepted occurrence, never the mutable task head. */ export declare function requireScheduledTaskIncidentAuthorityInTransaction(tx: Database, input: { workspaceId: string; taskId: string; }): Promise; export declare function getScheduledTaskXaiProviderAccountAuthoritySnapshot(db: Database, workspaceId: string, taskId: string): Promise; /** * 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 declare function getScheduledTaskCreatorPolicy(db: Database, workspaceId: string, taskId: string): Promise; /** Batch form of {@link getScheduledTaskCreatorPolicy}; tasks without a row are absent. */ export declare function listScheduledTaskCreatorPolicies(db: Database, workspaceId: string, taskIds: readonly string[]): Promise>; export declare function requireScheduledTask(db: Database, workspaceId: string, taskId: string): Promise; export declare class ScheduledTaskTargetConflictError extends Error { constructor(); } /** * 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 declare function requireScheduledTaskTargetInTransaction(tx: Database, input: { workspaceId: string; taskId: string; targetSessionId: string; }): Promise; /** Authoritative current targets, batched after session visibility has been resolved. */ export declare function scheduledSessionIds(db: Database, workspaceId: string, sessionIds: string[]): Promise>; /** * 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 declare function scheduledTaskHasUpcomingRun(task: { status: string; schedule: unknown; }, now: Date): boolean; 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; }; /** * 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 declare function scheduledTaskNextRunAt(schedule: unknown, now: Date): Date | null; export declare 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; export declare function listScheduledTasks(db: Database, workspaceId: string, limit?: number, offset?: number, 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; /** * 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 declare function listActiveScheduledTasksWithPinnedAccounts(db: Database, workspaceId: string, input: { subjectId: string; includeOwnerless: boolean; limit: number; }): Promise; export declare function deleteScheduledTask(db: Database, workspaceId: string, taskId: string): Promise<{ cleanup: TemporalScheduleCleanupClaim | null; changed: boolean; }>; /** * 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 declare function retireArchivedChatWaits(db: Database, input: { workspaceId: string; rootSessionId: string; }): Promise; /** A terminal refusal is evidence, not accepted execution or permission to retry. */ export declare function recordScheduledTaskAdmissionFailure(db: Database, input: { workspaceId: string; taskId: string; taskAuthorityRevision: number; taskExecutionDigest: string; triggerType: ScheduledTaskTriggerType; producerKey: string; scheduledAt?: Date | null; diagnostic: ConnectionAccountSelectionDiagnostic; }): Promise; /** 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 declare 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; export declare 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; export declare function getScheduledTaskRunAcceptedExecution(db: Database, input: { workspaceId: string; runId: string; }): Promise; export declare function getScheduledTaskRunByProducerKey(db: Database, input: { workspaceId: string; taskId: string; triggerType: ScheduledTaskTriggerType; producerKey: string; }): Promise; 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 declare function getScheduledTaskRunPersonalResourceAuthority(db: Database, input: { accountId: string; workspaceId: string; runId: string; }): Promise; export declare function materializeScheduledTaskReusableSessionFromRun(db: Database, input: { accountId: string; workspaceId: string; taskId: string; runId: string; sessionId: string; sourceTaskAuthorityRevision: number; sourceExecutionDigest: string; }): Promise; export declare function bindScheduledTaskRunSessionInTransaction(tx: Database, input: { accountId: string; workspaceId: string; runId: string; sessionId: string; }): Promise; export declare function getScheduledTaskPersonalResourceAuthoritySubject(db: Database, input: { accountId: string; workspaceId: string; taskId: string; taskAuthorityRevision: number; }): Promise; export declare function getScheduledTaskRevisionAuthoritySubject(db: Database, input: { accountId: string; workspaceId: string; taskId: string; taskAuthorityRevision: number; }): Promise; export { getScheduledTaskRevisionAuthority } from "./scheduled-task-revision-authority.js"; /** Failure settlement must not rewrite a source already committed as dispatched. */ export declare function markScheduledTaskRunFailedIfQueued(db: Database, workspaceId: string, runId: string, error: string): Promise; 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 declare function failScheduledGeneratedSessionRoute(db: Database, input: { accountId: string; workspaceId: string; taskId: string; runId: string; sessionId: string; error: string; }): Promise; export declare 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; /** * 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 declare function isWorkspaceAgentActivityPaused(db: Database, workspaceId: string): Promise; /** * 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 declare function scheduledTaskPreviousRunSessionBusy(db: Database, input: { workspaceId: string; taskId: string; runId: string; }): Promise; /** Claim-time stale-authority settlement; no model/tool/sandbox work has started. */ export declare function markScheduledTaskRunAuthorityRejectedInTransaction(tx: Database, input: { workspaceId: string; sessionId: string; runId: string; error?: string; }): Promise; export declare 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; /** DB-only source mutation callback for durable scheduled delivery. */ export declare function settleScheduledTaskRunInTransaction(tx: Database, input: { workspaceId: string; runId: string; sessionId: string; triggerEventId: string | null; status: "dispatched" | "skipped"; error?: string | null; }): Promise; export declare function listScheduledTaskRuns(db: Database, workspaceId: string, taskId: string, limit?: number): Promise; export declare class RigChangeTransitionError extends Error { readonly changeId: string; readonly fromStatus: string; readonly toStatus: string; constructor(changeId: string, fromStatus: string, toStatus: string); } export declare class RigActiveVersionChangedError extends Error { readonly rigId: string; readonly expectedVersionId: string; readonly actualVersionId: string | null; constructor(rigId: string, expectedVersionId: string, actualVersionId: string | null); } export declare class RigChangeAlreadyVerifyingError extends Error { readonly changeId: string; constructor(changeId: string); } export declare class RigImageOverrideUnsupportedError extends Error { constructor(); } 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; }; export declare 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; export type RigAccessContext = { accountId: string; workspaceId: string; subjectId: string; }; export declare function listRigs(db: Database, access: string | RigAccessContext): Promise; export declare function getRig(db: Database, access: string | RigAccessContext, rigId: string): Promise; export declare function getRigByName(db: Database, access: string | RigAccessContext, name: string, scope?: Rig["scope"]): Promise; export declare function updateRig(db: Database, workspaceId: string, rigId: string, input: { name?: string; description?: string | null; }): Promise; export declare function deleteRig(db: Database, workspaceId: string, rigId: string): Promise; export declare function deleteRigIfNoActiveSessions(db: Database, workspaceId: string, rigId: string): Promise<{ deleted: boolean; activeSessionCount: number; }>; export declare function updateScopedRig(db: Database, access: RigAccessContext, rigId: string, input: { name?: string; description?: string | null; allowOrganization?: boolean; }): Promise; export declare function revokeScopedRig(db: Database, access: RigAccessContext, rigId: string, options?: { allowOrganization?: boolean; }): Promise; /** 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[]; }; /** 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 declare function updateOrganizationRigReach(db: Database, rigId: string, input: OrganizationComputeReachInput): Promise; /** 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 declare function listOrganizationCompute(db: Database, access: RigAccessContext, kind: "machine" | "rig"): Promise; export declare class ChannelNameConflictError extends Error { constructor(name: string); } export declare class ChannelNotFoundError extends Error { constructor(channelId: string); } /** * 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 declare class ChannelAudienceMismatchError extends Error { constructor(kind: "chat" | "app"); } export declare 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; export declare function listChannels(db: Database, workspaceId: string): Promise; export declare function getChannel(db: Database, workspaceId: string, channelId: string): Promise; export declare 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; export declare function deleteChannel(db: Database, workspaceId: string, channelId: string): Promise; /** * 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 declare function reorderChannels(db: Database, workspaceId: string, channelIds: readonly string[]): Promise; export declare function setSessionChannel(db: Database, input: { workspaceId: string; sessionId: string; channelId: string | null; }): Promise; /** Bound on the conversations one Site row move re-files. */ export declare 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 declare function listSiteProjectConversationIds(db: Database, input: { workspaceId: string; subjectId: string; siteId: string; channelId: string | null; }): Promise; /** * 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 declare 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[]; }>; export declare function countRigs(db: Database, access: string | RigAccessContext, scope?: Rig["scope"]): Promise; export declare function countSessionsUsingRig(db: Database, workspaceId: string, rigId: string): Promise; export declare function createRigVersion(db: Database, workspaceId: string, rigId: string, input: RigVersionContentInput, options?: { activate?: boolean; }): Promise; export declare function createRigVersionForChangePromotion(db: Database, workspaceId: string, rigId: string, changeId: string, input: RigVersionContentInput & { expectedActiveVersionId: string; providerImages?: RigProviderImages; }): Promise<{ version: RigVersion; change: RigChange; }>; export declare function listRigVersions(db: Database, workspaceId: string, rigId: string): Promise; 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 declare function listRigVersionMonitoringSummaries(db: Database, workspaceId: string, rigId: string, limit?: number): Promise<{ versions: RigVersionMonitoringSummary[]; hasMore: boolean; total: number; }>; export declare function getRigVersion(db: Database, workspaceId: string, rigId: string, versionId: string): Promise; /** 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 declare function getScheduledScopedRigVersionMetadata(db: Database, access: RigAccessContext, rigId: string, versionId: string): Promise<{ name: string; version: RigVersion; health: RigVerificationHealth; } | null>; export declare 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>; /** Metadata-only health for one exact frozen rig version. Never reads setup, * variable values, credential material, or the currently active version. */ export declare function getRigVersionHealth(db: Database, workspaceId: string, rigId: string, versionId: string): Promise; export declare function getRigVersionById(db: Database, workspaceId: string, versionId: string): Promise; 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; }; /** * 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 declare 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; /** 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 declare function finalizeRigVersionProviderImageBuild(db: Database, input: { workspaceId: string; versionId: string; image: RigProviderImage; }): Promise; export declare function getRigName(db: Database, workspaceId: string, rigId: string): Promise; export declare function activateRigVersion(db: Database, workspaceId: string, rigId: string, versionId: string): Promise; export declare function createRigChange(db: Database, input: { accountId: string; workspaceId: string; rigId: string; baseVersionId?: string | null; kind: RigChangeKind; payload: Record; proposedBy?: string | null; }): Promise; export declare function listRigChanges(db: Database, workspaceId: string, rigId: string, limit?: number): Promise; 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 declare function listRigChangeMonitoringSummaries(db: Database, workspaceId: string, rigId: string, limit?: number): Promise<{ changes: RigChangeMonitoringSummary[]; hasMore: boolean; total: number; }>; export declare function getRigChange(db: Database, workspaceId: string, changeId: string): Promise; export declare function updateRigChangeStatus(db: Database, workspaceId: string, changeId: string, input: { status: RigChangeStatus; verification?: Record | null; resultVersionId?: string | null; }): Promise; export declare function beginRigChangeVerificationAttempt(db: Database, workspaceId: string, changeId: string, input: { startedAt: string; allowAlreadyVerifying?: boolean; }): Promise; /** * 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 declare function getSessionAuthorityEpoch(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; }): Promise; /** * 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 declare function namedSubjectHasLiveWorkspaceAuthority(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; }): Promise; /** * 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 declare function resolveSlackTargetAuthority(db: Database, input: { subjectId: string; targetAccountId: string; targetWorkspaceId: string; }): Promise; /** * 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 declare function inventoryOrganizationTenancy(db: Database, input: { organizationId: string; }): Promise>; /** * 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 declare const TENANCY_PARITY_GATES: readonly TenancyParityGateDefinition[]; /** * Compatibility lanes. These are legacy populations, NOT invariant violations: * a non-zero lane blocks a cutover but is not schema corruption. */ export declare const TENANCY_PARITY_LANES: readonly TenancyParityLaneDefinition[]; /** * 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 declare const TENANCY_PARITY_UNVERIFIABLE: readonly TenancyParityUnverifiable[]; /** * 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 declare function composeTenancyParityReport(raw: Record, options?: { generatedAt?: string; }): TenancyParityReport; /** * 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 declare function checkOrganizationTenancyParity(db: Database, input: { organizationId: string; evidenceLimit?: number; observationWindowDays?: number; generatedAt?: string; }): Promise; /** * 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 declare function verifyOrganizationResourceClassification(db: Database, input: { organizationId: string; runKey?: string | null; }): Promise>; /** * 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 declare function classifyOrganizationSessionOwnership(db: Database, input: { organizationId: string; runKey?: string | null; }): Promise>; /** * 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 declare function backfillOrganizationSessionOwnership(db: Database, input: { organizationId: string; limit?: number; dryRun?: boolean; runKey?: string | null; }): Promise>; export declare class CodexSubscriptionSourceChangeBlockedError extends Error { readonly code = "codex_subscription_source_change_blocked"; constructor(); } export declare function fetchOrganizationCodexUsageForAccount(db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string; }, fetchImpl?: CodexFetch, refresh?: CodexAuthDeps["refresh"]): Promise; /** * One organization-managed Codex connection (canonical id or legacy alias) * for an organization administrator; null when the id is not one. */ export declare function findOrganizationCodexConnectionForAdministrator(db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string; }): Promise<{ credentialId: string; status: string; } | null>; /** * The bearer of one organization-managed Codex connection for an * organization administrator (usage limit resets on the organization page). */ export declare function buildOrganizationCodexAdministratorTokenResolver(db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; credentialId: string; }, refresh?: CodexAuthDeps["refresh"]): { getToken: () => Promise; refresh: () => Promise; }; /** * 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 declare function resolveOrganizationCodexRedemptionWorkspace(db: Database, input: { organizationId: string; actorSubjectId: string; }): Promise; /** * 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 declare function assertOrganizationCodexAdministrator(db: Database, input: { organizationId: string; actorSubjectId: string; }): Promise; export type CodexAppsSettings = { credentialId: string | null; version: number; designatedAt: Date | null; }; /** A specific designated-credential unavailability observed at request time. */ export declare class CodexAppsAuthorizationRevokedError extends CodexAppsCredentialUnavailable { constructor(); } /** * 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 declare function workspaceCodexSubscriptionActive(db: Database, settings: Pick, workspaceId: string, acceptedTurnId?: string, context?: { accountId?: string | null; subjectId?: string | null; }): Promise; /** * 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 declare 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; export declare class CodexCredentialLeaseAttemptFencedError extends Error { readonly code = "codex_credential_lease_attempt_fenced"; constructor(); } export declare class CodexCredentialFailoverExhaustedError extends Error { readonly failoverCount: number; readonly maxFailovers: number; readonly code = "codex_credential_failover_exhausted"; constructor(failoverCount: number, maxFailovers: number); } /** * 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 declare const CODEX_CREDENTIAL_LEASE_TTL_MS: number; 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 declare const CODEX_CAPACITY_REFRESH_MIN_MS = 60000; export declare const CODEX_CAPACITY_REFRESH_MAX_MS: number; /** * 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 declare function codexCapacityRefreshBackoffMs(attempt: number): number; /** * 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; /** Whether a provider's core waiter rechecks before its stored reset (see the vocabulary). */ export declare function subscriptionCoreWaiterRechecksBeforeReset(provider: SubscriptionCoreWaiterProvider): boolean; 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; }; /** * 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 declare 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; }; /** The workflow reference of any provider's core waiter (Codex's carries no `provider`). */ export declare const subscriptionCoreCapacityWaitRef: typeof subscriptionCoreCodexCapacityWaitRef; /** The session's waiting core Codex waiter, if any (workflow peek and recovery). */ export declare function getSubscriptionCoreCodexCapacityWaitForSession(db: Database, workspaceId: string, sessionId: string): Promise; /** Same lookup by the exact waiter id a workflow history recorded. */ export declare function getSubscriptionCoreCodexCapacityWaitById(db: Database, input: { workspaceId: string; sessionId: string; waiterId: string; }): Promise; /** The session's core waiter of any provider (the provider-neutral workflow peek). */ export declare function getSubscriptionCoreCapacityWaitForSession(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function getSubscriptionCoreCapacityWaitById(db: Database, input: { workspaceId: string; sessionId: string; waiterId: string; }): Promise; /** * 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 declare 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; }; 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 declare function armSubscriptionCoreCodexCapacityWait(db: Database, input: ArmSubscriptionCoreCapacityWaitInput): Promise; 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 declare function armSubscriptionCoreCapacityWait(db: Database, provider: SubscriptionCoreWaiterProvider, input: ArmSubscriptionCoreCapacityWaitInput): Promise; /** 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[]; }; /** * 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 declare 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; /** * 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 declare 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; /** * 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 declare function withSubscriptionCapacityWakeOutboxScope(db: Database, scope: { accountId: string; workspaceId: string; }, operation: (tx: Database) => Promise): Promise; /** 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 declare 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; /** * The same wake for any provider on the core (the generic session workflow * wake included). Refused for a provider without a registered binding. */ export declare function wakeSubscriptionCoreProviderCapacityWaiters(db: Database, provider: SubscriptionCoreWaiterProvider, input: { accountId: string; reason: string; workspaceIds?: readonly string[]; sessionIds?: readonly string[]; }): Promise; /** Shared durable scoped-subscription waiter state machine. */ /** Commit organization subscription policy and its durable capacity wake atomically. */ export declare function updateModelConnectionAccess(db: Database, target: ModelConnectionTarget, policy: ModelConnectionAccess): Promise; /** Compose existing pool metadata without a leaf-to-root database import cycle. */ export declare function getWorkspaceConnectionModelRestrictions(db: Database, workspaceId: string, subjectId: string, claudeAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1, claudeCoreRestrictions?: ClaudeCoreModelRestrictions, workspaceConnections?: Promise): Promise; export declare const CODEX_RESET_REDEMPTION_OUTCOMES: readonly ["reset", "nothingToReset", "noCredit", "alreadyRedeemed"]; 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; }; /** Metadata-only attempt read used to resume a browser-session-bound ambiguity. */ export declare function getCodexResetRedemptionAttempt(db: Database, workspaceId: string, attemptId: string): Promise; 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 declare function adoptCodexResetRedemptionAttempt(db: Database, input: { accountId: string; workspaceId: string; attemptId: string; credentialId: string; creditId: string; subjectId: string; browserSessionHash: string; }, authority: CodexResetRedemptionCredentialAuthority): Promise; 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 declare 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): Promise; 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 declare function fenceCodexResetRedemptionSend(db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; credentialId: string; subjectId: string; browserSessionHash: string; sendLeaseMs?: number; }, authority: CodexResetRedemptionCredentialAuthority): Promise; /** Delete only definite pre-provider work still owned by this request. */ export declare function abandonCodexResetRedemptionBeforeProvider(db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; }): Promise; /** Release a failed claim while preserving processing/provider_started truth. */ export declare function releaseCodexResetRedemptionClaim(db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; failureKind: string; }): Promise; /** * 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 declare const subscriptionCoreCodexResetAuthority: CodexResetRedemptionCredentialAuthority; /** The core ledger's cross-workspace credit fence (`subscription_codex_reset_credit_fence`). */ export declare const subscriptionCoreCodexResetCreditFence: CodexResetCreditFence; /** * 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 declare function fenceSubscriptionCoreCodexResetCredit(db: Database, input: Parameters[1]): Promise>>; /** * 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 declare function completeSubscriptionCoreCodexResetRedemption(db: Database, input: { accountId: string; workspaceId: string; attemptId: string; claimHolderId: string; outcome: CodexResetRedemptionOutcome; }): Promise<{ attempt: CodexResetRedemptionAttempt | null; wake: SubscriptionCoreCodexWake | 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 declare function listSubscriptionCoreCodexResetRedemptionRecoveries(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; }): Promise; /** Per-connection redemption authority for the caller, read outside the ledger. */ export declare function readSubscriptionCoreCodexResetAuthority(db: Database, input: { accountId: string; workspaceId: string; credentialId: string; subjectId: string; }): Promise<{ status: string; owned: boolean; } | null>; /** * 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; }; /** * The workspace's own policy row and the organization's ceiling above it. * `organization` is null when the organization allows every model. */ export declare 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; }>; /** * 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 declare function getWorkspaceModelPolicy(db: Database, workspaceId: string): Promise; /** Remove the workspace's own policy so it uses its organization's list as is. */ export declare function deleteWorkspaceModelPolicy(db: Database, input: { accountId: string; workspaceId: string; }): Promise; /** * 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 declare function upsertWorkspaceModelPolicy(db: Database, input: { accountId: string; workspaceId: string; allowedProviders: string[] | null; allowedModels: string[] | null; }): Promise; /** Lease-backed serving audit, written after placement in its own fenced * transaction. Proposals and claim-time provenance alone emit no transition. */ export declare 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; }>; /** Legacy Codex audit/alias, projected from core placement without writing * the old session credential pointer. Idempotent under the same attempt fence. */ export declare 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; }>; /** * 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 declare function getSubscriptionCoreSessionCodexAccounts(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; viewerSubjectId?: string | null; }): Promise<{ accounts: import("./codex-account-types.js").CodexAccountStatus[]; rotation: import("./codex-account-types.js").CodexRotationSettings; currentSelection: { waiting: boolean; credentialId: string | null; } | null; currentAccount: import("./codex-account-types.js").CodexAccountStatus | null; pinnedAccountId: string | null; lastAccountId: string | null; } | 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 declare function getSubscriptionCoreCodexSessionPointers(db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[]; }): Promise>; /** * 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 declare function getSubscriptionCoreCodexCurrentSelections(db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[]; }): Promise>; /** * Deliver a core Codex wake after the mutation that caused it committed. * Codex's binding of the provider-neutral `deliverSubscriptionCoreWake`. */ export declare function deliverSubscriptionCoreCodexWake(db: Database, wake: SubscriptionCoreCodexWake | null): Promise; /** * 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 declare function deliverSubscriptionCoreWake(db: Database, provider: string, wake: SubscriptionCoreWake | null, /** The provider's display name in the log line. */ label?: string): Promise; /** * 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 declare function deliverSubscriptionCoreProviderWake(db: Database, provider: import("@opengeni/subscriptions").ProviderId, wake: { accountId: string; reason: string; workspaceIds?: readonly string[]; }): Promise; /** * 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 declare function deliverSubscriptionCoreProviderWakes(db: Database, wakes: readonly SubscriptionCoreProviderWake[]): Promise; export declare function recordAuditEvent(db: Database, input: { accountId: string; workspaceId?: string | null; subjectId?: string | null; action: string; targetType?: string | null; targetId?: string | null; metadata?: Record; }): Promise; export declare function createSessionMcpServers(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; servers: CreateSessionMcpServerInput[]; }): Promise; export declare function listSessionMcpServerMetadata(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function listSessionMcpServersForChildInheritance(db: Database, workspaceId: string, sessionId: string): Promise; export declare function updateSessionMcpServerCredentials(db: Database, input: { workspaceId: string; sessionId: string; updates: UpdateSessionMcpServerCredentialsInput[]; }): Promise; export declare function updateSessionMcpApprovalPolicy(db: Database, input: { workspaceId: string; sessionId: string; serverId: string; requireApproval: SessionMcpApprovalPolicy; }): Promise; export declare function listSessionMcpServersForRun(db: Database, workspaceId: string, sessionId: string, attemptId: string, encryptionKey: Uint8Array | null): Promise; 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; }; export type ConnectorActionPolicyWrite = { accountId: string; workspaceId: string; subjectId: string; connectionId: string; serverId: string; toolName: string; actionName: string; policy: ConnectorActionPolicyDecision; }; export declare function upsertConnectorActionPolicies(db: Database, inputs: readonly ConnectorActionPolicyWrite[]): Promise>; export declare function upsertConnectorActionPolicy(db: Database, input: ConnectorActionPolicyWrite): Promise<{ policy: typeof schema.connectorActionPolicies.$inferSelect; changed: boolean; }>; export declare function listConnectorActionPolicies(db: Database, input: { accountId: string; workspaceId: string; connectionIds: readonly string[]; }): Promise; /** * 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 declare function connectorActionPolicySnapshotForTurn(db: Database, input: { accountId: string; workspaceId: string; bindings: readonly McpConnectionAccountBinding[] | null; }): Promise; /** * Install a risk-appropriate connector default without overwriting an explicit * user choice that already exists for the same immutable connector action. */ export declare 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; }>; export declare function prepareConnectorActionApproval(db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation): Promise; /** Resolve the frozen connector policy without creating approval or audit state. */ export declare function previewConnectorActionApproval(db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation): Promise; /** * 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 declare 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">; export declare function beginConnectorActionExecution(db: Database, identity: ConnectorActionAttemptIdentity, invocation: ConnectorActionInvocation): Promise; export declare 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; /** Read the persisted deployment fallback; process configuration is not policy authority. */ export declare function getNestedAgentDepthDeploymentPolicy(db: Database): Promise; type AgentSessionCreationActor = Extract; /** A caller-preallocated session UUID is already owned by another session. */ export declare class SessionIdConflictError extends Error { readonly sessionId: string; constructor(sessionId: string); } export declare class SessionCreateIdempotencyConflictError extends Error { constructor(); } /** 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 declare class SessionCreateIdempotencyUnavailableError extends Error { readonly name = "SessionCreateIdempotencyUnavailableError"; constructor(); } 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; }; /** Canonical creation metadata shared with strict generated-session admission. */ export declare function metadataWithAgentConfigCreateIdentity(metadata: Record, config: ResolvedAgentConfig | null | undefined): Record; /** * 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 declare function parseStoredSessionAgentConfig(value: unknown): ResolvedAgentConfig | null; /** The agent a new chat starts with is gone, or not one its creator can see. */ export declare class SessionAgentNotFoundError extends Error { readonly agentId: string; readonly reason: "not_found" | "child_chat" | "requires_private_chat"; readonly name = "SessionAgentNotFoundError"; constructor(agentId: string, reason?: "not_found" | "child_chat" | "requires_private_chat"); } export declare function createSession(db: Database, input: SessionCreateInput): Promise; /** * 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 declare function createSessionWithIdempotencyKeyResult(db: Database, input: SessionCreateInput & { createIdempotencyKey: string; }): Promise; /** * 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 declare function createSessionWithIdempotencyKey(db: Database, input: SessionCreateInput & { createIdempotencyKey: string; }): Promise; export declare function getSessionByCreateIdempotencyKey(db: Database, workspaceId: string, createIdempotencyKey: string): Promise; /** * 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 declare 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; /** Read the canonical sequence without materializing the session presentation. */ export declare function getSessionEventSequence(db: Database, workspaceId: string, sessionId: string): Promise; /** Who can open a chat: the workspace, or only its owner. Null when it does not exist. */ export declare function getSessionVisibility(db: Database, workspaceId: string, sessionId: string): Promise<"workspace_shared" | "user_private" | null>; export declare function getSession(db: Database, workspaceId: string, sessionId: string): Promise; /** Fresh admission read; retain canonical control/policy/row validation without UI decorations. */ export declare function getSessionModelGate(db: Database, workspaceId: string, sessionId: string): Promise | null>; 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 declare function discardUninitializedSessionShell(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; discardKeyed?: boolean; }): Promise; 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 declare 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; /** * 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; }; export declare function getSessionAuthorityProjection(db: Database, workspaceId: string, sessionId: string): Promise; /** One live RLS read for a response window; absent and hidden rows stay absent. */ export declare function getSessionAuthorityProjections(db: Database, workspaceId: string, sessionIds: readonly string[]): Promise>; /** Workspace-RLS read of one session's frozen agent-access and memory scope. */ export declare function getSessionAccessProjection(db: Database, workspaceId: string, sessionId: string): Promise; /** 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 declare function getSessionAuthorizationFacts(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; caller?: { sessionId: string; attemptId: string; } | undefined; }): Promise; /** Canonical authorization facts for one bounded response window, not an authority cache. */ export declare function getSessionAuthorizationFactsBatch(db: Database, input: { accountId: string; workspaceId: string; sessionIds: readonly string[]; caller?: { sessionId: string; attemptId: string; } | undefined; }): Promise>; /** * 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 declare function resolveSessionMemoryAgentScope(db: Database, workspaceId: string, sessionId: string, caller?: { turnId?: unknown; attemptId?: unknown; executionGeneration?: unknown; }): Promise; export declare function memoryAgentScopeForSessionAccess(access: Pick): MemoryAgentScope; export declare function getSessionTurnMcpAccountBindings(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; /** The exact turn's account intent; null for a turn accepted before intent existed. */ export declare function getSessionTurnConnectionAccountIntent(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; export declare function getSessionParentMcpAccountBindings(db: Database, workspaceId: string, childSessionId: string): Promise; export declare function getSessionTurnXaiProviderAccountAuthoritySnapshot(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; export declare function getSessionTurnPersonalConnectionDelegations(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; export declare function getSessionParentPersonalConnectionDelegations(db: Database, workspaceId: string, childSessionId: string): Promise; export declare function getSessionParentXaiProviderAccountAuthority(db: Database, workspaceId: string, childSessionId: string): Promise; /** 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; }; /** * 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 declare function getSessionChainRoot(db: Database, workspaceId: string, sessionId: string): Promise; export declare function getSessionSpawnDenial(db: Database, workspaceId: string, denialId: string): Promise; export declare function getSessionSpawnDenialByIdempotencyKey(db: Database, workspaceId: string, createIdempotencyKey: string): Promise; export declare function listSessionSpawnDenials(db: Database, workspaceId: string, options?: { limit?: number; parentSessionId?: string | null; }): Promise; /** * 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 declare function getAnySessionInGroup(db: Database, workspaceId: string, sandboxGroupId: string): Promise; export declare function listDistinctRigVersionIdsInGroup(db: Database, workspaceId: string, sandboxGroupId: string): Promise>; export declare function getWorkspaceDefaultRigId(db: Database, workspaceId: string): Promise; 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 declare 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 declare class SessionPinVersionConflictError extends Error { readonly current: Pick; constructor(current: Pick); } /** Archived chats leave the Pinned list with every other list, so they cannot be pinned. */ export declare class SessionArchivedPinError extends Error { readonly code = "session_archived_pin"; constructor(); } export declare class SessionAttentionVersionConflictError extends Error { readonly current: Pick; constructor(current: Pick); } export declare class SessionListCursorError extends Error { constructor(message?: string); } export declare class SessionListCursorExpiredError extends Error { constructor(message?: string); } export declare class SessionListAccessError extends Error { constructor(message?: string); } export declare class SessionPinAccessError extends Error { constructor(message?: string); } /** * 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 declare function requireSessionArchiveMemberAuthority(db: Database, input: { workspaceId: string; subjectId: string; personalWorkspaceOwnerException?: PersonalWorkspaceOwnerException | undefined; }): Promise; 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 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"; /** * 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 declare function currentSessionWaitingOn(row: Pick, facts: { initiatorSubjectId: string | null; latestTurnId: string | null; }): SessionWaitingOn | 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 declare function currentSessionInputWaitTurnsQuery(db: Database, workspaceId: string, sessionIds: readonly string[]): Omit; turnId: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "latest_wait_turn"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }, "partial", Record<"sessions", "not-null"> & { latest_wait_turn: "nullable"; }, false, "where", { id: string; turnId: string | null; }[], { id: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; turnId: import("drizzle-orm").Column, { notNull: false; }>, object, object>; }>, "where">; type SessionTreeStats = NonNullable; /** * 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 declare function projectEffectiveControlForRelatedAccess(control: Session["effectiveControl"], sessionId: string, access: "target" | "root"): Session["effectiveControl"]; /** * Remove metadata derived from sessions other than the exact authorized * target, including parent identity, policy provenance, and descendant counts. */ export declare function projectSessionForRelatedAccess(session: Session, access: "target" | "root"): Session; /** * 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 declare function sessionTreeStatsForSessions(db: Database, workspaceId: string, rootIds: string[], subjectId?: string): Promise>; /** * 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 declare function sessionRequiresActionSinceForSessions(db: Database, workspaceId: string, sessionIds: readonly string[]): Promise>; /** * 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 declare function sessionLatestTurnsForSessions(db: Database, workspaceId: string, sessionIds: readonly string[]): Promise>; /** * 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 declare const SITE_CONVERSATION_GROUP_LIMIT = 200; /** * 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 declare function sessionAgentAccessViewerFilter(viewer: SessionAgentAccessViewer): SQL; /** * 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 declare function sessionAuthorizationScopeFilter(scope: SessionAuthorizationListScope): SQL; /** * 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 declare const SESSION_LIST_SNAPSHOT_REDACTED_SESSION_ID = "00000000-0000-0000-0000-000000000000"; /** Opaque, URL-safe cursor encoding for bounded session-list pagination. */ export declare function encodeSessionListCursor(cursor: SessionListCursor): string; /** Decode and validate a cursor before it reaches any SQL predicate. */ export declare function decodeSessionListCursor(value: string): SessionListCursor | null; /** Bounded global TTL cleanup, isolated from serializable member list reads. */ export declare function reapExpiredSessionListSnapshots(db: Database, limit?: number): Promise; /** 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 declare function searchSessionMessagesForSubject(db: Database, workspaceId: string, request: SessionMessageSearchRequest, authority: Pick, options?: { signal?: AbortSignal | undefined; }): Promise; /** Console projection over live commands, with the same membership and audience * boundary as ordinary chat discovery. Archived chats may still own live work. */ export declare function listWorkspaceBackgroundCommandsForSubject(db: Database, workspaceId: string, authority: Pick, afterId?: string): Promise<{ commands: import("./session-background-commands.js").WorkspaceBackgroundCommand[]; nextCursor: string | null; }>; /** * 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 declare function listSessionsForSubject(db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, skills: SessionSkillsRead): Promise; export declare function listSessionsForSubject(db: Database, workspaceId: string, options: ListSessionsForSubjectOptions, skills?: "read"): Promise; /** 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 declare function listSessionEntriesForSubject(db: Database, workspaceId: string, options: ListSessionsForSubjectOptions): Promise; type SessionListReadAuthority = Pick; /** No configuration, parent IDs or inaccessible IDs cross the hint boundary. */ export declare function listVisibleSessionInvalidationIds(db: Database, workspaceId: string, sessionIds: string[], authority: SessionListReadAuthority): Promise; /** * 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 declare function listVisibleSessionInvalidationHints(db: Database, workspaceId: string, sessionIds: string[], authority: SessionListReadAuthority): Promise<{ sessionIds: string[]; siteSessionIds: string[]; }>; /** A response that never carries the Skill folders passes `skills: "omit"`. */ export declare function getSessionForSubject(db: Database, workspaceId: string, sessionId: string, subjectId: string, relatedSessionAccess: "target" | "root", skills: SessionSkillsRead): Promise; export declare function getSessionForSubject(db: Database, workspaceId: string, sessionId: string, subjectId: string, relatedSessionAccess?: "target" | "root", skills?: "read"): Promise; /** * 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 declare 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; /** * 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 declare 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; export declare function listSessions(db: Database, workspaceId: string, limit?: number): Promise; export declare function listSessions(db: Database, workspaceId: string, options?: ListSessionsOptions): Promise; /** * 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 declare function getLatestSessionModelForSubject(db: Database, workspaceId: string, subjectId: string): Promise; 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 declare const SESSION_DISCOVERY_GOAL_MAX_CHARS = 600; export declare 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; }; /** * 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 declare 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; }>; 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 declare function listSessionDiscoveryAncestorPaths(db: Database, workspaceId: string, sessionIds: string[], authorizationScope?: SessionAuthorizationListScope, subjectId?: string): Promise>; 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 declare function getSessionRootId(db: Database, workspaceId: string, sessionId: string): Promise; /** Descendants a lineage read lists: depth 5 and this many rows at most. */ export declare const SESSION_TREE_DESCENDANT_LIMIT = 200; /** * 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 declare function listSessionTreeIds(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function getSessionLineage(db: Database, workspaceId: string, sessionId: string, skills: SessionSkillsRead): Promise; export declare function getSessionLineage(db: Database, workspaceId: string, sessionId: string, skills?: "read"): Promise; /** * 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 declare function countActiveSessionsForWorkspace(db: Database, workspaceId: string): Promise; /** Immutable creation evidence for scheduled-session binding checks, never continuation defaults. */ export declare function getSessionCreationExecutionPolicy(db: Database, workspaceId: string, sessionId: string): Promise<{ model: string; reasoningEffort: string; latencyMode: string; } | null>; export declare function requireSession(db: Database, workspaceId: string, sessionId: string): Promise; 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; }; 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; }; export declare const SESSION_EVENT_DB_PAGE_MAX_BYTES: number; /** * Largest canonical event payload a full-mode history read returns verbatim. * Larger legacy rows are projected in SQL to an explicit preview. */ export declare const SESSION_EVENT_FULL_READ_MAX_PAYLOAD_BYTES: number; /** A previewed step read returns tool-output payloads up to this size exactly. */ export declare const SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MIN_BYTES: number; /** Hard ceiling of one previewed tool-output payload (structured or text). */ export declare const SESSION_EVENT_TOOL_OUTPUT_PREVIEW_MAX_BYTES: number; /** * 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 declare function readSessionEventStorageGapEnd(db: Database, workspaceId: string, sessionId: string, after: number): Promise; /** * 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 declare function listSessionEventPage(db: Database, workspaceId: string, sessionId: string, options?: ListSessionEventPageOptions): Promise; 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; }; /** * 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 declare function listSessionEventConversationBookkeeping(db: Database, workspaceId: string, sessionId: string, options: { turns: readonly SessionEventConversationTurn[]; after: number; before?: number | undefined; payloadMode?: SessionEventPayloadMode; }): Promise; export declare function listSessionEvents(db: Database, workspaceId: string, sessionId: string): Promise; export declare function listSessionEvents(db: Database, workspaceId: string, sessionId: string, after: number, limit?: number): Promise; export declare function listSessionEvents(db: Database, workspaceId: string, sessionId: string, options: ListSessionEventsOptions): Promise; /** * 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 declare function listOwedModelUsageSettlements(db: Database, workspaceId: string, input: { sessionId: string; turnId?: string; attemptId?: string; since?: Date; }): Promise>; export declare function getSessionEvent(db: Database, workspaceId: string, eventId: string): Promise; /** * 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 declare function cancelSiteRuntimeConversation(db: Database, input: { accountId: string; workspaceId: string; siteId: string; sessionId: string; operationKey: string; reason: string; }): Promise<{ receiptId: string; replay: boolean; cancelledSessionCount: number; cancelledTurnCount: number; wakeCount: number; events: { id: string; workspaceId: string; sessionId: string; sequence: number; coveredThrough?: number | undefined; type: "agent.message.completed" | "agent.message.delta" | "agent.model.request" | "agent.model.usage" | "agent.reasoning.delta" | "agent.toolCall.created" | "agent.toolCall.output" | "agent.updated" | "artifact.created" | "codex.account.selection.changed" | "codex.account.switched" | "codex.capacity.resumed" | "codex.capacity.superseded" | "codex.capacity.waiting" | "codex.credential.selected" | "codex.fleet.decision" | "credential.auth_needed" | "fs.changed" | "git.changed" | "goal.cleared" | "goal.completed" | "goal.continuation" | "goal.held" | "goal.paused" | "goal.progress" | "goal.resumed" | "goal.rewrite.proposed" | "goal.rewrite.rejected" | "goal.set" | "goal.updated" | "instruction.confirmation.recovered" | "knowledge.confirmation.recovered" | "knowledge.source.failed" | "knowledge.source.prepared" | "machine.link.lost" | "machine.link.restored" | "machine.op.failed" | "machine.op.recovered" | "machine.runner.restarted" | "memory.corrected" | "memory.saved" | "model_account.selection.changed" | "recording.available" | "recording.failed" | "recording.started" | "rig.setup.completed" | "rig.setup.failed" | "rig.setup.skipped" | "rig.setup.started" | "sandbox.box.created" | "sandbox.box.lost" | "sandbox.box.snapshot" | "sandbox.box.terminated" | "sandbox.command.output.delta" | "sandbox.env.drift" | "sandbox.operation.completed" | "sandbox.operation.failed" | "sandbox.operation.started" | "sandbox.recovery.selected" | "session.agent.updated" | "session.agentCall.ringing" | "session.agentCall.settled" | "session.command.backgrounded" | "session.command.finished" | "session.context.cleared" | "session.context.compacted" | "session.context.compaction.requested" | "session.context.compaction.skipped" | "session.context.compaction.started" | "session.control.paused" | "session.control.resumed" | "session.control.steer_requested" | "session.created" | "session.event.envelope_omitted" | "session.humanInput.requested" | "session.links.changed" | "session.mcp.approval_policy.updated" | "session.model_settings.updated" | "session.notification.posted" | "session.notification.withdrawn" | "session.personal_resources.attached" | "session.profile_set" | "session.queue.changed" | "session.queue.history" | "session.queue.prompt.cancelled" | "session.realtime.ended" | "session.realtime.started" | "session.requiresAction" | "session.resources.added" | "session.resources.removed" | "session.route.reconciled" | "session.runtime.configured" | "session.skills.updated" | "session.status.changed" | "session.title_set" | "session.tool_policy.updated" | "session.tool_server.unavailable" | "session.usage_limit.updated" | "session.variable_sets.updated" | "session.visibility.changed" | "session.wait.finished" | "session.wait.started" | "session.waiting_on.changed" | "stream.closed" | "stream.opened" | "stream.revoked" | "stream.url.rotated" | "subscription.account.selected" | "subscription.account.switched" | "system.update.cancelled" | "system.update.delivered" | "system.update.pending" | "system.update.settled" | "system.update.superseded" | "terminal.pty.exited" | "terminal.pty.output.delta" | "terminal.pty.started" | "tool.auth_needed" | "tool.discovery_card" | "turn.cancelled" | "turn.capacity_waiting" | "turn.completed" | "turn.dispatch.expired" | "turn.event.rejected_late" | "turn.failed" | "turn.queued" | "turn.recovery.requested" | "turn.started" | "turn.startup.phase.completed" | "turn.startup.phase.failed" | "turn.startup.phase.started" | "turn.superseded" | "usage.exhausted" | "usage.period_reset" | "usage.threshold_reached" | "user.approvalDecision" | "user.humanInputResponse" | "user.message" | "user.pause" | "workspace.inference.paused" | "workspace.inference.resumed" | "workspace.revision.captured" | "workspace.revision.degraded"; payload: unknown; occurredAt: string; clientEventId?: string | null | undefined; turnId?: string | null | undefined; turnGeneration?: number | null | undefined; turnAttemptId?: string | null | undefined; turnAssociation?: "current" | "duplicate" | "late_rejected" | null | undefined; duplicateOfEventId?: string | null | undefined; duplicateReason?: string | null | undefined; }[]; workspaceEvent: { id: string; workspaceId: string; sequence: number; revision: number; type: "workspace.control.changed"; scope: "session" | "workspace"; rootSessionId: string | null; action: "pause" | "resume" | "timer_cancelled" | "timer_set"; automatic: boolean; reason: string | null; actor: string; occurredAt: string; truncation?: { truncated: true; surface: "database_guard" | "durable_control" | "http_projection" | "nats_legacy_guard" | "sse_legacy_guard"; deliveredBytes: number; fields: { field: "actor" | "reason"; originalBytes: number; deliveredBytes: number; omittedBytes: number; }[]; fullEvidence: { available: false; reason: "not_retained"; }; } | null | undefined; } | null; } | null>; /** Read one durable event under the exact human subject visibility projection. */ export declare function getSessionEventForSubject(db: Database, workspaceId: string, subjectId: string, eventId: string): Promise; export declare function listWorkspaceControlEvents(db: Database, workspaceId: string, after?: number, limit?: number): Promise; export declare function getWorkspaceControlEvent(db: Database, workspaceId: string, eventId: string): Promise; /** * 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 declare function getSessionEventByClientEventId(db: Database, workspaceId: string, sessionId: string, clientEventId: string): Promise; /** * 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 declare function getSessionToolCallCreatedEventByOperationId(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; operationId: string; }): Promise; export declare const APPROVAL_RUN_STATE_MAX_JSON_BYTES: number; export declare const APPROVAL_RUN_STATE_MAX_JSON_NODES = 65536; export declare const APPROVAL_RUN_STATE_MAX_JSON_PROPERTIES = 32768; export declare const APPROVAL_PENDING_MAX_JSON_BYTES: number; export declare 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 declare class ApprovalRunStateLimitExceededError extends Error { readonly limitKind: ApprovalRunStateLimitKind; readonly actual: number; readonly maximum: number; readonly code = "approval_run_state_too_large"; constructor(limitKind: ApprovalRunStateLimitKind, actual: number, maximum: number); } /** * 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 declare function getLatestRunState(db: Database, workspaceId: string, sessionId: string, limitOverrides?: Partial): Promise<{ id: string; turnId: string | null; serializedRunState: string; pendingApprovals: unknown[]; providerArtifactInvalidatedAt: Date | null; } | null>; export declare class HumanInputResponseValidationError extends Error { readonly code: "INVALID_RESPONSE" | "SKIP_NOT_ALLOWED" | "HUMAN_AUTH_REQUIRED"; readonly name = "HumanInputResponseValidationError"; constructor(code: "INVALID_RESPONSE" | "SKIP_NOT_ALLOWED" | "HUMAN_AUTH_REQUIRED", message: string); } export declare function getSessionHumanInputRequest(db: Database, workspaceId: string, sessionId: string, requestId: string): Promise; export declare function listSessionHumanInputRequests(db: Database, workspaceId: string, sessionId: string, options?: { status?: SessionHumanInputRequest["status"]; limit?: number; }): Promise; /** * "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 declare function humanInputAgentMayDecide(request: Pick & Partial>): boolean; export declare function validateHumanInputResponse(request: Pick & Partial>, rawResponse: unknown, secretAnswerQuestionIds?: ReadonlySet): HumanInputResponse; 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"; }; /** 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; }; /** * 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 declare function listTurnApprovalDecisions(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; throughSequence: number; }): Promise; /** * 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 declare 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; export declare function expireSessionHumanInputRequest(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; requestId: string; }): Promise; export declare function getHumanInputResumeForEvent(db: Database, workspaceId: string, sessionId: string, event: Pick): Promise<{ requestId: string; toolCallId: string; response: HumanInputResponse; } | null>; export declare class SessionBackgroundCommandAdoptionFencedError extends Error { readonly reason: TurnAttemptFenceRejectReason; readonly name = "SessionBackgroundCommandAdoptionFencedError"; constructor(reason: TurnAttemptFenceRejectReason); } /** 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 declare 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; }): Promise<{ id: string; workspaceId: string; sessionId: string; provider: "connected_machine" | "managed"; state: "exited" | "lost" | "running" | "stopping"; observationStatus?: "unavailable" | undefined; reconciliation?: { lastOutcome: string | null; attempts: number; dueAt: string; claimedAt: string | null; terminalProof: { outcome: "exited"; exitCode: number; observedAt: string; } | { outcome: "lost"; exitCode: null; observedAt: string; } | null; } | undefined; commandPreview: string; commandText?: string | undefined; cancelRequestedAt: string | null; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; } | undefined; backgroundChildrenStopped?: true | undefined; startedAt: string; settledAt: string | null; completionObservedAt?: string | null | undefined; updatedAt: string; }>; /** 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 declare function recordAbandonedDirectConnectedMachineCommand(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; command: string; }): Promise<{ id: string; workspaceId: string; sessionId: string; provider: "connected_machine" | "managed"; state: "exited" | "lost" | "running" | "stopping"; observationStatus?: "unavailable" | undefined; reconciliation?: { lastOutcome: string | null; attempts: number; dueAt: string; claimedAt: string | null; terminalProof: { outcome: "exited"; exitCode: number; observedAt: string; } | { outcome: "lost"; exitCode: null; observedAt: string; } | null; } | undefined; commandPreview: string; commandText?: string | undefined; cancelRequestedAt: string | null; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; } | undefined; backgroundChildrenStopped?: true | undefined; startedAt: string; settledAt: string | null; completionObservedAt?: string | null | undefined; updatedAt: string; }>; /** 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 declare function adoptManagedSessionBackgroundCommand(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; processId: string; expected: SandboxRetainedProcessIdentity; command: string; }): Promise<{ id: string; workspaceId: string; sessionId: string; provider: "connected_machine" | "managed"; state: "exited" | "lost" | "running" | "stopping"; observationStatus?: "unavailable" | undefined; reconciliation?: { lastOutcome: string | null; attempts: number; dueAt: string; claimedAt: string | null; terminalProof: { outcome: "exited"; exitCode: number; observedAt: string; } | { outcome: "lost"; exitCode: null; observedAt: string; } | null; } | undefined; commandPreview: string; commandText?: string | undefined; cancelRequestedAt: string | null; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; } | undefined; backgroundChildrenStopped?: true | undefined; startedAt: string; settledAt: string | null; completionObservedAt?: string | null | undefined; updatedAt: string; }>; /** 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 declare function recoverManagedSessionBackgroundCommand(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; reconciliationClaimId: string; }): Promise<{ id: string; workspaceId: string; sessionId: string; provider: "connected_machine" | "managed"; observationStatus?: "unavailable" | undefined; reconciliation?: { lastOutcome: string | null; attempts: number; dueAt: string; claimedAt: string | null; terminalProof: { outcome: "exited"; exitCode: number; observedAt: string; } | { outcome: "lost"; exitCode: null; observedAt: string; } | null; } | undefined; commandPreview: string; commandText?: string | undefined; cancelRequestedAt: string | null; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; } | undefined; backgroundChildrenStopped?: true | undefined; startedAt: string; settledAt: string | null; completionObservedAt?: string | null | undefined; updatedAt: string; state: "exited" | "lost" | "running" | "stopping"; } | null>; 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 declare function installOrReadTurnExecutionPolicyForAttempt(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; policyForAbsent: TurnExecutionPolicyV1; }): Promise; /** Persist the current catalog once per logical turn; retries reuse its exact snapshot. */ export declare 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; /** * 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 declare function ensureSessionRepositorySkills(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; index: string | null; }): Promise; /** * 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 declare function ensureSessionWorkspaceGovernance(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; governance: string | null; }): Promise; /** * 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 declare function ensureSessionWorkspaceFilesystem(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; layout: string | null; }): Promise; /** * 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 organization agent version for every attempt of a turn. */ export declare const ORG_AGENT_VERSION_METADATA_KEY = "opengeniOrgAgentVersion"; /** * 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 declare function readSessionOrgAgentVersion(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turn?: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; }; }): Promise<{ agentId: string; version: number; } | null>; /** * 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 declare function readSessionAgentPrompt(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turn?: { turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; }; }): Promise; /** * 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 declare function ensureSessionAgentInstructions(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; prompt: SessionAgentPrompt; }): Promise; /** Install an effort update before accepted input, or at the maintenance tail, under the attempt fence. */ export declare function ensureSessionReasoningConfiguration(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; effort: ConfigurationEffort; }): Promise; /** * 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 declare 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; /** Append under an existing exact-attempt fence; acknowledge the footprint only after commit. */ export declare function appendSessionHistoryItemsInTransaction(tx: Database, input: Omit[1], "onAppendedFootprint">, allowed: Extract): Promise; export type PendingSessionToolCallInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; callId: string; callType: string; callItem: Record; modelToolOutputTruncationTokens?: number; }; /** * 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 declare function registerPendingSessionToolCallInTransaction(tx: Database, input: PendingSessionToolCallInput, fence: Extract): Promise<{ accepted: boolean; registered: boolean; }>; /** Root-handle entry point: each rollback retry starts a fresh fenced transaction. */ export declare function registerPendingSessionToolCall(db: Database, input: PendingSessionToolCallInput): Promise<{ accepted: boolean; registered: boolean; }>; /** Record the raw SDK result without dropping the call receipt. */ export declare 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; }>; /** Standalone recovery/test callers retain a fresh, exact-attempt transaction. */ export declare function recordPendingSessionToolCallResult(db: Database, input: Parameters[1]): Promise<{ accepted: boolean; recorded: boolean; }>; 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; }; /** * Bind unpaired interruption calls and their tied reasoning onto existing * pending receipts. Fail closed when any interruption call is missing. */ export declare 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; }>; /** Turn-scoped interruption suffix rows, including already-settled members. */ export declare function listTurnOpenSuffixToolCalls(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; /** * 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 declare function turnHasPendingToolCalls(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; /** * 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 declare function listRecordedInteractionToolCallIds(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; toolCallIds: string[]; }): Promise>; /** * 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 declare function replacePendingToolCallMcpInputRequest(db: Database, input: Omit & { callId: string; mcpInputRequest: Record; }): Promise<{ accepted: boolean; }>; /** * 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 declare function clearDurablePendingSessionToolCallsInTransaction(tx: Database, input: Omit & { callIds: string[]; }, fence: Extract): Promise<{ accepted: boolean; cleared: number; }>; export declare function clearDurablePendingSessionToolCalls(db: Database, input: Parameters[1]): Promise<{ accepted: boolean; cleared: number; }>; export declare function getSessionHistoryItems(db: Database, workspaceId: string, sessionId: string): Promise; }>>; /** * 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 declare function getActiveSessionHistoryItems(db: Database, workspaceId: string, sessionId: string): Promise; providerArtifactInvalidatedAt: Date | null; }>>; /** Bounded finalized voice turns used only to resume a later realtime call. */ export declare function getSessionRealtimeContinuityEntries(db: Database, workspaceId: string, sessionId: string, maximumEntries?: number): Promise; /** * 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 declare function countActiveSessionHistoryItems(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function orphanedResultRowIndicesForRepair(activeRowsInPositionOrder: ReadonlyArray<{ item: Record; }>): number[]; export type ApplyContextCompactionResult = { applied: true; supersededFrom: number; summaryPosition: number; events: SessionEvent[]; } | { applied: false; reason: TurnAttemptFenceRejectReason; }; /** * 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 declare 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; /** * 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 declare 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"; }>; /** * 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 declare 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"; }>; /** * 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 declare function hasPendingSteerForTurn(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise; /** * 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 declare function hasPendingSteerAfterContextCompaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; }): Promise; /** * 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 declare function nextSessionHistoryPosition(db: Database, workspaceId: string, sessionId: string): Promise; /** Persist socket refusal before HTTP dispatch, under the current attempt fence. * Every recovery path and worker replacement then inherits the same turn policy. */ export declare function markSessionTurnModelTransportHttpOnly(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; attemptId: string; }): Promise; /** * 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 declare function setSessionLastInputTokensForTurnAttempt(db: Database, input: { workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; lastInputTokens: number | null; }): Promise; /** The caller owns the exact session/turn/attempt locks through commit. */ export declare function setSessionLastInputTokensInTransaction(tx: Database, fence: Extract, lastInputTokens: number | null): Promise; /** The neutral boundary left as the sole active history row after a clear. */ export declare function clearedContextMarkerItem(): Record; export type ClearSessionContextResult = { /** Active history rows superseded (active=true -> false). */ supersededItems: number; /** Position of the inserted neutral boundary marker. */ markerPosition: number; }; export declare class SessionContextBusyError extends Error { readonly status: string; constructor(status: string); } /** * 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 declare function clearSessionContext(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; }): Promise; export declare function countSessionHistoryItems(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function requestSessionCompaction(db: Database, workspaceId: string, sessionId: string): Promise<{ wakeRevision: number; temporalWorkflowId: string; }>; 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 declare function requestIdleSessionCompactionIfDue(db: Database, input: { workspaceId: string; sessionId: string; thresholdTokens: number; }): Promise; /** 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 declare function sessionCompactionRequestTrigger(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function convertSessionToPortableCompactionForModelSwitch(db: Database, workspaceId: string, sessionId: string, attempt?: { turnId: string; executionGeneration: number; attemptId: string; }): Promise<{ codexCompactionMode: "remote_v2" | "portable"; compactRequested: boolean; } | null | "fenced">; /** 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 declare function isSessionCompactionRequested(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function upsertSandboxSessionEnvelope(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; envelope: Record; }): Promise; export declare function getSandboxSessionEnvelope(db: Database, workspaceId: string, sessionId: string): Promise | null>; 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; }; export declare 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; export declare 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; /** * 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 declare function deleteRecording(db: Database, input: { accountId: string; workspaceId: string; recordingId: string; }): Promise; /** * 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 declare 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; export declare function getSessionRecording(db: Database, workspaceId: string, recordingId: string): Promise; export declare function listSessionRecordings(db: Database, workspaceId: string, sessionId: string): Promise; 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 & SandboxPtyProcessIdentity & { status: "open"; }; export declare 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; /** Read an OPEN PTY row by ptyId. Returns null when absent or already closed. */ export declare function getOpenPtySession(db: Database, input: { workspaceId: string; sessionId: string; ptyId: string; }): Promise; /** Refresh activity/geometry only when the full retained-process identity still * matches. A numeric provider locator or PTY UUID alone is never authority. */ export declare function updatePtySessionActivity(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; ptyId: string; identity: SandboxPtyProcessIdentity; cols?: number; rows?: number; }): Promise; /** Mark a PTY closed (idempotent — a double close on a closed row is a no-op). */ export declare function closePtySession(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; ptyId: string; identity: SandboxPtyProcessIdentity; }): Promise; /** List a session's OPEN PTYs (reattach + reap). */ export declare function listOpenPtySessions(db: Database, workspaceId: string, sessionId: string): Promise; 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; }; 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; image: string | null; rigVersionId: string | null; dataPlaneUrl: string | null; 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; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; subjectId?: string | null; /** 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; /** 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; 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; rigVersionId?: string | null; leaseTtlMs: number; warmingLeaseTtlMs?: number; 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 = { role: "spawner"; lease: LeaseSnapshot; sandboxPlanTier?: string; sandboxPaidHistory?: true; } | { role: "attached"; lease: LeaseSnapshot; sandboxPlanTier?: string; sandboxPaidHistory?: true; } | { role: "rearmed"; lease: LeaseSnapshot; } | { role: "blocked"; code: "restore_degraded" | "restore_unrecoverable"; lease: LeaseSnapshot; } | { role: "fenced"; reason: "superseded" | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress" | "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; }; /** * 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 declare function claimSandboxSharedPreparation(db: Database, input: ClaimSandboxSharedPreparationInput): Promise; export declare function readSandboxSharedPreparation(db: Database, input: Omit): Promise<{ status: "available"; preparation: SandboxSharedPreparationSnapshot; } | { status: "fenced"; }>; export declare function settleSandboxSharedPreparation(db: Database, input: Omit & { outcome: "completed" | "failed"; }): Promise; export declare class SandboxLeaseSupersededError extends Error { readonly sandboxGroupId: string; readonly leaseEpoch: number; readonly diagnostic?: { backend: string; instanceId: string | null; liveness: SandboxLeaseLiveness; } | undefined; constructor(sandboxGroupId: string, leaseEpoch: number, diagnostic?: { backend: string; instanceId: string | null; liveness: SandboxLeaseLiveness; } | undefined); } export declare class SandboxLeaseTransitionError extends Error { readonly sandboxGroupId: string; readonly leaseEpoch: number; readonly reason: "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress" | "organization_sandbox_capacity"; readonly backend: string; readonly instanceId: string | null; readonly liveness: SandboxLeaseLiveness; /** organization_sandbox_capacity only: the plan's running-box limit. */ readonly organizationBoxLimit?: number | undefined; readonly name = "SandboxLeaseTransitionError"; constructor(sandboxGroupId: string, leaseEpoch: number, reason: "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress" | "organization_sandbox_capacity", backend: string, instanceId: string | null, liveness: SandboxLeaseLiveness, /** organization_sandbox_capacity only: the plan's running-box limit. */ organizationBoxLimit?: number | undefined); } export type SandboxViewerForceDrainReason = "balance" | "warm_cap"; export declare class SandboxViewerAdmissionBlockedError extends Error { readonly workspaceId: string; readonly sandboxGroupId: string; readonly reason: SandboxViewerForceDrainReason | "viewer_idle"; readonly name = "SandboxViewerAdmissionBlockedError"; constructor(workspaceId: string, sandboxGroupId: string, reason: SandboxViewerForceDrainReason | "viewer_idle"); } /** * 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 declare class SandboxViewerBoxLimitError extends Error { readonly workspaceId: string; readonly sandboxGroupId: string; readonly limit: number; readonly scope: SandboxViewerBoxLimitScope; readonly name = "SandboxViewerBoxLimitError"; constructor(workspaceId: string, sandboxGroupId: string, limit: number, scope?: SandboxViewerBoxLimitScope); } /** * 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 declare const SANDBOX_FLEET_REFUSAL_REASONS: readonly SandboxOrganizationBoxLimitReason[]; /** The person-facing explanation of a SandboxOrganizationBoxLimitError. */ export declare function sandboxOrganizationBoxLimitMessage(reason: SandboxOrganizationBoxLimitReason, limit: number): string; /** * 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 declare class SandboxOrganizationBoxLimitError extends Error { readonly workspaceId: string; readonly sandboxGroupId: string; readonly limit: number; readonly reason: SandboxOrganizationBoxLimitReason; 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(workspaceId: string, sandboxGroupId: string, limit: number, reason?: SandboxOrganizationBoxLimitReason); } /** 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; /** What a suspended organization is told when a cost path refuses it. */ export declare 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."; /** Forget cached suspensions (tests). */ export declare function resetOrganizationSuspensionCache(): void; /** * 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 declare function resolveOrganizationSuspension(db: Database, input: { accountId: string; subjectId?: string | null; }): Promise; /** Metered box seconds of one organization since the start of the UTC day * (maintenance callers). */ export declare function readOrganizationBoxSecondsToday(db: Database, accountId: string): Promise; /** * 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 declare 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; /** Forget cached person standings (tests). */ export declare function resetSandboxPersonStandingCache(): void; /** The organization-wide count definer (1475, granted by 1479). */ export declare 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 declare 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 declare function sandboxPlanTierExemptFromViewerOnlyBounds(tier: string): boolean; /** The tier of a young Free self-serve organization, while the * `new` tier sets `organizationsYoungerThanMs`. */ export declare 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 declare const SELF_SERVE_ACCOUNT_SOURCES: readonly string[]; /** * 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 declare function resolveSandboxPlanTier(tx: Database, accountId: string, limits?: SandboxPlanLimits, options?: { linkedRestricted?: boolean; }): Promise; /** 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; }; /** Forget cached purchase facts (tests). */ export declare function resetOrganizationPurchasedCreditCache(): void; export declare function resolveSandboxPlanStanding(tx: Database, accountId: string, limits?: SandboxPlanLimits, options?: { linkedRestricted?: boolean; }): Promise; export declare function sandboxPlanLimitFor(limits: SandboxPlanLimits, tier: string): SandboxPlanLimit; /** resolveSandboxPlanTier for maintenance callers, in the RLS context of one * of the organization's workspaces. */ export declare function resolveSandboxPlanTierInWorkspace(db: Database, input: { accountId: string; workspaceId: string; limits?: SandboxPlanLimits; }): Promise; /** resolveSandboxPlanStanding for maintenance callers, in the RLS context of * one of the organization's workspaces. */ export declare function resolveSandboxPlanStandingInWorkspace(db: Database, input: { accountId: string; workspaceId: string; limits?: SandboxPlanLimits; }): Promise; export declare class SandboxPaidComputeAdmissionError extends Error { readonly workspaceId: string; readonly sandboxGroupId: string; readonly name = "SandboxPaidComputeAdmissionError"; constructor(workspaceId: string, sandboxGroupId: string, message?: string); } export declare class SandboxDebitAttributionUnavailableError extends SandboxPaidComputeAdmissionError { readonly code = "credit_debit_attribution_unavailable"; constructor(workspaceId: string, sandboxGroupId: string); } /** * 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 declare function markWarmBillingStopCutoff(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; }): Promise; export declare class SandboxLeaseRecoveryBlockedError extends Error { readonly sandboxGroupId: string; readonly leaseEpoch: number; readonly code: "restore_degraded" | "restore_unrecoverable"; readonly recovery: SandboxRecoveryState; readonly name = "SandboxLeaseRecoveryBlockedError"; constructor(sandboxGroupId: string, leaseEpoch: number, code: "restore_degraded" | "restore_unrecoverable", recovery: SandboxRecoveryState); } export declare class SandboxBackendConflictError extends Error { readonly sandboxGroupId: string; readonly actualBackend: string; readonly requestedBackend: string; readonly name = "SandboxBackendConflictError"; constructor(sandboxGroupId: string, actualBackend: string, requestedBackend: string); } export declare class SandboxImageConflictError extends Error { readonly sandboxGroupId: string; readonly currentImage: string; readonly requestedImage: string; constructor(sandboxGroupId: string, currentImage: string, requestedImage: string); } export declare class SandboxRigConflictError extends Error { readonly sandboxGroupId: string; readonly currentRigVersionId: string; readonly requestedRigVersionId: string; constructor(sandboxGroupId: string, currentRigVersionId: string, requestedRigVersionId: string); } /** 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 declare function leaseMayHaveUntrackedWriters(lease: Pick & Partial>): boolean; export type SandboxDrainCaptureFailures = { count: number; firstFailedAt: Date | null; lastFailedAt: Date | null; }; /** * 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 declare function organizationHasAnyTurn(db: Database, accountId: string): Promise; /** Metered box seconds of one organization since `since`. */ export declare function organizationBoxSecondsSince(db: Database, accountId: string, since: Date): Promise; export declare function acquireLease(db: Database, request: AcquireLeaseInput): Promise; 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; }; export declare 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 declare function sessionEffectiveSandboxRecoveryBlocked(tx: Database, session: typeof schema.sessions.$inferSelect): Promise; 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; }; /** Authorized caller only; provider-free and mutation-free (transaction scope only). */ export declare function readPublicSandboxRecovery(db: Database, input: PublicRecoveryScope): Promise; /** 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 declare function consentPublicSandboxRecovery(db: Database, input: PublicRecoveryScope & { request: SandboxRecoveryRequest; }): Promise; type WorkspaceRecoveryRequest = Extract; /** Operator-controlled database access is the authority boundary. Shares the * exact human recovery transaction and never edits archive bytes/generations. */ export declare function readSandboxWorkspaceRecoveryAsOperator(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; }): Promise; export declare function recoverSandboxWorkspaceAsOperator(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; request: WorkspaceRecoveryRequest; }): Promise; 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; }; /** 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 declare function authorizeAutomaticSandboxCheckpointRecovery(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; }): Promise; /** 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 declare function sessionHoldsFreshWorkspaceRecovery(db: Database, workspaceId: string, sessionId: string): Promise; /** These warnings are outside compactable history and survive ordinary context * reconstruction. Receipts describe decisions, never unverified restore success. */ export declare function getSandboxRecoveryDiscontinuity(db: Database, workspaceId: string, sessionId: string, projection?: "all" | "legacy_instructions" | "explicit_notice"): Promise; /** 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 declare 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; }>; /** 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 declare 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; export declare function markSandboxRestoreVerifying(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; rematerializationId: string; }): Promise<{ wrote: boolean; }>; export declare 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; }>; export declare function markSandboxProviderReady(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; }): Promise<{ wrote: boolean; lease: LeaseSnapshot | null; }>; export declare function commitWarmingToWarm(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; instanceId: string; dataPlaneUrl?: string | null; 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"; }>; /** * 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 declare function deliverPendingSandboxRestoreNotice(db: Database, input: { accountId: string; workspaceId: string; } & ({ sandboxGroupId: string; sessionId?: undefined; } | { sessionId: string; sandboxGroupId?: undefined; })): Promise; /** 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 declare 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; export declare function listPendingModalProviderCreates(db: Database): Promise>; /** Throttle positive discovery without extending the warming lease or changing * its create authority. Old unresolved rows rotate behind the next batch. */ export declare function claimModalProviderCreateRecovery(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; }): Promise; /** 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 declare const MODAL_PROVIDER_CREATE_SETTLE_AFTER_MS: number; export declare function modalProviderCreateOutlivedProvider(attempt: Pick, nowMs?: number): boolean; /** 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 declare function settleExpiredModalProviderCreate(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; attempt: SandboxProviderCreateAttempt; }): Promise; /** Attribute a positively identified late receipt, preserving expiry and every * checkpoint. Ordinary holder/epoch-fenced draining owns all physical cleanup. */ export declare function recordRecoveredModalProviderCreate(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; attempt: SandboxProviderCreateAttempt; instanceId: string; }): Promise; export declare 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; }>; 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; }; /** * 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 declare function previewColdLostLeaseInstanceBlockers(db: Database, input: PreviewColdLostLeaseInstanceBlockersInput): Promise; 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; }; /** * 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 declare 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; 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 declare 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; 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 declare function listEndedEpochWorkspaceBlockers(db: Database, input: { limit: number; }): Promise; 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 declare function listEndedEpochSandboxSetupUncertainties(db: Database, input: { limit: number; }): Promise; /** * 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 declare function settleEndedEpochWorkspaceBlockers(db: Database, tuple: EndedEpochBlockerTuple): Promise; export declare 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; /** * 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 declare function endComputeGroupOfArchivedChats(db: Database, input: { workspaceId: string; sandboxGroupId: string; }, bound?: DatabaseWorkBound): Promise; export type ColdSandboxOfArchivedChats = { accountId: string; workspaceId: string; sandboxGroupId: string; }; /** * 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 declare function listColdSandboxesOfArchivedChats(db: Database, input: { after?: { workspaceId: string; sandboxGroupId: string; } | null; limit: number; }): Promise; /** * 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 declare function forgetColdSandboxOfArchivedChats(db: Database, input: ColdSandboxOfArchivedChats): Promise; export declare 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>; /** 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 declare function normalizeViewerInteractionAgeMs(value: unknown): number | null; 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_allowance_exhausted"; }; export declare 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; export declare 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; 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 declare function reinstateTurnLeaseHolder(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; sessionId: string; attemptId: string; expectedEpoch: number; expectedInstanceId: string; leaseTtlMs: number; }): Promise; /** * 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 declare function touchLeaseHolder(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; kind: LeaseHolderKind; holderId: string; }): Promise; export interface ReapDrainable { workspaceId: string; sandboxGroupId: string; instanceId: string | null; leaseEpoch: number; } export declare function reapStaleLeaseHolders(db: Database, input: { workspaceId: string; viewerHolderTtlMs: number; /** 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; }): Promise<{ reapedViewers: number; reapedDirect: number; reapedTurns: number; reapedInteractions: number; warmingReset: number; drained: ReapDrainable[]; }>; /** 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 declare const IDLE_COMMAND_CONTAINMENT_REASON = "idle_containment"; export declare const DEADLINE_COMMAND_CONTAINMENT_REASON = "provider_deadline_containment"; export declare const QUIESCENCE_COMMAND_CONTAINMENT_REASON = "quiescence_containment"; type SettledCommandOwner = { sessionId: string; attemptId: string; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; }; /** 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"; }; /** 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 declare const COMMAND_CONTAINMENT_TURN_STARTING_UPDATE_KINDS: { always: ("agent_message" | "agent_steer_instruction" | "background_command_result" | "capability_setup_completed" | "goal_continuation" | "media_generation_result" | "scheduled_occurrence" | "secret_use_approval_decided" | "session_wait_timeout")[]; withActiveGoal: ("child_paused" | "child_progress" | "child_requires_action" | "child_requires_action_resolved" | "child_terminal_result" | "child_waiting_capacity")[]; }; /** * 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 declare 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; /** 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 declare const IDLE_INTERACTION_RELEASED = "idle_released"; /** A browser or desktop on a compute sandbox whose chat or workspace was deleted. */ export declare const COMPUTE_GROUP_ENDED = "sandbox_deleted"; /** 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 declare function listAgentHeldBrowserSessions(db: Database, input: { limit: number; }): Promise; /** * 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 declare 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; 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 declare function listIdleCheckpointCandidates(db: Database, input: { limit: number; intervalMs: number; }): Promise; /** 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 declare function recordIdleCheckpointAttempt(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; }): Promise; export declare 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; export interface MeterableWarmLease { accountId: string; workspaceId: string; sandboxGroupId: string; leaseEpoch: number; backend: string; } export declare function listMeterableWarmLeases(db: Database): Promise; /** Workspaces whose durable viewer-drain admission intent must be reevaluated * even after every affected sandbox lease has become cold. */ export declare function listSandboxViewerForceDrainWorkspaceIds(db: Database): Promise; export declare function countQueuedTurns(db: Database): Promise; export type SessionRecoveryBacklogState = "quiescence_missing" | "projection_stale"; export declare function countSessionRecoveryBacklog(db: Database): Promise>; 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 declare function summarizeSessionRecoveryBacklog(db: Database): Promise>; /** What currently holds a durable queued turn, from its session's own state. */ export declare const QUEUED_TURN_HOLDS: readonly ["ready", "behind_active_turn", "paused", "failed", "requires_action", "waiting_capacity", "cancelled"]; 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 declare function summarizeQueuedTurnsByHold(db: Database): Promise>; /** * 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 declare const CAPACITY_WAITING_TURN_PROVIDERS: readonly ["claude", "codex", "xai"]; 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; }; /** * 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 declare function summarizeTurnHolds(db: Database): Promise<{ queued: Record; capacityWaiting: Record; }>; /** The parked-turn half of {@link summarizeTurnHolds}. */ export declare function summarizeCapacityWaitingTurns(db: Database): Promise>; 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 declare function getContextCompactionPendingSummary(db: Database): Promise; export declare function countSandboxLeasesByLiveness(db: Database): Promise>; export type CreditBalanceByAccount = { accountId: string; balanceMicros: number; }; export declare function listCreditBalancesByAccount(db: Database): Promise; export declare function listLiveModalSandboxLeaseAttributions(db: Database): Promise; export declare function reArmDrainingLease(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; leaseTtlMs: number; warmBilling?: AcquireLeaseInput["warmBilling"]; }): Promise<{ rearmed: boolean; }>; export declare 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[]; }; }>; export declare class SandboxWorkspaceMutationFencedError extends Error { readonly code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" | "authority_unattributed" | "authority_revoked"; /** Remaining exact archive-capture budget projected by PostgreSQL. This is * observational wait input only; it never licenses capture takeover. */ readonly captureRemainingMs: number | null; readonly name: string; constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" | "authority_unattributed" | "authority_revoked", message: string, /** Remaining exact archive-capture budget projected by PostgreSQL. This is * observational wait input only; it never licenses capture takeover. */ captureRemainingMs?: number | null); } /** 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 declare class SandboxRetainedProcessTerminalError extends SandboxWorkspaceMutationFencedError { readonly state: "exited" | "lost"; readonly exitCode: number | null; readonly name = "SandboxRetainedProcessTerminalError"; constructor(state: "exited" | "lost", exitCode: number | null); } 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 declare 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); matchesPhysicalSettlement(input: { accountId: string; workspaceId: string; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }): boolean; } 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; 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 declare function retainedProcessSettlementIdentity(process: SandboxRetainedProcess): SandboxRetainedProcessIdentity; export declare function retainedProcessReconciliationProof(process: SandboxRetainedProcess): RetainedProcessProviderProof | 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 declare class SandboxRetainedProcessPromotionFencedError extends SandboxWorkspaceMutationFencedError { readonly process: SandboxRetainedProcess; readonly name = "SandboxRetainedProcessPromotionFencedError"; constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "route_fenced" | "process_fenced" | "admission_fenced" | "authority_unattributed" | "authority_revoked", message: string, process: SandboxRetainedProcess); } /** * 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 declare 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; /** 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 declare 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; /** 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 declare function advanceWorkspaceGenerationForRetainedProcess(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; operation: string; captureWaitMs?: number; waitSignal?: AbortSignal; }): Promise; /** 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 declare 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; export declare 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; export declare function verifyRetainedProcessMutationSettlement(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; admission: SandboxWorkspaceMutationAdmission; operation: string; outcome: SandboxWorkspaceMutationProviderOutcome; }): Promise; /** 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 declare 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; /** 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 declare function getRetainedProcess(db: Database, input: { workspaceId: string; sessionId: string; processId: string; }): Promise; /** 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 declare 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; /** 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 declare 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 declare function claimTerminalRetainedProcesses(db: Database, input: { claimId: string; limit: number; claimTtlMs: number; }): Promise; /** * 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 declare function bindRetainedProcessProviderIdentity(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; providerBindingKey: string; providerBinding: ModalCheckpointProviderBinding; }): Promise; /** 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 declare function recordRetainedProcessReconciliationProof(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; proof: RetainedProcessProviderProof; }): Promise; /** 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 declare function deferRetainedProcessReconciliation(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; processId: string; expected: SandboxRetainedProcessIdentity; claimId: string; outcome: string; retryAfterMs: number; }): Promise; export declare function countActiveRetainedProcessesByOwnerState(db: Database): Promise; export declare function countExpiredDrainingSandboxLeases(db: Database): Promise; /** 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 declare 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[]; }>; /** 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 declare function rejectRetainedSupervisedLaunch(db: Database, scope: { accountId: string; workspaceId: string; sessionId: string; processId: string; }, command: ModalRouterProviderCommand): Promise; /** Compose the leaf cursor/proof persistence with canonical settlement. The * leaf subpath cannot import this root without reversing the DB boundary. */ export declare function retainedProviderCommandPersistence(...[db, scope, publish]: Parameters): { recordSupervisionReceipt: (receipt: import("./retained-provider-commands.js").SupervisionReceipt) => Promise; loadSupervisionReceipt: () => Promise<{ protocol: "native-subreaper-v1"; invocationId: string; receiptId: string; leaderExitCode: number; } | null>; requestCancellation: (reason: "provider_deadline" | "explicit_stop") => Promise; cancellationRequested: () => Promise; load: () => Promise<{ kind: "modal-router-v1"; sandboxId: string; taskId: string; execId: string; pty?: boolean | undefined; supervision?: { protocol: "native-subreaper-v1"; invocationId: string; nonce: string; controlPath: string; } | undefined; streams: { stdout: { byteOffset: number; utf8Remainder: string; eof: boolean; exitCode: number | null; }; stderr: { byteOffset: number; utf8Remainder: string; eof: boolean; exitCode: number | null; }; }; } | null>; reserveInput: (byteLength: number) => Promise; captureRouterPage: (page: import("./retained-provider-commands.js").RetainedRouterOutputPage) => Promise<{ command: { kind: "modal-router-v1"; sandboxId: string; taskId: string; execId: string; pty?: boolean | undefined; supervision?: { protocol: "native-subreaper-v1"; invocationId: string; nonce: string; controlPath: string; } | undefined; streams: { stdout: { byteOffset: number; utf8Remainder: string; eof: boolean; exitCode: number | null; }; stderr: { byteOffset: number; utf8Remainder: string; eof: boolean; exitCode: number | null; }; }; }; captured: boolean; }>; rejectSupervisedLaunch: (command: ModalRouterProviderCommand) => Promise; }; /** 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 declare 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>; export declare const SANDBOX_REAPER_HOLD_MAX_TTL_MS: number; /** 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 declare function readSandboxLeaseReaperHoldTarget(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; }): Promise; 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 declare 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; /** Release only the exact operator receipt on the exact physical lease. */ export declare function releaseSandboxLeaseReaperHold(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; holdId: string; }): Promise; 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 declare function workspaceArchiveCaptureDeadlineElapsed(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; captureId: string; expectedEpoch: number; expectedInstanceId: string; }): Promise; 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" | "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 declare 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; /** Clear only the exact capture owner. A stale callback cannot release a * successor claim or a replacement provider epoch. */ export declare 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; /** * 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 declare 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; export type SandboxCheckpointArtifactState = "candidate" | "current" | "previous" | "delete_pending" | "deleting" | "delete_failed" | "deleted"; export type SandboxCheckpointArtifactRegistration = { id: string; state: SandboxCheckpointArtifactState; objectId: string; }; export declare class SandboxCheckpointArtifactRegistrationConflictError extends Error { readonly name = "SandboxCheckpointArtifactRegistrationConflictError"; } /** * 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 declare 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; /** Hand an unpublished candidate to asynchronous GC. Referenced artifacts are * protected both here and by the global claim function. */ export declare function markSandboxCheckpointArtifactDeletePending(db: Database, input: { accountId: string; workspaceId: string; artifactId: string; reason?: string; }): Promise; export type SandboxCheckpointArtifactGcClaim = { id: string; providerBackend: string; providerBindingKey: string; providerBinding: Record; objectKind: "modal_filesystem_snapshot" | "modal_directory_snapshot"; objectId: string; deleteAttempts: number; }; export declare function claimSandboxCheckpointArtifactsForGc(db: Database, input: { claimId: string; limit: number; claimTtlMs: number; }): Promise; export declare function settleSandboxCheckpointArtifactGc(db: Database, input: { artifactId: string; claimId: string; deleted: boolean; error?: string | null; retryAfterMs: number; }): Promise; export declare function pruneDeletedSandboxCheckpointArtifacts(db: Database, retentionMs: number, limit: number): Promise; export declare function requestDueSandboxRotationsGlobal(db: Database, leadMs: number, limit: number): Promise; export declare const SANDBOX_CHECKPOINT_ARTIFACT_STATES: readonly ["candidate", "current", "previous", "delete_pending", "deleting", "delete_failed", "deleted"]; export declare function countSandboxCheckpointArtifactsByState(db: Database): Promise>; export type SandboxRotationBacklog = { requested: number; overdue: number; turnBlocked: number; directBlocked: number; processBlocked: number; interactionBlocked: number; }; export declare function readSandboxRotationBacklog(db: Database): Promise; 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 declare function readSandboxCheckpointStaleness(db: Database): Promise; /** 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 declare function readRecentSandboxRecoveryObservations(db: Database): Promise<{ providerLosses: number; fallbackSelections: number; freshWorkspaceSelections: number; }>; 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 declare function listLegacyModalCheckpointSlots(db: Database, limit?: number): Promise; 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 declare function adoptLegacyModalCheckpointArtifact(db: Database, input: LegacyModalCheckpointAdoptionTarget): Promise; /** 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"; export declare 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; }>; /** * 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 declare function rotateWorkspaceArchives(input: { resumeState: Record | null; priorCurrentArchive: string | null; priorPreviousArchive: string | null; }): { previousArchive: string | null; previousArchiveMeta: SandboxArchiveRevision | null; previousArchiveRef: WorkspaceArchiveObjectRef | null; }; /** * 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 declare 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; }>; export declare function getMaterializedSandboxFileResources(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; instanceId: string; }): Promise>; export declare function markSandboxFileResourcesMaterialized(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; instanceId: string; fileIds: string[]; }): Promise<{ wrote: boolean; }>; 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[]; }; /** * 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 declare 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; /** * 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 declare 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; /** The newest capture for a session (highest revision), or null if none. */ export declare function latestWorkspaceCapture(db: Database, workspaceId: string, sessionId: string): Promise; 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 declare function sessionLatestWorkspaceCapture(db: Database, workspaceId: string, sessionId: string): Promise; /** 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 declare function workspaceCaptureAtRevision(db: Database, workspaceId: string, sessionId: string, revision: number): Promise; /** * 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 declare function computeWorkspaceCaptureGcPlan(rows: WorkspaceCaptureGcRow[], keepN: number): WorkspaceCaptureGcPlan; export declare function planWorkspaceCaptureGc(db: Database, input: { workspaceId: string; sessionId: string; keepN: number; }): Promise; /** Delete evicted capture rows by id (call AFTER their storage blobs are gone). */ export declare function deleteWorkspaceCaptureRows(db: Database, input: { workspaceId: string; rowIds: string[]; }): Promise; export declare function readLease(db: Database, workspaceId: string, sandboxGroupId: string): Promise; /** 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 declare function readSandboxReducedSave(db: Database, workspaceId: string, sessionId: string): Promise<{ capturedAt: string; omittedPaths: string[]; } | 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 declare function waitWhileLeaseWarming(db: Database, workspaceId: string, sandboxGroupId: string, options: { timeoutMs: number; pollMs: number; signal?: AbortSignal | undefined; }): Promise; export declare function recordLeaseDataPlaneUrl(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; dataPlaneUrl: string | null; }): Promise; export declare function recordLeaseTerminalDataPlaneUrl(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; terminalDataPlaneUrl: string | null; }): Promise; /** 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 declare function recordLeaseControllerDataPlaneUrl(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; expectedEpoch: number; expectedInstanceId: string; controllerDataPlaneUrl: string | null; }): Promise; 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; }; 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; }; export declare function createEnrollment(db: Database, input: { accountId: string; workspaceId: string; pubkey: string; exposure?: EnrollmentExposure; hasDisplay?: boolean; allowScreenControl?: boolean; os?: EnrollmentOs; arch?: string; }): Promise; export declare function getEnrollment(db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string; }, enrollmentId: string): Promise; /** 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 declare function getLiveEnrollmentConnection(db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string; }, enrollmentId: string): Promise; export declare 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; /** 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 declare 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; /** Preserve authorized machine metadata while its runner is offline. Admission * and liveness are separate: startup may bind the normal offline transport. */ export declare function resolvePersonalMachineRouteForAttempt(db: Database, input: Parameters[1]): Promise<{ enrollment: EnrollmentRecord; liveConnection: EnrollmentRecord | null; } | null>; export declare function authorizePersonalMachineForAttempt(db: Database, input: { accountId: string; workspaceId: string; subjectId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; enrollmentId: string; requireActiveSandbox?: boolean; }): Promise; /** 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 declare 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; /** 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 declare function updateOrganizationMachineReach(db: Database, enrollmentId: string, input: OrganizationComputeReachInput): Promise; export type EnrollmentConnectionClaim = { claimed: boolean; connectionInstanceId: string | null; connectionGeneration: number; connectionLeaseExpiresAt: string | null; }; /** * 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 declare function claimEnrollmentConnection(db: Database, input: { workspaceId: string; enrollmentId: string; credentialGeneration: number; connectionInstanceId: string; leaseMs: number; }): Promise; /** Renew only the exact active runner. Stale heartbeats never extend or steal a * successor's lease. */ export declare function renewEnrollmentConnection(db: Database, input: { accountId?: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; leaseMs: number; }): Promise<{ renewed: boolean; enrollment: EnrollmentRecord | null; }>; /** Release only the exact active runner. A late goodbye from a fenced process is * ignored and cannot mark its successor offline. */ export declare function releaseEnrollmentConnection(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; connectionInstanceId: string; reason: string; }): Promise<{ released: boolean; }>; export declare function listEnrollments(db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string; }, options?: { status?: EnrollmentStatus; }): Promise; 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 declare class MachineRemovalIdempotencyError extends Error { readonly name = "MachineRemovalIdempotencyError"; } export declare class MachineRemovalRevisionConflictError extends Error { readonly currentUpdatedAt: string; readonly name = "MachineRemovalRevisionConflictError"; constructor(message: string, currentUpdatedAt: string); } /** * 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 declare function removeEnrollment(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; operationKey: string; expectedUpdatedAt?: string; subjectId?: string | null; }): Promise; export declare function revokeEnrollment(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; }): Promise<{ revoked: boolean; }>; export declare function revokeEnrollmentByGeneration(db: Database, input: { workspaceId: string; enrollmentId: string; credentialGeneration: number; }): Promise<{ matched: boolean; revoked: boolean; }>; export declare function touchEnrollmentLastSeen(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; }): Promise; export declare function setEnrollmentWentOffline(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; reason: string; }): Promise; /** 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 declare function recordEnrollmentExpiredCredentials(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; credentialGeneration: number; }): Promise; export declare 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; }>; export declare 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; }>; /** The three macOS desktop permissions a Mac agent reports. */ export type EnrollmentMacPermissions = { screenRecording: boolean; accessibility: boolean; inputMonitoring: boolean; }; /** Runtime-capability keys under which a Mac's permission snapshot is stored. */ export declare function enrollmentMacPermissionCapabilities(permissions: EnrollmentMacPermissions): Record; /** The stored Mac permission snapshot, or null when the agent never reported one. */ export declare function enrollmentMacPermissions(capabilities: Record | null | undefined): EnrollmentMacPermissions | null; /** * 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 declare 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; }>; export declare 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; }>; /** 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 declare 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; }>; /** Atomically reserve the one process-global update slot on an exact live * runner generation. An in-flight operation is never overwritten. */ export declare 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; /** 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 declare 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; }>; 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; }; export declare 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; export declare function getDeviceEnrollmentRequestByDeviceCode(db: Database, deviceCode: string): Promise; export declare function getPendingDeviceEnrollmentRequestByUserCode(db: Database, workspaceId: string, userCode: string): Promise; export declare function getPendingDeviceEnrollmentRequestByUserCodeGlobal(db: Database, userCode: string): Promise; export declare class PersonalMachineConnectedElsewhereError extends Error { constructor(); } export declare class EnrollTokenAlreadyRedeemedError extends Error { constructor(); } export declare class EnrollTokenOwnerUnavailableError extends Error { constructor(options?: { cause?: unknown; }); } export declare 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; }>; export declare class SandboxEnrollmentConflictError extends Error { constructor(); } export declare function createSandboxEnrollment(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sandboxGroupId: string; hasDisplay: boolean; workspaceRoot: string; }): Promise; /** 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; }; /** * 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 declare function openSandboxAgentLink(db: Database, input: SandboxAgentLinkInput & { leaseMs: number; }): Promise<{ opened: true; connectionGeneration: number; superseded: boolean; } | { opened: false; code: SandboxAgentLinkRefusal; }>; /** * 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 declare function renewSandboxAgentLink(db: Database, input: SandboxAgentLinkInput & { leaseMs: number; }): Promise<{ renewed: true; } | { renewed: false; code: SandboxAgentLinkEnd; }>; /** 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 declare const COMPUTE_HAND_OFF_UNWAKEABLE_MS: number; /** 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 declare function computeHostHandingOff(lease: Pick | null, nowMs?: number): boolean; /** * 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 declare function recordComputeSandboxPower(db: Database, input: SandboxAgentLinkInput & { sandboxId: string; asleep: boolean; handingOff?: boolean; }): Promise<{ accepted: boolean; changed: boolean; }>; /** 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 declare function releaseSandboxAgentLink(db: Database, input: SandboxAgentLinkInput): Promise<{ released: boolean; }>; /** * 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 declare class DatabaseWorkDeadlineError extends Error { constructor(options?: { cause?: unknown; }); } export declare class DatabaseWorkOutcomeUnknownError extends Error { constructor(options?: { cause?: unknown; }); } export declare function revokeSandboxEnrollment(db: Database, input: { workspaceId: string; enrollmentId: string; now?: Date; }, bound?: DatabaseWorkBound): Promise<{ revoked: boolean; }>; /** * 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 declare function computeSandboxNamed(db: Database, input: { workspaceId: string; sandboxGroupId: string; enrollmentId: string; sandboxId: string; }, bound?: DatabaseWorkBound): Promise; /** * 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 declare function computeSandboxOfEnrollment(db: Database, input: { workspaceId: string; enrollmentId: string; }, bound?: DatabaseWorkBound): Promise; /** The most entries one page of the stale compute enrollment inventory holds. */ export declare 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 declare function listStaleComputeSandboxEnrollments(db: Database, after: string | undefined, bound?: DatabaseWorkBound): Promise<{ candidates: { workspaceId: string; enrollmentId: string; }[]; more: boolean; }>; /** * 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 declare function revokeStaleComputeSandboxEnrollment(db: Database, candidate: { workspaceId: string; enrollmentId: string; }, bound?: DatabaseWorkBound): Promise; export declare function approveDeviceEnrollmentRequest(db: Database, input: { accountId: string; workspaceId: string; scope?: EnrollmentRecord["scope"]; allowOrganization?: boolean; requestId: string; allowScreenControl: boolean; approvedBySubjectId: string; approvedBySubjectLabel?: string | null; sandboxName: string; now?: Date; }): Promise<{ approved: boolean; enrollment: EnrollmentRecord | null; sandbox: SandboxRecord | null; }>; export declare function denyDeviceEnrollmentRequest(db: Database, input: { accountId: string; workspaceId: string; requestId: string; }): Promise<{ denied: boolean; }>; export declare function consumeDeviceEnrollmentRequest(db: Database, input: { accountId: string; workspaceId: string; requestId: string; }): Promise<{ consumed: boolean; }>; export declare function createSandbox(db: Database, input: { accountId: string; workspaceId: string; kind: SandboxKind; name: string; enrollmentId?: string | null; }): Promise; export declare function getSandbox(db: Database, access: string | { accountId: string; workspaceId: string; subjectId: string; }, sandboxId: string): Promise; /** Exact-turn machine consent can expose one route without exposing the owner's * machine list or borrowing their authority for any other resource. */ export declare function getSandboxForAttempt(db: Database, input: { accountId: string; workspaceId: string; subjectId: string | null; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; }, sandboxId: string): Promise; export declare function listSandboxes(db: Database, workspaceId: string): Promise; export declare function sessionsWithActiveOpOnEnrollment(db: Database, input: { workspaceId: string; enrollmentId: string; }): Promise>; export declare function readActiveSandbox(db: Database, workspaceId: string, sessionId: string): Promise; 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; }; export declare function upsertMachineMetricsLatest(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sample: MachineMetricsSample; }): Promise; export declare function insertMachineMetricsSeries(db: Database, input: { accountId: string; workspaceId: string; enrollmentId: string; sample: MachineMetricsSample; }): Promise; export declare const MACHINE_METRICS_SERIES_INTERVAL_MS = 60000; /** * 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 declare 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; }>; 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; }; export declare function readMachineMetricsLatest(db: Database, workspaceId: string, enrollmentId: string): Promise; export declare function readMachineMetricsLatestForWorkspace(db: Database, workspaceId: string): Promise>; export declare function readMachineMetricsSeries(db: Database, input: { workspaceId: string; enrollmentId: string; since: Date; limit?: number; }): Promise; export interface StreamAcknowledgment { acknowledgedUnredacted: boolean; acknowledgedShared: boolean; } export declare function recordStreamAcknowledgment(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; subjectId: string; acknowledgeUnredacted: boolean; acknowledgeShared: boolean; }): Promise; export declare function getStreamAcknowledgment(db: Database, input: { workspaceId: string; sandboxGroupId: string; subjectId: string; }): Promise; export declare function listSessionIdsInGroup(db: Database, workspaceId: string, sandboxGroupId: string): Promise; /** * 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 declare function countAllSessionsInGroup(db: Database, workspaceId: string, sandboxGroupId: string): Promise; export declare function revokeViewer(db: Database, input: { accountId: string; workspaceId: string; sandboxGroupId: string; viewerId: string; idleGraceMs: number; }): Promise<{ liveness: SandboxLeaseLiveness; refcount: number; } | null>; 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 declare 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; 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; }[]; } export declare 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; export declare function saveRunState(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedExecutionGeneration: number; expectedAttemptId: string; serializedRunState: string; pendingApprovals: unknown[]; }): Promise; 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 declare function createSessionGoal(db: Database, input: CreateSessionGoalInput): Promise; export declare function getSessionGoal(db: Database, workspaceId: string, sessionId: string): Promise; /** 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 declare function getSessionMcpMonitoringSummary(db: Database, workspaceId: string, sessionId: string): Promise; 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 declare function getSessionGoalWithContinuation(db: Database, workspaceId: string, sessionId: string): Promise<(SessionGoal & { continuation: SessionGoalContinuationProjection; }) | null>; export declare function clearSessionGoal(db: Database, workspaceId: string, sessionId: string, options?: { actor: "api" | "agent"; }): Promise<{ cleared: boolean; goal: SessionGoal | null; event: SessionEvent | null; }>; /** * 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 declare function upsertSessionGoal(db: Database, input: CreateSessionGoalInput): Promise<{ goal: SessionGoal; replaced: boolean; }>; /** * 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 declare function upsertScheduledSessionGoalForRun(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; runId: string; text: string; successCriteria?: string | null; maxAutoContinuations?: number | null; mutationPolicy?: SessionGoalMutationPolicy; }): Promise; /** * 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 declare function upsertSessionGoalWithEvent(db: Database, input: CreateSessionGoalInput & { actor: "agent" | "api"; commandActor?: Extract; }): Promise<{ goal: SessionGoal; replaced: boolean; workflowWakeRevision: number | null; events: SessionEvent[]; }>; export declare function listSessionGoalRevisions(db: Database, workspaceId: string, sessionId: string): Promise; export declare function listSessionGoalRevisionPage(db: Database, workspaceId: string, sessionId: string, options?: { limit: number; before?: string; }): Promise<{ revisions: SessionGoalRevision[]; hasMore: boolean; nextCursor: string | null; }>; export declare function getSessionGoalRevision(db: Database, workspaceId: string, sessionId: string, revisionId: string): Promise; export declare function rejectSessionGoalRevisionWithEvent(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; revisionId: string; expectedObjectiveRevision: number; rationale: string; }): Promise<{ revision: SessionGoalRevision; events: SessionEvent[]; replay: boolean; }>; /** * 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 declare function updateSessionGoal(db: Database, workspaceId: string, sessionId: string, input: { text?: string; successCriteria?: string | null; mutationPolicy?: SessionGoalMutationPolicy; }): Promise; /** * 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 declare 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; }>; /** Maximum relative duration accepted by the session-level out-of-turn wait. */ export declare const SESSION_INPUT_WAIT_MIN_SECONDS = 30; export declare const SESSION_INPUT_WAIT_MAX_SECONDS: number; export declare const SESSION_INPUT_WAIT_REASON_MAX_BYTES: number; /** * 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 declare 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; }>; /** * 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 declare 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; }>; /** * 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 declare 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; }>; /** * 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 declare 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[]; }>; /** A stored avatar, or null for one this version cannot read. */ export declare function storedSessionAvatar(value: unknown): SessionAvatar | 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 declare function getSessionBotIdentity(db: Database, workspaceId: string, sessionId: string): Promise<{ title: string | null; avatar: SessionAvatar | null; } | null>; /** * 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 declare 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[]; }>; /** A stored link list, or empty when absent or unreadable. */ export declare function storedSessionLinks(value: unknown): SessionLink[]; /** The chat's Linked items, in the caller's RLS scope. Null when the chat is not visible. */ export declare function getSessionLinks(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare 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>; /** Read-only admission at a locked paused-to-active transition. */ export type SessionGoalResumeValidation = (tx: Database, session: Pick, 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 declare 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; }>; export type SetSessionGoalStatusEvent = { type: "goal.completed"; evidence: string; } | { type: "goal.paused"; actor: "agent" | "api"; reason: string; rationale?: string; } | { type: "goal.resumed"; actor: "api" | "agent"; }; /** Status mutation and its timeline fact share the same session-first commit. */ export declare 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[]; }>; export declare function setSessionGoalLastContinuationTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; 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; }; /** * 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 declare function evaluateGoalContinuation(db: Database, input: { workspaceId: string; sessionId: string; defaultMaxAutoContinuations?: number | null; budgetBlocked?: string | null; budgetPausedReason?: "limits" | GoalAdmissionPausedReason | undefined; }): Promise; export declare 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: []; } | { 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 declare 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; 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; }; /** * 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 declare function initializeSessionStartAtomically(db: Database, input: InitializeSessionStartInput): Promise; export declare function enqueueSessionTurn(db: Database, input: EnqueueSessionTurnInput): Promise; export type SessionWorkTrigger = { kind: "next"; } | { kind: "approval"; triggerEventId: string; }; export declare const MAX_INTERNAL_UPDATE_BYTES: number; export declare const MAX_INTERNAL_UPDATE_BATCH_MEMBERS = 100; export declare const MAX_INTERNAL_UPDATE_BATCH_BYTES: number; export type FrozenXaiExecutionAuthority = { snapshot: XaiProviderAccountAuthoritySnapshotV1; subjectId: string | null; }; 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; }) => 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"; }; /** * Bound legacy exact goal content only at the immutable model-context snapshot * boundary. The canonical goal/revision remains byte-for-byte unchanged. */ export declare function projectSessionGoalPromptField(value: string, maxBytes: number): string; /** Internal read receipt. Call only after the complete bounded response has been * constructed and the exact caller attempt's frozen human reauthorized. */ export declare function acknowledgeConsumedChildEvents(db: Database, input: { workspaceId: string; sessionId: string; subjectId: string | null; children: readonly { sessionId: string; sequences: readonly number[]; }[]; }): Promise; /** * 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 declare 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 declare const CODEMODE_CHILD_ANSWER_READS_METADATA_KEY = "codemodeChildAnswerReads"; /** * 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 declare 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; }>; /** * 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 declare function listOutstandingSessionSystemUpdatesForAttempt(db: Database, workspaceId: string, sessionId: string, attempt: { turnId: string; attemptId: string; }): Promise; /** 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 declare 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; }>; /** * 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 declare function claimSessionWorkForAttempt(db: Database, workspaceId: string, input: ClaimSessionWorkForAttemptInput): Promise; 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; }; export declare function commitSessionAttemptQuiescence(db: Database, input: MarkSessionAttemptQuiescedInput): Promise; /** 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 declare function markSessionAttemptQuiesced(db: Database, input: MarkSessionAttemptQuiescedInput): Promise; 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 declare function getSessionAttemptActivityRef(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; temporalWorkflowId: string; }): Promise; /** * 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 declare function reconcileSessionAttemptQuiescence(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; attemptId: string; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; activitySettled: boolean; workerProcessExitDeadlineMs?: number; }): Promise; /** * 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 declare function settleSessionAttemptInterruptions(db: Database, workspaceId: string, sessionId: string, attemptId: string): Promise; export { isSessionDefinitivelyDeleted } from "./session-deletion.js"; 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"; }; /** 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 declare function repairMissingQuiescenceReceiptWakes(db: Database, limit?: number, after?: QuiescenceReceiptWakeRepairCursor | null): Promise<{ examined: number; registered: number; failed: number; cursor: QuiescenceReceiptWakeRepairCursor | null; }>; export declare function peekSessionWork(db: Database, workspaceId: string, sessionId: string, includeAdmissionFence?: boolean, observerAccountId?: string): Promise; export type SettleSessionInputWaitResult = { action: "held"; events: []; workflowWakeRevision: number; } | { action: "timeout"; events: SessionEvent[]; workflowWakeRevision: number | null; } | { action: "superseded"; events: SessionEvent[]; } | { action: "stale"; events: []; }; export declare function settleSessionInputWait(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waitTurnId: string; disposition: "held" | "timeout" | "superseded"; }): Promise; /** Park only the exact pre-dispatch snapshot; late failures cannot block new work. */ export declare 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[]; }>; /** What changed that may fix a blocked chat's saved message. */ export type SessionAdmissionAccessChange = "personal_resource" | "membership" | "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 declare function releaseSessionAdmissionBlocksAfterAccessChange(db: Database, input: { accountId: string; workspaceId: string; change: SessionAdmissionAccessChange; sessionIds?: readonly string[]; }): Promise; 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 declare function failSessionWorkBeforeAttemptClaim(db: Database, workspaceId: string, input: FailSessionWorkBeforeAttemptClaimInput): Promise; /** Explicit operator maintenance, not normal admission and never a reaper * age heuristic. Exact manifest fences and physical quiescence are mandatory. */ export declare function retireInterruptedSessionTurn(db: Database, workspaceId: string, input: { accountId: string; sessionId: string; workflowId: string; } & InterruptedTurnRetirementProof): Promise; /** 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 declare function recordRetiredChildNotice(db: Database, workspaceId: string, input: { accountId: string; sessionId: string; } & InterruptedTurnRetirementProof): Promise; /** * 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 declare function recoverSessionWorkFailedBeforeAttemptClaim(db: Database, workspaceId: string, input: RecoverSessionWorkFailedBeforeAttemptClaimInput): Promise; /** * 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 declare function settleSessionIdleWithParentOutbox(db: Database, workspaceId: string, sessionId: string): Promise<{ action: "settled"; changed: boolean; episodeKey: string; notifyParent: boolean; events: SessionEvent[]; } | { action: "stale"; episodeKey: null; events: []; }>; export declare function setTemporalWorkflowId(db: Database, workspaceId: string, sessionId: string, workflowId: string): Promise; /** Version-one pre-dispatch setup recovery has exactly five automatic retries. */ export declare 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; }; /** 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"; }; /** 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 declare function reconcileCompletedSandboxSetup(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; terminatedBox?: TerminatedSandboxSetupBox; }): Promise<{ reconciled: boolean; events: SessionEvent[]; }>; export type SandboxLifecycleWait = { version: 1; sandboxGroupId: string; leaseEpoch: number; reason: "rotation_in_progress"; }; export type SessionTurnRecoveryRetry = { version: 1; notBefore: string; afterSequence: number; }; export declare function sessionTurnRecoveryRetryFromMetadata(metadata: Record | null | undefined): SessionTurnRecoveryRetry | null; /** Longest backoff a recovery may request; anything longer is a caller bug. */ export declare const SESSION_TURN_RECOVERY_RETRY_MAX_MS: number; 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; }; export type CanonicalTurnStartupMilestoneReceipt = { milestone: "queue" | "provider_dispatch" | "first_byte"; outcome: "completed" | "failed"; eventId: string; durationMs: number; }; /** * 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 declare function applySessionTurnSettlement(db: Database, workspaceId: string, input: ApplySessionTurnSettlementInput, hooks?: ApplySessionTurnSettlementHooks): Promise; 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 declare function readSessionTurnToolProgressRecoveryState(db: Database, workspaceId: string, input: { sessionId: string; turnId: string; }): Promise; /** The `sandbox.operation.*` name a worker records when it restarts a turn's * sandbox because the sandbox could no longer start programs. */ export declare 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 declare function countSessionTurnSandboxProcessStartRestarts(db: Database, workspaceId: string, input: { sessionId: string; turnId: string; }): Promise<{ started: number; completed: number; }>; /** * 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 declare 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>; /** 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 declare 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 declare function readSessionTurnSandboxBoxNotSaved(db: Database, workspaceId: string, input: { sessionId: string; turnId: string; }): Promise; /** * 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 declare function releaseSandboxProcessStartReplacementWaiters(db: Database, input: { workspaceId: string; sandboxGroupId: string; leaseEpoch: number; }): Promise; export declare function requestSessionTurnRecovery(db: Database, workspaceId: string, input: RequestSessionTurnRecoveryInput): Promise; 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; }; 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 declare function reconcileSettledSessionAttempt(db: Database, input: ReconcileSettledSessionAttemptInput): Promise; /** * 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 declare function recoverSessionDispatch(db: Database, workspaceId: string, input: RecoverSessionDispatchInput): Promise; export declare function getSessionTurn(db: Database, workspaceId: string, turnId: string): Promise; /** * 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 declare function getLatestSessionMessageTimeZone(db: Database, workspaceId: string, sessionId: string): Promise; /** * Read only the immutable causal human for one exact accepted turn. Public * SessionTurn projections intentionally omit this execution-authority field. */ export declare function getSessionTurnInitiatingHumanSubjectId(db: Database, workspaceId: string, turnId: string): Promise; /** * 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 declare function getActiveSessionTurnForExecution(db: Database, workspaceId: string, sessionId: string): Promise; export declare function getSessionTurnForAttempt(db: Database, workspaceId: string, sessionId: string, attemptId: string): Promise; /** * 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 declare function getLatestStartedSessionTurn(db: Database, workspaceId: string, sessionId: string): Promise; /** * 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 declare function getScheduledTargetSessionExecution(db: Database, workspaceId: string, sessionId: string, authoritySubjectId?: string | null): Promise; export declare function listSessionTurns(db: Database, workspaceId: string, sessionId: string, limit?: number): Promise; export declare function listPendingSessionTurns(db: Database, workspaceId: string, sessionId: string): Promise; /** 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 declare function getSessionQueueMonitoringSummary(db: Database, workspaceId: string, sessionId: string): Promise<(SessionMcpQueueSummary & Pick) | null>; export declare function getSessionQueueSnapshot(db: Database, workspaceId: string, sessionId: string): Promise; type ChildLifecycleOutboxPayload = Extract; /** Derive the bounded responder kind of a human-input/approval resolution. */ export declare function childRequiresActionRespondedByKindFor(respondedBy: string, explicit?: ChildRequiresActionRespondedByKind): ChildRequiresActionRespondedByKind; /** * 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 declare function childFailedTurnDedupeKey(childSessionId: string, turnId: string): string; /** 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 declare function sessionSystemUpdateOutboxKindPayload(outbox: Pick): SessionSystemUpdateOutboxKindPayload; /** * 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 declare function getSessionSystemUpdateOutboxByDedupeKey(db: Database, input: { accountId: string; workspaceId: string; dedupeKey: string; }): Promise; export declare function claimPendingSessionSystemUpdateOutbox(db: Database, limit?: number): Promise; 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 declare function claimAutomaticSessionTitleFanout(db: Database, limit?: number): Promise; export declare function markAutomaticSessionTitleFanoutDelivered(db: Database, delivery: AutomaticSessionTitleFanoutDelivery): Promise; export declare function markAutomaticSessionTitleFanoutFailed(db: Database, delivery: AutomaticSessionTitleFanoutDelivery, error: string): Promise; 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 declare function enqueueSessionWorkflowWakeInTransaction(tx: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }): Promise; /** Standalone transactional producer for operations not already in a DB txn. */ export declare function enqueueSessionWorkflowWake(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }): Promise; /** * 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 declare function enqueueSessionWorkflowWakeIfRunnable(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; notBefore?: Date; controlRequested?: boolean; }): Promise; /** Claim only explicit, undelivered wake revisions; never infer work by scan. */ export declare function claimPendingSessionWorkflowWakes(db: Database, limit?: number): Promise; /** * 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 declare function markSessionWorkflowWakeDelivered(db: Database, input: Omit): Promise; /** Record delivery failure; the claim already scheduled the bounded retry. */ export declare function markSessionWorkflowWakeFailed(db: Database, input: SessionWorkflowWake, error: string): Promise; export declare function getOrCreateSessionSystemUpdateOutbox(db: Database, input: Omit & { /** Default: the source child's exact spawning parent turn's value. */ subscriptionAuthority?: SubscriptionPersonalAuthorityV2 | null; }): Promise; export declare function markSessionSystemUpdateOutboxFailed(db: Database, input: Pick, error: string): Promise; /** DB-only callback for addSessionSystemUpdateWithSourceMutation. */ export declare function markSessionSystemUpdateOutboxDeliveredInTransaction(tx: Database, input: Pick): Promise; 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 declare function addSessionSystemUpdate(db: Database, input: AddSessionSystemUpdateInput): Promise>; 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; }; /** The card's dedupe key: at most one continuation per posted card. */ export declare function capabilitySetupContinuationDedupeKey(cardEventId: string): string; /** * 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 declare function enqueueCapabilitySetupContinuation(db: Database, input: EnqueueCapabilitySetupContinuationInput): Promise; /** * 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 declare function latestConnectionAuthNotice(db: Database, input: { workspaceId: string; sessionId: string; connectionId: string; }): Promise<{ id: string; payload: Record; } | null>; /** * Persist one internal update without fabricating a user prompt or queue row. * Dedupe and any producer/outbox mutation commit in the same transaction. */ export declare function addSessionSystemUpdateWithSourceMutation(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>; 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 declare 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; export declare function settleClaimedConnectedMachineBackgroundCommand(db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; }): Promise<{ settled: boolean; events: SessionEvent[]; wakes: SessionWorkflowWake[]; }>; /** Shared push/reaper terminal commit after output capture. A concurrent attached * owner finishing the same command is success, not a reconciliation failure. */ export declare 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; /** How long a settlement caller waits for its wake signals before it moves on. */ export declare const BACKGROUND_COMMAND_WAKE_SIGNAL_TIMEOUT_MS = 5000; /** * 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 declare function signalBackgroundCommandWakes(wakes: readonly SessionWorkflowWake[] | undefined, wake: ((wake: SessionWorkflowWake) => Promise) | null | undefined, options?: { timeoutMs?: number; onError?: (error: unknown, wake: SessionWorkflowWake) => void; }): Promise; /** * 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 declare function getSessionSystemUpdateById(db: Database, workspaceId: string, sessionId: string, updateId: string): Promise; /** * 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 declare function childRequiresActionResolutionExists(db: Database, workspaceId: string, sessionId: string, boundary: { childSessionId: string; childTurnId: string; childTurnGeneration: number; }): Promise; export declare function listOutstandingSessionSystemUpdates(db: Database, workspaceId: string, sessionId: string): Promise; /** Internal updates atomically attached when this inference was claimed. */ export declare function listSessionSystemUpdatesForTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise; export declare function sessionEventRawLaneEnabled(value?: string | undefined): boolean; export declare function appendSessionEvents(db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[]): Promise; 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"; /** The answer to an approval's MCP server questions does not fit their forms. */ export declare class SessionApprovalAnswerError extends Error { readonly name = "SessionApprovalAnswerError"; } /** * 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 declare 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; 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; }; }; 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 declare function expireScheduledRunHumanWait(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; runId: string; }): Promise; /** * 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 declare function expireSessionInteractionIntervention(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; interventionId: string; }): Promise; /** * 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 declare 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[]; }>; /** * 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 declare function withConnectionCardNotice(events: readonly T[]): Array; /** * 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 declare function appendTurnCapabilityCardOnce(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, capabilityId: string, input: AppendEventInput, requestedSandboxId?: string | null, options?: { sinceLatestMessage?: boolean; }): Promise<{ events: SessionEvent[]; accepted: boolean; existingEventId: string | null; }>; 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 declare 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[]; }>; 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 declare function sessionEventAppendClass(inputs: ReadonlyArray<{ type: string; }>): SessionEventAppendClass; export declare function observeSessionEventAppendPhase(observer: SessionEventAppendObserver | undefined, observation: SessionEventAppendPhaseObservation): void; /** * 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 declare 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[]; }>; 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 declare function adoptCodemodeApprovalWithOutput(db: Database, input: Parameters[1]): Promise<{ operation: { version: 1; operationId: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; catalogDigest: string; requestDigest: string; identity: { serverId: string; toolName: string; }; arguments: Record; caller: { kind: "codemode" | "model"; subjectId: string; }; state: "cancelled" | "completed" | "failed" | "outcome_unknown" | "queued" | "running" | "waiting_for_approval"; durableApproval?: true | undefined; approvalRequestId?: string | undefined; result: { [x: string]: unknown; content: ({ [x: string]: unknown; type: "text"; text: string; annotations?: Record | undefined; _meta?: Record | undefined; } | { [x: string]: unknown; type: "image"; data: string; mimeType: string; annotations?: Record | undefined; _meta?: Record | undefined; } | { [x: string]: unknown; type: "audio"; data: string; mimeType: string; annotations?: Record | undefined; _meta?: Record | undefined; } | { [x: string]: unknown; type: "resource_link"; name: string; title?: string | undefined; uri: string; description?: string | undefined; mimeType?: string | undefined; size?: number | undefined; icons?: { src: string; mimeType?: string | undefined; sizes?: string[] | undefined; theme?: "dark" | "light" | undefined; }[] | undefined; annotations?: Record | undefined; _meta?: Record | undefined; } | { [x: string]: unknown; type: "resource"; resource: { [x: string]: unknown; uri: string; mimeType?: string | undefined; text: string; _meta?: Record | undefined; } | { [x: string]: unknown; uri: string; mimeType?: string | undefined; blob: string; _meta?: Record | undefined; }; annotations?: Record | undefined; _meta?: Record | undefined; })[]; structuredContent?: Record | undefined; isError?: boolean | undefined; _meta?: Record | undefined; } | null; errorCode: string | null; errorMessage: string | null; createdAt: string; claimedAt: string | null; executionStartedAt: string | null; completedAt: string | null; updatedAt: string; } | null; events: { id: string; workspaceId: string; sessionId: string; sequence: number; coveredThrough?: number | undefined; type: "agent.message.completed" | "agent.message.delta" | "agent.model.request" | "agent.model.usage" | "agent.reasoning.delta" | "agent.toolCall.created" | "agent.toolCall.output" | "agent.updated" | "artifact.created" | "codex.account.selection.changed" | "codex.account.switched" | "codex.capacity.resumed" | "codex.capacity.superseded" | "codex.capacity.waiting" | "codex.credential.selected" | "codex.fleet.decision" | "credential.auth_needed" | "fs.changed" | "git.changed" | "goal.cleared" | "goal.completed" | "goal.continuation" | "goal.held" | "goal.paused" | "goal.progress" | "goal.resumed" | "goal.rewrite.proposed" | "goal.rewrite.rejected" | "goal.set" | "goal.updated" | "instruction.confirmation.recovered" | "knowledge.confirmation.recovered" | "knowledge.source.failed" | "knowledge.source.prepared" | "machine.link.lost" | "machine.link.restored" | "machine.op.failed" | "machine.op.recovered" | "machine.runner.restarted" | "memory.corrected" | "memory.saved" | "model_account.selection.changed" | "recording.available" | "recording.failed" | "recording.started" | "rig.setup.completed" | "rig.setup.failed" | "rig.setup.skipped" | "rig.setup.started" | "sandbox.box.created" | "sandbox.box.lost" | "sandbox.box.snapshot" | "sandbox.box.terminated" | "sandbox.command.output.delta" | "sandbox.env.drift" | "sandbox.operation.completed" | "sandbox.operation.failed" | "sandbox.operation.started" | "sandbox.recovery.selected" | "session.agent.updated" | "session.agentCall.ringing" | "session.agentCall.settled" | "session.command.backgrounded" | "session.command.finished" | "session.context.cleared" | "session.context.compacted" | "session.context.compaction.requested" | "session.context.compaction.skipped" | "session.context.compaction.started" | "session.control.paused" | "session.control.resumed" | "session.control.steer_requested" | "session.created" | "session.event.envelope_omitted" | "session.humanInput.requested" | "session.links.changed" | "session.mcp.approval_policy.updated" | "session.model_settings.updated" | "session.notification.posted" | "session.notification.withdrawn" | "session.personal_resources.attached" | "session.profile_set" | "session.queue.changed" | "session.queue.history" | "session.queue.prompt.cancelled" | "session.realtime.ended" | "session.realtime.started" | "session.requiresAction" | "session.resources.added" | "session.resources.removed" | "session.route.reconciled" | "session.runtime.configured" | "session.skills.updated" | "session.status.changed" | "session.title_set" | "session.tool_policy.updated" | "session.tool_server.unavailable" | "session.usage_limit.updated" | "session.variable_sets.updated" | "session.visibility.changed" | "session.wait.finished" | "session.wait.started" | "session.waiting_on.changed" | "stream.closed" | "stream.opened" | "stream.revoked" | "stream.url.rotated" | "subscription.account.selected" | "subscription.account.switched" | "system.update.cancelled" | "system.update.delivered" | "system.update.pending" | "system.update.settled" | "system.update.superseded" | "terminal.pty.exited" | "terminal.pty.output.delta" | "terminal.pty.started" | "tool.auth_needed" | "tool.discovery_card" | "turn.cancelled" | "turn.capacity_waiting" | "turn.completed" | "turn.dispatch.expired" | "turn.event.rejected_late" | "turn.failed" | "turn.queued" | "turn.recovery.requested" | "turn.started" | "turn.startup.phase.completed" | "turn.startup.phase.failed" | "turn.startup.phase.started" | "turn.superseded" | "usage.exhausted" | "usage.period_reset" | "usage.threshold_reached" | "user.approvalDecision" | "user.humanInputResponse" | "user.message" | "user.pause" | "workspace.inference.paused" | "workspace.inference.resumed" | "workspace.revision.captured" | "workspace.revision.degraded"; payload: unknown; occurredAt: string; clientEventId?: string | null | undefined; turnId?: string | null | undefined; turnGeneration?: number | null | undefined; turnAttemptId?: string | null | undefined; turnAssociation?: "current" | "duplicate" | "late_rejected" | null | undefined; duplicateOfEventId?: string | null | undefined; duplicateReason?: string | null | undefined; }[]; }>; export declare function settleCodemodeOperationWithOutput(db: Database, input: SettleCodemodeOperationWithOutputInput): Promise<{ committed: boolean; events: SessionEvent[]; accepted: boolean; }>; export declare function appendSessionEventToSandboxGroup(db: Database, workspaceId: string, sandboxGroupId: string, input: AppendEventInput): Promise; export declare 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; 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 declare function appendSessionEventsWithLockedSessionUpdate(db: Database, workspaceId: string, sessionId: string, build: (session: Session, context: LockedSessionUpdateContext) => LockedSessionUpdateResult | Promise, options: { activity: "raw-only" | "semantic"; lockParentSession?: boolean; }): Promise; export declare function sessionSubject(workspaceId: string, sessionId: string): string; /** A stored file row as the public file contract reads it. */ export declare function fileAssetFromRow(row: typeof schema.files.$inferSelect): FileAsset; /** Resolve explicit configuration before the provider recommendation. */ export declare function resolveMcpApprovalRecommendation(rawConfigValue: unknown, rawMetadataValue: unknown): SessionMcpApprovalPolicy | undefined; /** @deprecated Compatibility alias. Recommendations never impose an approval floor. */ export declare function requireApprovalWithFloor(rawConfigValue: unknown, rawMetadataValue: unknown, _isGlobalRow: boolean): SessionMcpApprovalPolicy | undefined; export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps?: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): ReturnType; 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.js"; 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.js"; export { CapabilityComponentVersionConflictError, cleanupOrphanedCapabilityComponents, effectiveCapabilityOwnerSql, type CapabilityComponentOwnerIdentity, } from "./capability-components.js"; 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.js"; export * from "./workspace-artifacts.js"; export * from "./mcp-oauth.js"; export * from "./mcp-auto-connect.js"; export * from "./id-jag-issuer.js"; export * from "./tool-gateway-approvals.js"; export * from "./site-tool-allowances.js"; export * from "./workspace-member-execution-defaults.js"; export * from "./recordings.js"; export * from "./recording-live.js"; export { cosineSimilarity, memberVoiceprints, recordingVoiceChannel, suggestSpeakersByVoice, voiceMatchingVoiceprints, VOICE_SUGGESTION_THRESHOLD, type KnownVoice, type RecordingSpeakerVoice, type RecordingVoiceChannel, } from "./recording-voices.js"; export * from "./editable-artifacts.js"; export * from "./editable-artifact-materialization.js"; export * from "./attempt-tool-catalogs.js"; export * from "./model-context-snapshots.js"; export * from "./session-content-blobs.js"; export * from "./session-content-compaction.js"; export * from "./session-content-garbage.js"; export * from "./session-secret-redaction.js"; export * from "./session-archive.js"; export * from "./session-unattended.js"; export * from "./codemode-operations.js"; export * from "./codemode-approvals.js"; export * from "./tool-action-reviews.js"; export * from "./browser-sessions.js"; export * from "./browser-deadline-checkpoints.js"; export * from "./sandbox-interaction-idle.js"; export * from "./computer-sessions.js"; export * from "./browser-identities.js"; export * from "./browser-state-artifacts.js"; export * from "./browser-auth.js"; export * from "./browser-downloads.js"; export * from "./attached-browser-devices.js"; export * from "./interaction-revisions.js"; export * from "./interaction-placement-loss.js"; export * from "./canonical-human-identities.js"; export * from "./managed-auth-session-sets.js"; export * from "./organization-recovery.js"; export * from "./active-sandbox.js"; export * from "./personal-machine-access.js"; export * from "./session-tenancy.js"; export * from "./governed-learning-activation.js"; export * from "./event-triggers.js"; export * from "./mcp-event-subscriptions.js"; export * from "./event-source-feeds.js"; export * from "./automation-templates.js"; export * from "./organization-model-providers.js"; export * from "./organization-compatible-model-endpoints.js"; export * from "./organization-anthropic-api-keys.js"; export * from "./workspace-model-key-list-price.js"; export * from "./organization-model-defaults.js"; export * from "./session-admin-access.js"; export * from "./subscription-core-claude-oauth.js"; export { setWorkspacePauseTimerInTransaction, fireWorkspacePauseTimerInTransaction, } from "./session-control.js"; export declare function listDueWorkspacePauseTimers(db: Database, limit?: number): Promise<{ workspace_id: string; timer_id: string; }[]>; export * from "./feedback.js"; export * from "./console.js"; export * from "./console-roles.js"; export * from "./session-final-reply.js"; export * from "./knowledge-entries.js"; export * from "./knowledge-indexing.js"; import type { ConnectorToolPermission } from "@opengeni/contracts"; export * from "./knowledge-document-preparation.js"; export declare function listConnectorToolPermissionPolicies(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; }): Promise<{ id: string; accountId: string; workspaceId: string; connectionId: string; serverId: string; toolName: string; actionName: string; policy: schema.ConnectorActionPolicyDecision; version: number; createdBySubjectId: string; updatedBySubjectId: string; createdAt: Date; updatedAt: Date; }[]>; /** A reset notice lasts until that exact policy version is changed by the user. */ export declare function listChangedConnectorToolPermissions(db: Database, input: { accountId: string; workspaceId: string; connectionId: string; serverId: string; }): Promise; /** All tools in a group change together, and never exceed the attempt snapshot bound. */ export declare 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; /** * 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 declare function copyConnectorToolPermissionPolicies(db: Database, input: { accountId: string; subjectId: string; from: { workspaceId: string; connectionId: string; }; to: { workspaceId: string; connectionId: string; }; serverId?: string; }): Promise; /** Resolve only the selected immutable customer model connection; no deployment fallback. */ export declare function loadDirectModelProviderConnection(db: Database, settings: Settings, workspaceId: string, modelId: string, connectionMetadata?: readonly ConnectionMetadataWithVerification[]): Promise<{ id: string; authorityId?: string | undefined; connectionAuthorityGeneration?: number | undefined; accountId: string; workspaceId: string; subjectId: string | null; providerDomain: string; kind: "api_key" | "app_install" | "delegated" | "oauth2"; status: "active" | "error" | "needs_reauth" | "revoked"; grantedScopes: string[]; expiresAt: string | null; lastRefreshAt: string | null; lastUsedAt: string | null; lastError: string | null; version: number; verifiedInstallAt: string | null; verifiedInstallVersion: number | null; metadata: Record; label?: string | null | undefined; accountIdentity?: "reconnect" | "single" | "verified" | undefined; listPrice?: { basis: "model"; modelId: string; } | { basis: "custom"; pricing: { inputMicrosPerMillionTokens: number; cachedInputMicrosPerMillionTokens?: number | undefined; cacheWriteMicrosPerMillionTokens?: number | undefined; outputMicrosPerMillionTokens: number; }; } | null | undefined; listPriceKnown?: boolean | undefined; createdBySubjectId: string | null; updatedBySubjectId: string | null; createdAt: string; updatedAt: string; turnedOnHere?: boolean | undefined; turnedOnHereGrantId?: string | null | undefined; apiKey: string; } | null>; export { apiIntegrationToolEffect } from "./api-integration-approvals.js"; export { subscriptionCoreProvider, subscriptionCoreProviderIds, } from "./subscription-core-providers.js"; export { placeSubscriptionCoreTurnWithFailover, evaluateSubscriptionCorePlacementWithFailover, type SubscriptionCoreFailoverPlacement, } from "./subscription-core/failover.js"; export { type SubscriptionCoreFailoverModel } from "./subscription-core/failover-world.js"; export { readSubscriptionCoreFailoverProvider } from "./subscription-core/failover-readiness.js"; export { recordSubscriptionCoreServingPolicyForTurnAttempt, readSubscriptionCoreServingPolicyForTurn, readSubscriptionCoreTurnFailoverBudget, SubscriptionCoreServingFailoverLimitError, SUBSCRIPTION_CORE_SERVING_FAILOVER_LIMIT, } from "./subscription-core/serving-policy.js"; export { readSubscriptionHistoryProvenance } from "./subscription-core/serving-runtime.js"; export * from "./session-usage-limits.js"; export * from "./boot-connect.js"; export * from "./teams-conversations.js"; export * from "./teams-private-session.js"; export * from "./teams-routing.js"; export { recordMachinePromotionProof } from "./promotion-abuse.js";