@xenosystem/agent-interface-host 0.1.25 → 0.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/AccountIntegrationOperations.d.ts +11 -0
- package/dist/account/AccountIntegrationOperations.d.ts.map +1 -0
- package/dist/account/AccountIntegrationOperations.js +78 -0
- package/dist/account/AccountIntegrationOperations.js.map +1 -0
- package/dist/account/AccountOperations.d.ts +15 -0
- package/dist/account/AccountOperations.d.ts.map +1 -0
- package/dist/account/AccountOperations.js +129 -0
- package/dist/account/AccountOperations.js.map +1 -0
- package/dist/account/AccountWorkforceService.d.ts +44 -0
- package/dist/account/AccountWorkforceService.d.ts.map +1 -0
- package/dist/account/AccountWorkforceService.js +175 -0
- package/dist/account/AccountWorkforceService.js.map +1 -0
- package/dist/account/AccountWorkspaceService.d.ts +56 -0
- package/dist/account/AccountWorkspaceService.d.ts.map +1 -0
- package/dist/account/AccountWorkspaceService.js +424 -0
- package/dist/account/AccountWorkspaceService.js.map +1 -0
- package/dist/account/ConversationCollaborationClient.d.ts +71 -0
- package/dist/account/ConversationCollaborationClient.d.ts.map +1 -0
- package/dist/account/ConversationCollaborationClient.js +271 -0
- package/dist/account/ConversationCollaborationClient.js.map +1 -0
- package/dist/account/WorkforceResourceOperations.d.ts +42 -0
- package/dist/account/WorkforceResourceOperations.d.ts.map +1 -0
- package/dist/account/WorkforceResourceOperations.js +225 -0
- package/dist/account/WorkforceResourceOperations.js.map +1 -0
- package/dist/account/WorkspaceKeyOperations.d.ts +54 -0
- package/dist/account/WorkspaceKeyOperations.d.ts.map +1 -0
- package/dist/account/WorkspaceKeyOperations.js +284 -0
- package/dist/account/WorkspaceKeyOperations.js.map +1 -0
- package/dist/account/WorkspaceMembershipOperations.d.ts +28 -0
- package/dist/account/WorkspaceMembershipOperations.d.ts.map +1 -0
- package/dist/account/WorkspaceMembershipOperations.js +188 -0
- package/dist/account/WorkspaceMembershipOperations.js.map +1 -0
- package/dist/account/accountIntegrationState.d.ts +22 -0
- package/dist/account/accountIntegrationState.d.ts.map +1 -0
- package/dist/account/accountIntegrationState.js +26 -0
- package/dist/account/accountIntegrationState.js.map +1 -0
- package/dist/account/accountKeyOperationState.d.ts +31 -0
- package/dist/account/accountKeyOperationState.d.ts.map +1 -0
- package/dist/account/accountKeyOperationState.js +33 -0
- package/dist/account/accountKeyOperationState.js.map +1 -0
- package/dist/account/accountMembershipOperationState.d.ts +32 -0
- package/dist/account/accountMembershipOperationState.d.ts.map +1 -0
- package/dist/account/accountMembershipOperationState.js +67 -0
- package/dist/account/accountMembershipOperationState.js.map +1 -0
- package/dist/account/accountOperationState.d.ts +22 -0
- package/dist/account/accountOperationState.d.ts.map +1 -0
- package/dist/account/accountOperationState.js +25 -0
- package/dist/account/accountOperationState.js.map +1 -0
- package/dist/account/accountWorkerClient.d.ts +15 -0
- package/dist/account/accountWorkerClient.d.ts.map +1 -0
- package/dist/account/accountWorkerClient.js +251 -0
- package/dist/account/accountWorkerClient.js.map +1 -0
- package/dist/account/accountWorkerEntry.d.ts +2 -0
- package/dist/account/accountWorkerEntry.d.ts.map +1 -0
- package/dist/account/accountWorkerEntry.js +50 -0
- package/dist/account/accountWorkerEntry.js.map +1 -0
- package/dist/account/accountWorkerProtocol.d.ts +76 -0
- package/dist/account/accountWorkerProtocol.d.ts.map +1 -0
- package/dist/account/accountWorkerProtocol.js +44 -0
- package/dist/account/accountWorkerProtocol.js.map +1 -0
- package/dist/account/accountWorkerRuntime.d.ts +81 -0
- package/dist/account/accountWorkerRuntime.d.ts.map +1 -0
- package/dist/account/accountWorkerRuntime.js +172 -0
- package/dist/account/accountWorkerRuntime.js.map +1 -0
- package/dist/account/accountWorkforceOperationState.d.ts +141 -0
- package/dist/account/accountWorkforceOperationState.d.ts.map +1 -0
- package/dist/account/accountWorkforceOperationState.js +149 -0
- package/dist/account/accountWorkforceOperationState.js.map +1 -0
- package/dist/account/canonicalAccountPort.d.ts +473 -0
- package/dist/account/canonicalAccountPort.d.ts.map +1 -0
- package/dist/account/canonicalAccountPort.js +44 -0
- package/dist/account/canonicalAccountPort.js.map +1 -0
- package/dist/acp/AcpAgentRegistryService.d.ts.map +1 -1
- package/dist/acp/AcpAgentRegistryService.js +11 -1
- package/dist/acp/AcpAgentRegistryService.js.map +1 -1
- package/dist/acp/AcpAgentTurnExecutionAdapter.d.ts +27 -0
- package/dist/acp/AcpAgentTurnExecutionAdapter.d.ts.map +1 -1
- package/dist/acp/AcpAgentTurnExecutionAdapter.js +18 -0
- package/dist/acp/AcpAgentTurnExecutionAdapter.js.map +1 -1
- package/dist/acp/AcpProcessSupervisor.d.ts +10 -0
- package/dist/acp/AcpProcessSupervisor.d.ts.map +1 -1
- package/dist/acp/AcpProcessSupervisor.js +156 -1
- package/dist/acp/AcpProcessSupervisor.js.map +1 -1
- package/dist/acp/AcpProviderModelService.d.ts.map +1 -1
- package/dist/acp/AcpProviderModelService.js +2 -0
- package/dist/acp/AcpProviderModelService.js.map +1 -1
- package/dist/acp/AcpRuntimeEventMapper.d.ts +1 -1
- package/dist/acp/AcpRuntimeEventMapper.d.ts.map +1 -1
- package/dist/acp/AcpRuntimeEventMapper.js +64 -2
- package/dist/acp/AcpRuntimeEventMapper.js.map +1 -1
- package/dist/acp/AcpSessionService.d.ts +24 -0
- package/dist/acp/AcpSessionService.d.ts.map +1 -1
- package/dist/acp/AcpSessionService.js +150 -14
- package/dist/acp/AcpSessionService.js.map +1 -1
- package/dist/acp/acpMeasuredUsage.d.ts +15 -0
- package/dist/acp/acpMeasuredUsage.d.ts.map +1 -0
- package/dist/acp/acpMeasuredUsage.js +41 -0
- package/dist/acp/acpMeasuredUsage.js.map +1 -0
- package/dist/acp/acpTypes.d.ts +28 -2
- package/dist/acp/acpTypes.d.ts.map +1 -1
- package/dist/acp/acpTypes.js.map +1 -1
- package/dist/agent/permissionProfiles.d.ts +3 -0
- package/dist/agent/permissionProfiles.d.ts.map +1 -1
- package/dist/agent/permissionProfiles.js.map +1 -1
- package/dist/browser/BrowserAdmissionLedger.d.ts +37 -0
- package/dist/browser/BrowserAdmissionLedger.d.ts.map +1 -0
- package/dist/browser/BrowserAdmissionLedger.js +51 -0
- package/dist/browser/BrowserAdmissionLedger.js.map +1 -0
- package/dist/browser/BrowserAutomationHttpTransport.d.ts +81 -0
- package/dist/browser/BrowserAutomationHttpTransport.d.ts.map +1 -0
- package/dist/browser/BrowserAutomationHttpTransport.js +160 -0
- package/dist/browser/BrowserAutomationHttpTransport.js.map +1 -0
- package/dist/browser/BrowserScopeResolver.d.ts +31 -0
- package/dist/browser/BrowserScopeResolver.d.ts.map +1 -0
- package/dist/browser/BrowserScopeResolver.js +31 -0
- package/dist/browser/BrowserScopeResolver.js.map +1 -0
- package/dist/browser/OwnedBrowserCommandService.d.ts +43 -0
- package/dist/browser/OwnedBrowserCommandService.d.ts.map +1 -0
- package/dist/browser/OwnedBrowserCommandService.js +99 -0
- package/dist/browser/OwnedBrowserCommandService.js.map +1 -0
- package/dist/browser/OwnedBrowserSessionRegistry.d.ts +83 -0
- package/dist/browser/OwnedBrowserSessionRegistry.d.ts.map +1 -0
- package/dist/browser/OwnedBrowserSessionRegistry.js +268 -0
- package/dist/browser/OwnedBrowserSessionRegistry.js.map +1 -0
- package/dist/browser/OwnedBrowserSessionService.d.ts +10 -0
- package/dist/browser/OwnedBrowserSessionService.d.ts.map +1 -0
- package/dist/browser/OwnedBrowserSessionService.js +37 -0
- package/dist/browser/OwnedBrowserSessionService.js.map +1 -0
- package/dist/browser/browserFrame.d.ts +12 -0
- package/dist/browser/browserFrame.d.ts.map +1 -0
- package/dist/browser/browserFrame.js +21 -0
- package/dist/browser/browserFrame.js.map +1 -0
- package/dist/cli/CliControlPlaneService.d.ts +12 -1
- package/dist/cli/CliControlPlaneService.d.ts.map +1 -1
- package/dist/cli/CliControlPlaneService.js +164 -15
- package/dist/cli/CliControlPlaneService.js.map +1 -1
- package/dist/cli/CliRemoteAdmissionStore.d.ts +43 -0
- package/dist/cli/CliRemoteAdmissionStore.d.ts.map +1 -0
- package/dist/cli/CliRemoteAdmissionStore.js +56 -0
- package/dist/cli/CliRemoteAdmissionStore.js.map +1 -0
- package/dist/cli/CliSchedulingService.d.ts +19 -0
- package/dist/cli/CliSchedulingService.d.ts.map +1 -0
- package/dist/cli/CliSchedulingService.js +182 -0
- package/dist/cli/CliSchedulingService.js.map +1 -0
- package/dist/cloud/XenoCloudAgentTurnExecutionAdapter.d.ts +3 -0
- package/dist/cloud/XenoCloudAgentTurnExecutionAdapter.d.ts.map +1 -1
- package/dist/cloud/XenoCloudAgentTurnExecutionAdapter.js +9 -3
- package/dist/cloud/XenoCloudAgentTurnExecutionAdapter.js.map +1 -1
- package/dist/codebase/CodebaseIntelligenceService.d.ts.map +1 -1
- package/dist/codebase/CodebaseIntelligenceService.js +9 -173
- package/dist/codebase/CodebaseIntelligenceService.js.map +1 -1
- package/dist/codebase/LanguageServerProcessManager.d.ts +2 -0
- package/dist/codebase/LanguageServerProcessManager.d.ts.map +1 -1
- package/dist/codebase/LanguageServerProcessManager.js +4 -0
- package/dist/codebase/LanguageServerProcessManager.js.map +1 -1
- package/dist/codebase/workspaceEdits.d.ts +7 -0
- package/dist/codebase/workspaceEdits.d.ts.map +1 -0
- package/dist/codebase/workspaceEdits.js +205 -0
- package/dist/codebase/workspaceEdits.js.map +1 -0
- package/dist/coordination/messages.d.ts +1 -1
- package/dist/coordination/messages.d.ts.map +1 -1
- package/dist/coordination/messages.js +3 -0
- package/dist/coordination/messages.js.map +1 -1
- package/dist/engineering/EngineeringWorkbenchService.d.ts +2 -2
- package/dist/engineering/EngineeringWorkbenchService.d.ts.map +1 -1
- package/dist/engineering/EngineeringWorkbenchService.js +40 -14
- package/dist/engineering/EngineeringWorkbenchService.js.map +1 -1
- package/dist/engineering/GitLandingArtifactSource.d.ts +55 -0
- package/dist/engineering/GitLandingArtifactSource.d.ts.map +1 -0
- package/dist/engineering/GitLandingArtifactSource.js +261 -0
- package/dist/engineering/GitLandingArtifactSource.js.map +1 -0
- package/dist/engineering/GitLandingAuthority.d.ts +148 -0
- package/dist/engineering/GitLandingAuthority.d.ts.map +1 -0
- package/dist/engineering/GitLandingAuthority.js +516 -0
- package/dist/engineering/GitLandingAuthority.js.map +1 -0
- package/dist/engineering/LandingService.d.ts +27 -75
- package/dist/engineering/LandingService.d.ts.map +1 -1
- package/dist/engineering/LandingService.js +169 -225
- package/dist/engineering/LandingService.js.map +1 -1
- package/dist/engineering/LandingServicePersistence.d.ts +20 -0
- package/dist/engineering/LandingServicePersistence.d.ts.map +1 -0
- package/dist/engineering/LandingServicePersistence.js +148 -0
- package/dist/engineering/LandingServicePersistence.js.map +1 -0
- package/dist/index.d.ts +198 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +677 -35
- package/dist/index.js.map +1 -1
- package/dist/inference/AuxiliaryInferenceService.d.ts +23 -0
- package/dist/inference/AuxiliaryInferenceService.d.ts.map +1 -0
- package/dist/inference/AuxiliaryInferenceService.js +103 -0
- package/dist/inference/AuxiliaryInferenceService.js.map +1 -0
- package/dist/isolation/CommandExecution.d.ts +26 -3
- package/dist/isolation/CommandExecution.d.ts.map +1 -1
- package/dist/isolation/CommandExecution.js.map +1 -1
- package/dist/isolation/LocalCommandExecutor.d.ts +8 -1
- package/dist/isolation/LocalCommandExecutor.d.ts.map +1 -1
- package/dist/isolation/LocalCommandExecutor.js +92 -6
- package/dist/isolation/LocalCommandExecutor.js.map +1 -1
- package/dist/isolation/SandboxCommandExecutor.d.ts.map +1 -1
- package/dist/isolation/SandboxCommandExecutor.js +2 -0
- package/dist/isolation/SandboxCommandExecutor.js.map +1 -1
- package/dist/knowledge/WorkspaceKnowledgeService.d.ts +7 -2
- package/dist/knowledge/WorkspaceKnowledgeService.d.ts.map +1 -1
- package/dist/knowledge/WorkspaceKnowledgeService.js +91 -40
- package/dist/knowledge/WorkspaceKnowledgeService.js.map +1 -1
- package/dist/lease/ProcessLivenessProber.d.ts +10 -8
- package/dist/lease/ProcessLivenessProber.d.ts.map +1 -1
- package/dist/lease/ProcessLivenessProber.js +36 -51
- package/dist/lease/ProcessLivenessProber.js.map +1 -1
- package/dist/lease/ProviderWriterLeaseService.d.ts +1 -1
- package/dist/lease/ProviderWriterLeaseService.d.ts.map +1 -1
- package/dist/lease/ProviderWriterLeaseService.js +2 -2
- package/dist/lease/ProviderWriterLeaseService.js.map +1 -1
- package/dist/lease/localLeaseMutex.d.ts +5 -0
- package/dist/lease/localLeaseMutex.d.ts.map +1 -0
- package/dist/lease/localLeaseMutex.js +64 -0
- package/dist/lease/localLeaseMutex.js.map +1 -0
- package/dist/localHostLease.d.ts +5 -19
- package/dist/localHostLease.d.ts.map +1 -1
- package/dist/localHostLease.js +126 -125
- package/dist/localHostLease.js.map +1 -1
- package/dist/localRpcTransport.d.ts +1 -0
- package/dist/localRpcTransport.d.ts.map +1 -1
- package/dist/localRpcTransport.js +52 -11
- package/dist/localRpcTransport.js.map +1 -1
- package/dist/node.d.ts +28 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +26 -0
- package/dist/node.js.map +1 -1
- package/dist/notifications/WorkspaceNotificationService.d.ts +74 -0
- package/dist/notifications/WorkspaceNotificationService.d.ts.map +1 -0
- package/dist/notifications/WorkspaceNotificationService.js +480 -0
- package/dist/notifications/WorkspaceNotificationService.js.map +1 -0
- package/dist/notifications/notificationDestinationOperationState.d.ts +19 -0
- package/dist/notifications/notificationDestinationOperationState.d.ts.map +1 -0
- package/dist/notifications/notificationDestinationOperationState.js +58 -0
- package/dist/notifications/notificationDestinationOperationState.js.map +1 -0
- package/dist/provider/ProviderLaneService.d.ts +2 -0
- package/dist/provider/ProviderLaneService.d.ts.map +1 -1
- package/dist/provider/ProviderLaneService.js +19 -4
- package/dist/provider/ProviderLaneService.js.map +1 -1
- package/dist/sdk/SdkExecutionSettlementRegistry.d.ts +43 -0
- package/dist/sdk/SdkExecutionSettlementRegistry.d.ts.map +1 -0
- package/dist/sdk/SdkExecutionSettlementRegistry.js +88 -0
- package/dist/sdk/SdkExecutionSettlementRegistry.js.map +1 -0
- package/dist/sdk/SdkNativeAgentTurnExecutionAdapter.d.ts +21 -1
- package/dist/sdk/SdkNativeAgentTurnExecutionAdapter.d.ts.map +1 -1
- package/dist/sdk/SdkNativeAgentTurnExecutionAdapter.js +18 -4
- package/dist/sdk/SdkNativeAgentTurnExecutionAdapter.js.map +1 -1
- package/dist/state/JsonAgentStateRepository.d.ts.map +1 -1
- package/dist/state/JsonAgentStateRepository.js +24 -1
- package/dist/state/JsonAgentStateRepository.js.map +1 -1
- package/dist/state/ScopedAuditService.d.ts +9 -0
- package/dist/state/ScopedAuditService.d.ts.map +1 -0
- package/dist/state/ScopedAuditService.js +137 -0
- package/dist/state/ScopedAuditService.js.map +1 -0
- package/dist/state/ScopedBackupService.d.ts +26 -0
- package/dist/state/ScopedBackupService.d.ts.map +1 -0
- package/dist/state/ScopedBackupService.js +203 -0
- package/dist/state/ScopedBackupService.js.map +1 -0
- package/dist/state/ScopedUsageService.d.ts +9 -0
- package/dist/state/ScopedUsageService.d.ts.map +1 -0
- package/dist/state/ScopedUsageService.js +171 -0
- package/dist/state/ScopedUsageService.js.map +1 -0
- package/dist/state/SqliteAgentStateRepository.d.ts +132 -0
- package/dist/state/SqliteAgentStateRepository.d.ts.map +1 -1
- package/dist/state/SqliteAgentStateRepository.js +976 -19
- package/dist/state/SqliteAgentStateRepository.js.map +1 -1
- package/dist/state/SqliteWorkspaceKnowledgeStore.d.ts +19 -0
- package/dist/state/SqliteWorkspaceKnowledgeStore.d.ts.map +1 -0
- package/dist/state/SqliteWorkspaceKnowledgeStore.js +29 -0
- package/dist/state/SqliteWorkspaceKnowledgeStore.js.map +1 -0
- package/dist/state/WorkspaceEnvironmentService.d.ts +24 -0
- package/dist/state/WorkspaceEnvironmentService.d.ts.map +1 -0
- package/dist/state/WorkspaceEnvironmentService.js +150 -0
- package/dist/state/WorkspaceEnvironmentService.js.map +1 -0
- package/dist/state/WorkspaceLifecycleService.d.ts +10 -0
- package/dist/state/WorkspaceLifecycleService.d.ts.map +1 -0
- package/dist/state/WorkspaceLifecycleService.js +28 -0
- package/dist/state/WorkspaceLifecycleService.js.map +1 -0
- package/dist/state/WorkspaceRulesService.d.ts +36 -0
- package/dist/state/WorkspaceRulesService.d.ts.map +1 -0
- package/dist/state/WorkspaceRulesService.js +135 -0
- package/dist/state/WorkspaceRulesService.js.map +1 -0
- package/dist/state/scopedBackupProjection.d.ts +21 -0
- package/dist/state/scopedBackupProjection.d.ts.map +1 -0
- package/dist/state/scopedBackupProjection.js +102 -0
- package/dist/state/scopedBackupProjection.js.map +1 -0
- package/dist/state/sdkProtectedStateCipher.d.ts +1 -0
- package/dist/state/sdkProtectedStateCipher.d.ts.map +1 -1
- package/dist/state/sdkProtectedStateCipher.js +9 -3
- package/dist/state/sdkProtectedStateCipher.js.map +1 -1
- package/dist/state/sqliteContention.d.ts +5 -0
- package/dist/state/sqliteContention.d.ts.map +1 -0
- package/dist/state/sqliteContention.js +21 -0
- package/dist/state/sqliteContention.js.map +1 -0
- package/dist/state/stateSanitizers.d.ts.map +1 -1
- package/dist/state/stateSanitizers.js +22 -20
- package/dist/state/stateSanitizers.js.map +1 -1
- package/dist/state/workspaceAdmission.d.ts +31 -0
- package/dist/state/workspaceAdmission.d.ts.map +1 -0
- package/dist/state/workspaceAdmission.js +27 -0
- package/dist/state/workspaceAdmission.js.map +1 -0
- package/dist/state/workspaceCoordinationFence.d.ts +26 -0
- package/dist/state/workspaceCoordinationFence.d.ts.map +1 -0
- package/dist/state/workspaceCoordinationFence.js +56 -0
- package/dist/state/workspaceCoordinationFence.js.map +1 -0
- package/dist/state/workspaceEnvironmentProjection.d.ts +3 -0
- package/dist/state/workspaceEnvironmentProjection.d.ts.map +1 -0
- package/dist/state/workspaceEnvironmentProjection.js +27 -0
- package/dist/state/workspaceEnvironmentProjection.js.map +1 -0
- package/dist/state/workspaceLifecycle.d.ts +29 -0
- package/dist/state/workspaceLifecycle.d.ts.map +1 -0
- package/dist/state/workspaceLifecycle.js +129 -0
- package/dist/state/workspaceLifecycle.js.map +1 -0
- package/dist/subagents/CliSubagentExecutionAdapter.d.ts +1 -0
- package/dist/subagents/CliSubagentExecutionAdapter.d.ts.map +1 -1
- package/dist/subagents/CliSubagentExecutionAdapter.js +74 -19
- package/dist/subagents/CliSubagentExecutionAdapter.js.map +1 -1
- package/dist/subagents/CliSubagentRecoveryAdapter.d.ts +9 -0
- package/dist/subagents/CliSubagentRecoveryAdapter.d.ts.map +1 -0
- package/dist/subagents/CliSubagentRecoveryAdapter.js +31 -0
- package/dist/subagents/CliSubagentRecoveryAdapter.js.map +1 -0
- package/dist/subagents/HostTurnSubagentExecutionAdapter.d.ts +8 -0
- package/dist/subagents/HostTurnSubagentExecutionAdapter.d.ts.map +1 -1
- package/dist/subagents/HostTurnSubagentExecutionAdapter.js +67 -1
- package/dist/subagents/HostTurnSubagentExecutionAdapter.js.map +1 -1
- package/dist/subagents/SubagentRunService.d.ts +23 -0
- package/dist/subagents/SubagentRunService.d.ts.map +1 -1
- package/dist/subagents/SubagentRunService.js +102 -8
- package/dist/subagents/SubagentRunService.js.map +1 -1
- package/dist/subagents/SubagentScheduler.d.ts +28 -0
- package/dist/subagents/SubagentScheduler.d.ts.map +1 -1
- package/dist/subagents/SubagentScheduler.js +106 -2
- package/dist/subagents/SubagentScheduler.js.map +1 -1
- package/dist/subagents/subagentExecutionOwnership.d.ts +21 -0
- package/dist/subagents/subagentExecutionOwnership.d.ts.map +1 -0
- package/dist/subagents/subagentExecutionOwnership.js +26 -0
- package/dist/subagents/subagentExecutionOwnership.js.map +1 -0
- package/dist/subagents/subagentRunPort.d.ts +17 -0
- package/dist/subagents/subagentRunPort.d.ts.map +1 -1
- package/dist/subagents/subagentRunPort.js +4 -2
- package/dist/subagents/subagentRunPort.js.map +1 -1
- package/dist/subagents/subagentTypes.d.ts +7 -0
- package/dist/subagents/subagentTypes.d.ts.map +1 -1
- package/dist/turns/DurableInterruptedTurnStore.d.ts.map +1 -1
- package/dist/turns/DurableInterruptedTurnStore.js +48 -35
- package/dist/turns/DurableInterruptedTurnStore.js.map +1 -1
- package/dist/turns/persistedToolPolicy.d.ts +7 -0
- package/dist/turns/persistedToolPolicy.d.ts.map +1 -0
- package/dist/turns/persistedToolPolicy.js +25 -0
- package/dist/turns/persistedToolPolicy.js.map +1 -0
- package/dist/turns/reasoningSelection.d.ts +4 -0
- package/dist/turns/reasoningSelection.d.ts.map +1 -0
- package/dist/turns/reasoningSelection.js +20 -0
- package/dist/turns/reasoningSelection.js.map +1 -0
- package/dist/turns/toolCategoryAdmission.d.ts +5 -0
- package/dist/turns/toolCategoryAdmission.d.ts.map +1 -0
- package/dist/turns/toolCategoryAdmission.js +24 -0
- package/dist/turns/toolCategoryAdmission.js.map +1 -0
- package/dist/turns/workspaceExecutionScope.d.ts +10 -0
- package/dist/turns/workspaceExecutionScope.d.ts.map +1 -0
- package/dist/turns/workspaceExecutionScope.js +47 -0
- package/dist/turns/workspaceExecutionScope.js.map +1 -0
- package/dist/workspace/WorkspaceHostService.d.ts +12 -2
- package/dist/workspace/WorkspaceHostService.d.ts.map +1 -1
- package/dist/workspace/WorkspaceHostService.js +81 -19
- package/dist/workspace/WorkspaceHostService.js.map +1 -1
- package/dist/workspace/readWorkspaceText.d.ts +8 -0
- package/dist/workspace/readWorkspaceText.d.ts.map +1 -0
- package/dist/workspace/readWorkspaceText.js +46 -0
- package/dist/workspace/readWorkspaceText.js.map +1 -0
- package/dist/workspace/windowsWorkspaceText.d.ts +18 -0
- package/dist/workspace/windowsWorkspaceText.d.ts.map +1 -0
- package/dist/workspace/windowsWorkspaceText.js +188 -0
- package/dist/workspace/windowsWorkspaceText.js.map +1 -0
- package/dist/workspace/writeWorkspaceText.d.ts +20 -0
- package/dist/workspace/writeWorkspaceText.d.ts.map +1 -0
- package/dist/workspace/writeWorkspaceText.js +185 -0
- package/dist/workspace/writeWorkspaceText.js.map +1 -0
- package/package.json +16 -7
|
@@ -4,13 +4,101 @@ import { createRequire } from 'node:module';
|
|
|
4
4
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
5
5
|
import { safeAgentStateError, sanitizeConversation, sanitizeWorkspaceTree, serializeBoundedAgentState, } from './stateSanitizers.js';
|
|
6
6
|
import { ProviderLaneSqliteStore } from './ProviderLaneSqliteStore.js';
|
|
7
|
+
import { withSqliteContentionRetry } from './sqliteContention.js';
|
|
7
8
|
import { AGENT_STATE_SCHEMA_VERSION, applyProviderLaneSchema, validateProviderLaneSchema, } from './providerLaneSchema.js';
|
|
9
|
+
import { WORKSPACE_LIFECYCLE_KEY, validateLifecycleRequest, sameScope, scopeEntity, entityIds, selectedEntityScopes, scopedConversationIds, removeScope, assertWorkspaceLifecycleSave, assertConversationLifecycleSave } from './workspaceLifecycle.js';
|
|
10
|
+
import { backupScopeKey } from './scopedBackupProjection.js';
|
|
11
|
+
import { assertNoDirectLifecycleMutation, rows } from './workspaceLifecycle.js';
|
|
12
|
+
import { resolveWorkspaceExecutionScope } from '../turns/workspaceExecutionScope.js';
|
|
13
|
+
import { admissionInScope, readWorkspaceAdmission } from './workspaceAdmission.js';
|
|
14
|
+
import { validateKnowledgeEntries } from '../knowledge/WorkspaceKnowledgeService.js';
|
|
15
|
+
import { workspaceKnowledgeMetadataKey, validKnowledgeIncarnation } from './SqliteWorkspaceKnowledgeStore.js';
|
|
16
|
+
import { accountKeyOperationId, isAccountKeyOperationRecord } from '../account/accountKeyOperationState.js';
|
|
17
|
+
import { isAccountMembershipOperationRecord } from '../account/accountMembershipOperationState.js';
|
|
18
|
+
import { isAccountOperationRecord } from '../account/accountOperationState.js';
|
|
19
|
+
import { parseWorkforceOperationId, parseWorkforceResourceOperationRecord } from '../account/accountWorkforceOperationState.js';
|
|
20
|
+
import { isAccountIntegrationRecord } from '../account/accountIntegrationState.js';
|
|
21
|
+
import { isNotificationDestinationOperationRecord } from '../notifications/notificationDestinationOperationState.js';
|
|
8
22
|
const SQLITE_SCHEMA_VERSION = AGENT_STATE_SCHEMA_VERSION;
|
|
9
23
|
const MAX_LEGACY_FILES = 100_002;
|
|
10
24
|
const MAX_LEGACY_FILE_BYTES = 128 * 1024 * 1024;
|
|
11
25
|
const MAX_LEGACY_TOTAL_BYTES = 2 * 1024 * 1024 * 1024;
|
|
12
26
|
const APPLICATION_ID = 0x58454e4f;
|
|
13
27
|
const HOST_CONVERSATION_STATE_KEY = '__xenoHost';
|
|
28
|
+
function readKeyOperationRecord(value, operationId) {
|
|
29
|
+
if (typeof value !== 'string' || Buffer.byteLength(value, 'utf8') > 16384)
|
|
30
|
+
throw new Error('Invalid account key operation record size');
|
|
31
|
+
const record = JSON.parse(value);
|
|
32
|
+
if (!isAccountKeyOperationRecord(record) || (operationId !== undefined && record.operationId !== operationId))
|
|
33
|
+
throw new Error('Invalid account key operation public record');
|
|
34
|
+
return record;
|
|
35
|
+
}
|
|
36
|
+
function readMembershipOperationRecord(value, operationId) {
|
|
37
|
+
if (typeof value !== 'string' || Buffer.byteLength(value, 'utf8') > 16384)
|
|
38
|
+
throw new Error('Invalid membership operation record size');
|
|
39
|
+
const record = JSON.parse(value);
|
|
40
|
+
if (!isAccountMembershipOperationRecord(record) || record.operationId !== operationId)
|
|
41
|
+
throw new Error('Invalid membership operation public record');
|
|
42
|
+
return record;
|
|
43
|
+
}
|
|
44
|
+
function validWorkforceTransition(prior, next) {
|
|
45
|
+
if (['committed', 'rejected', 'cancelled'].includes(prior.state))
|
|
46
|
+
return false;
|
|
47
|
+
if (prior.state === 'prepared') {
|
|
48
|
+
if (['prepared', 'cancelled', 'rejected'].includes(next.state))
|
|
49
|
+
return next.dispatchCount === 0;
|
|
50
|
+
return next.state === 'dispatched' && next.dispatchCount === 1;
|
|
51
|
+
}
|
|
52
|
+
if (next.state === 'dispatched')
|
|
53
|
+
return next.dispatchCount === prior.dispatchCount + 1;
|
|
54
|
+
return ['uncertain', 'committed'].includes(next.state) && next.dispatchCount === prior.dispatchCount;
|
|
55
|
+
}
|
|
56
|
+
function accountKeyScope(value) {
|
|
57
|
+
const scope = asRecord(value);
|
|
58
|
+
if (!scope || Object.keys(scope).length !== 3 || typeof scope.workspaceId !== 'string' || !scope.workspaceId.trim() || scope.workspaceId.length > 240
|
|
59
|
+
|| typeof scope.workspaceCreatedAt !== 'string' || !scope.workspaceCreatedAt.trim() || scope.workspaceCreatedAt.length > 100
|
|
60
|
+
|| typeof scope.bindingRevision !== 'string' || !/^[a-f0-9]{64}$/.test(scope.bindingRevision))
|
|
61
|
+
throw new Error('Invalid account key admission scope');
|
|
62
|
+
return { workspaceId: scope.workspaceId, workspaceCreatedAt: scope.workspaceCreatedAt, bindingRevision: scope.bindingRevision };
|
|
63
|
+
}
|
|
64
|
+
const UNRESOLVED_ADMISSION_PREDICATE = `key GLOB 'workspace_admission:*' AND CASE
|
|
65
|
+
WHEN NOT json_valid(value) THEN 1
|
|
66
|
+
WHEN json_extract(value, '$.state') IS NOT 'settled' THEN 1
|
|
67
|
+
WHEN json_type(value, '$.execution') IS NOT NULL AND json_extract(value, '$.execution.phase') IS NOT 'settled' THEN 1
|
|
68
|
+
ELSE 0 END = 1`;
|
|
69
|
+
const UNRESOLVED_REMOTE_ADMISSION_PREDICATE = `key GLOB 'remote_admission:*' AND CASE
|
|
70
|
+
WHEN NOT json_valid(value) THEN 1
|
|
71
|
+
WHEN json_extract(value, '$.phase') IS NOT 'settled' THEN 1
|
|
72
|
+
ELSE 0 END = 1`;
|
|
73
|
+
const ACTIVE_NOTIFICATION_PREDICATE = `key GLOB 'notification_*' AND CASE
|
|
74
|
+
WHEN key NOT GLOB 'notification_outbox:*' THEN 1
|
|
75
|
+
WHEN NOT json_valid(value) THEN 1
|
|
76
|
+
WHEN json_extract(value, '$.state') IN ('admitted', 'cancelled') THEN 0
|
|
77
|
+
ELSE 1 END = 1`;
|
|
78
|
+
function notificationCapacityWeight(kind, value) {
|
|
79
|
+
if (value === null)
|
|
80
|
+
return 0;
|
|
81
|
+
if (kind !== 'outbox')
|
|
82
|
+
return 1;
|
|
83
|
+
const row = JSON.parse(value);
|
|
84
|
+
return row?.state === 'admitted' || row?.state === 'cancelled' ? 0 : 1;
|
|
85
|
+
}
|
|
86
|
+
function notificationOperation(value) {
|
|
87
|
+
if (Buffer.byteLength(value, 'utf8') > 16384)
|
|
88
|
+
throw new Error('Invalid notification destination operation size');
|
|
89
|
+
const parsed = JSON.parse(value);
|
|
90
|
+
if (!isNotificationDestinationOperationRecord(parsed))
|
|
91
|
+
throw new Error('Invalid notification destination operation');
|
|
92
|
+
return parsed;
|
|
93
|
+
}
|
|
94
|
+
function sdkSettlementIdentity(input) {
|
|
95
|
+
for (const value of [input.requestId, ...(input.conversationId === undefined ? [] : [input.conversationId])]) {
|
|
96
|
+
if (typeof value !== 'string' || !value.trim() || value.length > 1024)
|
|
97
|
+
throw new Error('Invalid SDK execution identity');
|
|
98
|
+
}
|
|
99
|
+
const value = JSON.stringify([input.conversationId ?? null, input.requestId]);
|
|
100
|
+
return { key: `sdk_execution_settlement:${createHash('sha256').update(value).digest('hex')}`, value };
|
|
101
|
+
}
|
|
14
102
|
/**
|
|
15
103
|
* Transactional state authority for both XENO Agent surfaces. Runtime/audit events remain in the
|
|
16
104
|
* append-only event journal; this database owns mutable workspace and conversation projections.
|
|
@@ -45,6 +133,9 @@ export class SqliteAgentStateRepository {
|
|
|
45
133
|
const database = driver.open(normalized.databaseFile);
|
|
46
134
|
configureActiveDatabase(database);
|
|
47
135
|
validateSchema(database);
|
|
136
|
+
database.exec(`CREATE INDEX IF NOT EXISTS workspace_unresolved_admissions ON metadata(key) WHERE ${UNRESOLVED_ADMISSION_PREDICATE}`);
|
|
137
|
+
database.exec(`CREATE INDEX IF NOT EXISTS remote_unresolved_admissions ON metadata(key) WHERE ${UNRESOLVED_REMOTE_ADMISSION_PREDICATE}`);
|
|
138
|
+
database.exec(`CREATE INDEX IF NOT EXISTS notification_active_records ON metadata(key) WHERE ${ACTIVE_NOTIFICATION_PREDICATE}`);
|
|
48
139
|
return new SqliteAgentStateRepository(normalized.databaseFile, database, report, normalized.stateCipher);
|
|
49
140
|
}
|
|
50
141
|
finally {
|
|
@@ -55,9 +146,9 @@ export class SqliteAgentStateRepository {
|
|
|
55
146
|
try {
|
|
56
147
|
this.assertOpen();
|
|
57
148
|
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
return { success: true, workspaces: sanitizeWorkspaceTree(JSON.parse(
|
|
149
|
+
const json = typeof row?.json === 'string' ? row.json : '[]';
|
|
150
|
+
const pendingLifecycle = this.lifecycleLedger().operations.filter(op => op.status === 'pending').map(({ id, scope, action }) => ({ id, scope, action }));
|
|
151
|
+
return { success: true, workspaces: sanitizeWorkspaceTree(JSON.parse(json)), revision: workspaceRevision(json), ...(pendingLifecycle.length ? { pendingLifecycle } : {}) };
|
|
61
152
|
}
|
|
62
153
|
catch (error) {
|
|
63
154
|
return { success: false, workspaces: [], error: safeAgentStateError(error) };
|
|
@@ -70,20 +161,351 @@ export class SqliteAgentStateRepository {
|
|
|
70
161
|
return { success: false, error: 'Invalid workspace state: expected an array.' };
|
|
71
162
|
}
|
|
72
163
|
const json = serializeBoundedAgentState(sanitizeWorkspaceTree(input.workspaces), 'Workspace state');
|
|
73
|
-
|
|
164
|
+
const committed = await this.transaction(() => {
|
|
165
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
166
|
+
const currentRevision = workspaceRevision(typeof row?.json === 'string' ? row.json : '[]');
|
|
167
|
+
if (input.expectedRevision !== undefined && input.expectedRevision !== currentRevision)
|
|
168
|
+
return false;
|
|
169
|
+
assertWorkspaceLifecycleSave(input.workspaces, this.lifecycleLedger());
|
|
74
170
|
this.database.prepare(`
|
|
75
171
|
INSERT INTO workspace_state(singleton, json, updated_at)
|
|
76
172
|
VALUES (1, ?, ?)
|
|
77
173
|
ON CONFLICT(singleton) DO UPDATE SET json = excluded.json, updated_at = excluded.updated_at
|
|
78
174
|
`).run(json, Date.now());
|
|
79
175
|
markPostMigrationWrite(this.database);
|
|
176
|
+
return true;
|
|
80
177
|
});
|
|
81
|
-
|
|
178
|
+
if (!committed)
|
|
179
|
+
return { success: false, code: 'WORKSPACE_CONFLICT', error: 'Workspace state changed in another window. Your local edits have been retained; reconcile them before saving.' };
|
|
180
|
+
return input.expectedRevision === undefined ? { success: true } : { success: true, revision: workspaceRevision(json) };
|
|
82
181
|
}
|
|
83
182
|
catch (error) {
|
|
84
183
|
return { success: false, error: safeAgentStateError(error) };
|
|
85
184
|
}
|
|
86
185
|
}
|
|
186
|
+
lifecycleLedger() {
|
|
187
|
+
const value = readMetadata(this.database, WORKSPACE_LIFECYCLE_KEY);
|
|
188
|
+
if (!value)
|
|
189
|
+
return { operations: [] };
|
|
190
|
+
const ledger = JSON.parse(value);
|
|
191
|
+
if (!Array.isArray(ledger.operations))
|
|
192
|
+
throw new Error('Lifecycle ledger is corrupt');
|
|
193
|
+
return ledger;
|
|
194
|
+
}
|
|
195
|
+
transaction(action) {
|
|
196
|
+
return withSqliteContentionRetry(() => { this.assertOpen(); return inTransaction(this.database, action); });
|
|
197
|
+
}
|
|
198
|
+
knowledgeState(workspaceId, mutation) {
|
|
199
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
200
|
+
const matches = rows(JSON.parse(String(row?.json ?? '[]'))).filter(workspace => workspace.id === workspaceId);
|
|
201
|
+
if (matches.length !== 1)
|
|
202
|
+
throw new Error('Workspace knowledge scope is missing or ambiguous.');
|
|
203
|
+
const workspace = matches[0];
|
|
204
|
+
if (mutation && (workspace.isArchived === true || this.lifecycleLedger().operations.some(operation => operation.status === 'pending' && operation.scope.workspaceId === workspaceId && !operation.scope.teamId)))
|
|
205
|
+
throw new Error('Archived or lifecycle-fenced workspace knowledge is read-only.');
|
|
206
|
+
const key = workspaceKnowledgeMetadataKey(workspaceId, workspace.createdAt);
|
|
207
|
+
const stored = readMetadata(this.database, key);
|
|
208
|
+
if (stored && Buffer.byteLength(stored) > 4 * 1024 * 1024)
|
|
209
|
+
throw new Error('Workspace knowledge exceeds its storage bound.');
|
|
210
|
+
let entries = [];
|
|
211
|
+
try {
|
|
212
|
+
entries = stored ? JSON.parse(stored) : [];
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
throw new Error('Workspace knowledge record is corrupt.');
|
|
216
|
+
}
|
|
217
|
+
return { key, entries: validateKnowledgeEntries(workspaceId, entries) };
|
|
218
|
+
}
|
|
219
|
+
async readWorkspaceKnowledge(workspaceId) {
|
|
220
|
+
return this.transaction(() => this.knowledgeState(workspaceId, false).entries);
|
|
221
|
+
}
|
|
222
|
+
async mutateWorkspaceKnowledge(workspaceId, update) {
|
|
223
|
+
// Capture host-owned identity before the first retry can yield. A queued
|
|
224
|
+
// write must never be rebound to a replacement workspace with the same ID.
|
|
225
|
+
this.assertOpen();
|
|
226
|
+
const expectedKey = this.knowledgeState(workspaceId, true).key;
|
|
227
|
+
return this.transaction(() => {
|
|
228
|
+
const state = this.knowledgeState(workspaceId, true);
|
|
229
|
+
if (state.key !== expectedKey)
|
|
230
|
+
throw new Error('Workspace knowledge incarnation changed while awaiting admission.');
|
|
231
|
+
const entries = validateKnowledgeEntries(workspaceId, update(state.entries));
|
|
232
|
+
writeMetadata(this.database, state.key, JSON.stringify(entries));
|
|
233
|
+
markPostMigrationWrite(this.database);
|
|
234
|
+
return structuredClone(entries);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
async beginWorkspaceLifecycle(input) {
|
|
238
|
+
this.assertOpen();
|
|
239
|
+
validateLifecycleRequest(input);
|
|
240
|
+
return this.transaction(() => {
|
|
241
|
+
const ledger = this.lifecycleLedger();
|
|
242
|
+
const prior = ledger.operations.find(op => op.id === input.operationId);
|
|
243
|
+
if (prior) {
|
|
244
|
+
if (!sameScope(prior.scope, input.scope) || prior.action !== input.action)
|
|
245
|
+
throw new Error('Lifecycle operation identity was reused with a different request');
|
|
246
|
+
return structuredClone(prior);
|
|
247
|
+
}
|
|
248
|
+
const pending = ledger.operations.find(op => op.status === 'pending' && sameScope(op.scope, input.scope));
|
|
249
|
+
if (pending) {
|
|
250
|
+
if (pending.action !== input.action)
|
|
251
|
+
throw new Error('A different lifecycle action is pending for this entity');
|
|
252
|
+
return structuredClone(pending);
|
|
253
|
+
}
|
|
254
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
255
|
+
const json = typeof row?.json === 'string' ? row.json : '[]';
|
|
256
|
+
if (workspaceRevision(json) !== input.expectedRevision)
|
|
257
|
+
throw new Error('Workspace state changed; reload before applying lifecycle changes');
|
|
258
|
+
const workspaces = sanitizeWorkspaceTree(JSON.parse(json));
|
|
259
|
+
const entity = scopeEntity(workspaces, input.scope);
|
|
260
|
+
if (!entity)
|
|
261
|
+
throw new Error('Lifecycle scope no longer exists');
|
|
262
|
+
const conversations = this.database.prepare('SELECT json FROM conversations').all().map(value => JSON.parse(String(asRecord(value)?.json)));
|
|
263
|
+
const ids = entityIds(entity);
|
|
264
|
+
if (ledger.operations.some(op => op.status === 'pending' && op.entityIds.some(id => ids.includes(id))))
|
|
265
|
+
throw new Error('An overlapping lifecycle operation is pending');
|
|
266
|
+
const operation = { id: input.operationId, scope: input.scope, action: input.action, status: 'pending', entityIds: ids, conversationIds: scopedConversationIds(conversations, input.scope, ids, workspaces), createdAt: Date.now() };
|
|
267
|
+
entity.isArchived = true;
|
|
268
|
+
ledger.operations.push(operation);
|
|
269
|
+
writeMetadata(this.database, WORKSPACE_LIFECYCLE_KEY, serializeBoundedAgentState(ledger, 'Lifecycle ledger'));
|
|
270
|
+
this.database.prepare('UPDATE workspace_state SET json = ?, updated_at = ? WHERE singleton = 1').run(serializeBoundedAgentState(workspaces, 'Workspace state'), Date.now());
|
|
271
|
+
markPostMigrationWrite(this.database);
|
|
272
|
+
return structuredClone(operation);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
workspaceAdmissions() {
|
|
276
|
+
this.assertOpen();
|
|
277
|
+
return this.database.prepare("SELECT value FROM metadata WHERE key GLOB 'workspace_admission:*'").all()
|
|
278
|
+
.map(row => readWorkspaceAdmission(String(asRecord(row)?.value)));
|
|
279
|
+
}
|
|
280
|
+
hasSdkExecutionSettlement(input) {
|
|
281
|
+
this.assertOpen();
|
|
282
|
+
const identity = sdkSettlementIdentity(input);
|
|
283
|
+
const raw = readMetadata(this.database, identity.key);
|
|
284
|
+
if (raw === null)
|
|
285
|
+
return false;
|
|
286
|
+
const record = JSON.parse(raw);
|
|
287
|
+
if (record.schemaVersion !== 1 || record.identity !== identity.value || typeof record.ownerId !== 'string' || !record.ownerId || !Number.isFinite(record.settledAt))
|
|
288
|
+
throw new Error('SDK execution settlement identity is corrupt');
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
async acknowledgeSdkExecutionSettlement(input) {
|
|
292
|
+
this.assertOpen();
|
|
293
|
+
if (!input.ownerId.trim() || input.ownerId.length > 240)
|
|
294
|
+
throw new Error('Invalid SDK execution owner');
|
|
295
|
+
await this.transaction(() => {
|
|
296
|
+
const identity = sdkSettlementIdentity(input);
|
|
297
|
+
if (this.hasSdkExecutionSettlement(input)) {
|
|
298
|
+
const prior = JSON.parse(readMetadata(this.database, identity.key));
|
|
299
|
+
if (prior.ownerId !== input.ownerId)
|
|
300
|
+
throw new Error('SDK execution identity was settled by another owner');
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
writeMetadata(this.database, identity.key, JSON.stringify({ schemaVersion: 1, identity: identity.value, ownerId: input.ownerId, settledAt: Date.now() }));
|
|
304
|
+
markPostMigrationWrite(this.database);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
async beginWorkspaceAdmission(input) {
|
|
308
|
+
this.assertOpen();
|
|
309
|
+
for (const value of [input.id, input.hostInstanceId, input.conversationId, input.requestId])
|
|
310
|
+
if (typeof value !== 'string' || !value.trim() || value.length > 1024)
|
|
311
|
+
throw new Error('Invalid workspace admission identity');
|
|
312
|
+
if (!['turn', 'coordination', 'subagent', 'browser'].includes(input.kind))
|
|
313
|
+
throw new Error('Invalid workspace admission kind');
|
|
314
|
+
if (input.kind === 'browser' && (input.adapterId !== 'owned-browser-v1' || typeof input.expectedWorkspaceCreatedAt !== 'string' || !input.expectedWorkspaceCreatedAt.trim()))
|
|
315
|
+
throw new Error('Browser admission requires an exact workspace incarnation');
|
|
316
|
+
return this.transaction(() => {
|
|
317
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
318
|
+
const tree = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
319
|
+
const conversationRow = asRecord(this.database.prepare('SELECT json FROM conversations WHERE id = ?').get(input.conversationId));
|
|
320
|
+
const conversation = conversationRow ? JSON.parse(String(conversationRow.json)) : null;
|
|
321
|
+
const scope = resolveWorkspaceExecutionScope(tree, input.scope, conversation);
|
|
322
|
+
if (!scope.workspaceId)
|
|
323
|
+
return null;
|
|
324
|
+
const workspace = rows(tree).find(value => value.id === scope.workspaceId);
|
|
325
|
+
if (input.expectedWorkspaceCreatedAt !== undefined && String(workspace.createdAt ?? '') !== input.expectedWorkspaceCreatedAt)
|
|
326
|
+
throw new Error('Workspace incarnation changed before admission');
|
|
327
|
+
const key = `workspace_admission:${createHash('sha256').update(input.id).digest('hex')}`;
|
|
328
|
+
const existing = readMetadata(this.database, key);
|
|
329
|
+
if (existing) {
|
|
330
|
+
const receipt = readWorkspaceAdmission(existing);
|
|
331
|
+
if (input.kind === 'browser')
|
|
332
|
+
throw new Error('Browser admission identity already exists; reconcile its owner instead of launching again');
|
|
333
|
+
if (receipt.hostInstanceId !== input.hostInstanceId || receipt.conversationId !== input.conversationId || receipt.requestId !== input.requestId || receipt.kind !== input.kind || JSON.stringify(receipt.scope) !== JSON.stringify(scope))
|
|
334
|
+
throw new Error('Workspace admission identity was reused');
|
|
335
|
+
if (receipt.state !== 'pending')
|
|
336
|
+
throw new Error('Workspace admission was already settled; do not execute it again');
|
|
337
|
+
return receipt;
|
|
338
|
+
}
|
|
339
|
+
if (input.kind === 'browser') {
|
|
340
|
+
// A fresh request/host ID is not proof that an older Browser stopped.
|
|
341
|
+
// Keep this conservative per-conversation exclusion across owner restarts.
|
|
342
|
+
const prior = this.database.prepare(`SELECT value FROM metadata WHERE ${UNRESOLVED_ADMISSION_PREDICATE}`).all()
|
|
343
|
+
.map(value => readWorkspaceAdmission(String(asRecord(value)?.value)))
|
|
344
|
+
.find(value => value.kind === 'browser' && value.scope.workspaceId === scope.workspaceId && value.conversationId === input.conversationId);
|
|
345
|
+
if (prior)
|
|
346
|
+
throw new Error('Previous Browser ownership is unresolved; confirm its process exit before opening another session');
|
|
347
|
+
}
|
|
348
|
+
// Settled history is durable replay authority, not active capacity. The partial
|
|
349
|
+
// index avoids rescanning every prior completed turn in a long-lived host.
|
|
350
|
+
const unresolved = asRecord(this.database.prepare(`SELECT count(*) AS count FROM metadata WHERE ${UNRESOLVED_ADMISSION_PREDICATE}`).get());
|
|
351
|
+
if (Number(unresolved?.count) >= 20000)
|
|
352
|
+
throw new Error('Workspace unresolved admission capacity reached; no authority was discarded');
|
|
353
|
+
const receipt = { schemaVersion: 1, id: input.id, hostInstanceId: input.hostInstanceId, conversationId: input.conversationId, requestId: input.requestId, kind: input.kind, scope: { ...scope, workspaceId: scope.workspaceId }, workspaceCreatedAt: String(workspace.createdAt ?? ''), state: 'pending', phase: 'preparing', createdAt: Date.now() };
|
|
354
|
+
if (input.adapterId) {
|
|
355
|
+
if (!['turn', 'browser'].includes(input.kind) || !input.adapterId.trim() || input.adapterId.length > 240)
|
|
356
|
+
throw new Error('Invalid execution adapter identity');
|
|
357
|
+
receipt.execution = { adapterId: input.adapterId, phase: 'prepared' };
|
|
358
|
+
}
|
|
359
|
+
writeMetadata(this.database, key, serializeBoundedAgentState(receipt, 'Workspace admission'));
|
|
360
|
+
markPostMigrationWrite(this.database);
|
|
361
|
+
return receipt;
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
async readyWorkspaceAdmission(id, hostInstanceId) {
|
|
365
|
+
this.assertOpen();
|
|
366
|
+
await this.transaction(() => {
|
|
367
|
+
const key = `workspace_admission:${createHash('sha256').update(id).digest('hex')}`;
|
|
368
|
+
const raw = readMetadata(this.database, key);
|
|
369
|
+
if (!raw)
|
|
370
|
+
throw new Error('Workspace admission receipt does not exist');
|
|
371
|
+
const receipt = readWorkspaceAdmission(raw);
|
|
372
|
+
if (receipt.hostInstanceId !== hostInstanceId || receipt.state !== 'pending')
|
|
373
|
+
throw new Error('Workspace admission is not pending for this owner');
|
|
374
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
375
|
+
const tree = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
376
|
+
resolveWorkspaceExecutionScope(tree, receipt.scope, this.loadConversationForHost(receipt.conversationId));
|
|
377
|
+
receipt.phase = 'ready';
|
|
378
|
+
writeMetadata(this.database, key, serializeBoundedAgentState(receipt, 'Workspace admission'));
|
|
379
|
+
markPostMigrationWrite(this.database);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async markWorkspaceTurnExecution(id, hostInstanceId, phase) {
|
|
383
|
+
return this.markWorkspaceExecution(id, hostInstanceId, 'turn', phase);
|
|
384
|
+
}
|
|
385
|
+
async markWorkspaceBrowserExecution(id, hostInstanceId, phase) {
|
|
386
|
+
return this.markWorkspaceExecution(id, hostInstanceId, 'browser', phase);
|
|
387
|
+
}
|
|
388
|
+
async assertWorkspaceBrowserAdmission(id, hostInstanceId) {
|
|
389
|
+
this.assertOpen();
|
|
390
|
+
await this.transaction(() => { this.currentBrowserAdmission(id, hostInstanceId); });
|
|
391
|
+
}
|
|
392
|
+
currentBrowserAdmission(id, hostInstanceId) {
|
|
393
|
+
const raw = readMetadata(this.database, `workspace_admission:${createHash('sha256').update(id).digest('hex')}`);
|
|
394
|
+
if (!raw)
|
|
395
|
+
throw new Error('Browser admission does not exist');
|
|
396
|
+
const receipt = readWorkspaceAdmission(raw);
|
|
397
|
+
if (receipt.kind !== 'browser' || receipt.hostInstanceId !== hostInstanceId || receipt.state !== 'pending' || receipt.execution?.phase === 'settled')
|
|
398
|
+
throw new Error('Browser admission is not owned and active');
|
|
399
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
400
|
+
const tree = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
401
|
+
resolveWorkspaceExecutionScope(tree, receipt.scope, this.loadConversationForHost(receipt.conversationId));
|
|
402
|
+
if (String(rows(tree).find(value => value.id === receipt.scope.workspaceId)?.createdAt ?? '') !== receipt.workspaceCreatedAt)
|
|
403
|
+
throw new Error('Browser workspace incarnation changed');
|
|
404
|
+
return receipt;
|
|
405
|
+
}
|
|
406
|
+
async markWorkspaceExecution(id, hostInstanceId, kind, phase) {
|
|
407
|
+
this.assertOpen();
|
|
408
|
+
await this.transaction(() => {
|
|
409
|
+
const key = `workspace_admission:${createHash('sha256').update(id).digest('hex')}`;
|
|
410
|
+
const raw = readMetadata(this.database, key);
|
|
411
|
+
if (!raw)
|
|
412
|
+
throw new Error('Workspace admission receipt does not exist');
|
|
413
|
+
const receipt = readWorkspaceAdmission(raw);
|
|
414
|
+
if (receipt.kind !== kind || receipt.hostInstanceId !== hostInstanceId || !receipt.execution)
|
|
415
|
+
throw new Error('Workspace execution authority does not match');
|
|
416
|
+
if (phase === 'launching') {
|
|
417
|
+
if (kind === 'browser')
|
|
418
|
+
this.currentBrowserAdmission(id, hostInstanceId);
|
|
419
|
+
if (receipt.phase !== 'ready' || receipt.execution.phase !== 'prepared')
|
|
420
|
+
throw new Error('Workspace execution is not available for a new launch');
|
|
421
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
422
|
+
resolveWorkspaceExecutionScope(sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]'))), receipt.scope, this.loadConversationForHost(receipt.conversationId));
|
|
423
|
+
}
|
|
424
|
+
receipt.execution.phase = phase;
|
|
425
|
+
writeMetadata(this.database, key, serializeBoundedAgentState(receipt, 'Workspace admission'));
|
|
426
|
+
markPostMigrationWrite(this.database);
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
async settleWorkspaceAdmission(id, hostInstanceId) {
|
|
430
|
+
this.assertOpen();
|
|
431
|
+
await this.transaction(() => {
|
|
432
|
+
const key = `workspace_admission:${createHash('sha256').update(id).digest('hex')}`;
|
|
433
|
+
const raw = readMetadata(this.database, key);
|
|
434
|
+
if (!raw)
|
|
435
|
+
throw new Error('Workspace admission receipt does not exist');
|
|
436
|
+
const receipt = readWorkspaceAdmission(raw);
|
|
437
|
+
if (receipt.hostInstanceId !== hostInstanceId)
|
|
438
|
+
throw new Error('Workspace admission owner does not match');
|
|
439
|
+
if (receipt.kind === 'browser' && receipt.execution?.phase !== 'settled')
|
|
440
|
+
throw new Error('Browser process settlement is not confirmed');
|
|
441
|
+
if (receipt.state === 'settled')
|
|
442
|
+
return;
|
|
443
|
+
receipt.state = 'settled';
|
|
444
|
+
receipt.settledAt = Date.now();
|
|
445
|
+
writeMetadata(this.database, key, serializeBoundedAgentState(receipt, 'Workspace admission'));
|
|
446
|
+
markPostMigrationWrite(this.database);
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
async finishWorkspaceLifecycle(operationId) {
|
|
450
|
+
this.assertOpen();
|
|
451
|
+
return this.transaction(() => {
|
|
452
|
+
const ledger = this.lifecycleLedger();
|
|
453
|
+
const operation = ledger.operations.find(op => op.id === operationId);
|
|
454
|
+
if (!operation)
|
|
455
|
+
throw new Error('Lifecycle operation not found');
|
|
456
|
+
if (operation.status === 'completed')
|
|
457
|
+
return structuredClone(operation);
|
|
458
|
+
if (!operation.scope.teamId) {
|
|
459
|
+
for (const { family, id, record } of this.accountMutationRecords()) {
|
|
460
|
+
const rawScope = readMetadata(this.database, `account_${family}_scope:${id}`);
|
|
461
|
+
if (rawScope === null)
|
|
462
|
+
throw new Error('Account key operation admission scope is missing; lifecycle remains pending');
|
|
463
|
+
const scope = accountKeyScope(JSON.parse(rawScope));
|
|
464
|
+
if (scope.workspaceId === operation.scope.workspaceId && !['prepared', 'cancelled', 'committed', 'rejected', 'abandoned'].includes(record.state))
|
|
465
|
+
throw new Error('Account key operation outcome is unconfirmed; lifecycle remains pending');
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (this.workspaceAdmissions().some(receipt => receipt.state === 'pending' && admissionInScope(receipt, operation.scope)))
|
|
469
|
+
throw new Error('Workspace execution admission has not settled; lifecycle remains pending');
|
|
470
|
+
if (this.workspaceAdmissions().some(receipt => receipt.execution && receipt.execution.phase !== 'settled' && admissionInScope(receipt, operation.scope)))
|
|
471
|
+
throw new Error('Workspace execution outcome is not settled; lifecycle remains pending');
|
|
472
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
473
|
+
let workspaces = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
474
|
+
const conversations = this.database.prepare('SELECT json FROM conversations').all().map(value => JSON.parse(String(asRecord(value)?.json)));
|
|
475
|
+
operation.conversationIds = [...new Set([...operation.conversationIds, ...scopedConversationIds(conversations, operation.scope, operation.entityIds, workspaces)])];
|
|
476
|
+
for (const conversationId of operation.conversationIds) {
|
|
477
|
+
const lease = this.database.prepare("SELECT lease_id FROM provider_writer_leases WHERE conversation_id = ? AND state IN ('active','releasing','unknown') LIMIT 1").get(conversationId);
|
|
478
|
+
if (lease)
|
|
479
|
+
throw new Error('A native or external writer has not confirmed release; lifecycle remains pending');
|
|
480
|
+
}
|
|
481
|
+
const entity = scopeEntity(workspaces, operation.scope);
|
|
482
|
+
if (!entity?.isArchived)
|
|
483
|
+
throw new Error('Lifecycle execution fence was removed');
|
|
484
|
+
if (operation.action === 'delete') {
|
|
485
|
+
for (const scope of selectedEntityScopes(workspaces, operation.scope)) {
|
|
486
|
+
this.database.prepare('DELETE FROM metadata WHERE key = ?').run(`protected_environment:${backupScopeKey(scope)}`);
|
|
487
|
+
}
|
|
488
|
+
if (!operation.scope.teamId) {
|
|
489
|
+
if (validKnowledgeIncarnation(entity.createdAt))
|
|
490
|
+
this.database.prepare('DELETE FROM metadata WHERE key = ?').run(workspaceKnowledgeMetadataKey(operation.scope.workspaceId, entity.createdAt));
|
|
491
|
+
// These private selections belong to the workspace, not its descendants.
|
|
492
|
+
// Delete only the exact authority identity, in the same lifecycle transaction.
|
|
493
|
+
const workspaceKey = createHash('sha256').update(operation.scope.workspaceId).digest('hex');
|
|
494
|
+
for (const namespace of ['workspace_rules', 'account_binding']) {
|
|
495
|
+
this.database.prepare('DELETE FROM metadata WHERE key = ?').run(`${namespace}:${workspaceKey}`);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
workspaces = removeScope(workspaces, operation.scope);
|
|
499
|
+
for (const id of operation.conversationIds)
|
|
500
|
+
this.database.prepare('DELETE FROM conversations WHERE id = ?').run(id);
|
|
501
|
+
}
|
|
502
|
+
operation.status = 'completed';
|
|
503
|
+
writeMetadata(this.database, WORKSPACE_LIFECYCLE_KEY, serializeBoundedAgentState(ledger, 'Lifecycle ledger'));
|
|
504
|
+
this.database.prepare('UPDATE workspace_state SET json = ?, updated_at = ? WHERE singleton = 1').run(serializeBoundedAgentState(workspaces, 'Workspace state'), Date.now());
|
|
505
|
+
markPostMigrationWrite(this.database);
|
|
506
|
+
return structuredClone(operation);
|
|
507
|
+
});
|
|
508
|
+
}
|
|
87
509
|
async loadConversations() {
|
|
88
510
|
try {
|
|
89
511
|
this.assertOpen();
|
|
@@ -115,14 +537,17 @@ export class SqliteAgentStateRepository {
|
|
|
115
537
|
const conversation = sanitizeConversation(input.conversation);
|
|
116
538
|
if (!conversation)
|
|
117
539
|
return { success: false, error: 'Invalid conversation state.' };
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
540
|
+
await this.transaction(() => {
|
|
541
|
+
// Re-read host authority after obtaining the lock, including on retries.
|
|
542
|
+
const existing = this.loadConversationForHost(String(conversation.id));
|
|
543
|
+
if (existing?.[HOST_CONVERSATION_STATE_KEY] !== undefined) {
|
|
544
|
+
conversation[HOST_CONVERSATION_STATE_KEY] = existing[HOST_CONVERSATION_STATE_KEY];
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
delete conversation[HOST_CONVERSATION_STATE_KEY];
|
|
548
|
+
}
|
|
549
|
+
this.writeConversationRecord(conversation);
|
|
550
|
+
});
|
|
126
551
|
return { success: true };
|
|
127
552
|
}
|
|
128
553
|
catch (error) {
|
|
@@ -133,6 +558,8 @@ export class SqliteAgentStateRepository {
|
|
|
133
558
|
loadConversationForHost(conversationId) {
|
|
134
559
|
this.assertOpen();
|
|
135
560
|
const id = boundedConversationId(conversationId);
|
|
561
|
+
if (this.lifecycleLedger().operations.some(op => op.action === 'delete' && op.status === 'completed' && op.conversationIds.includes(id)))
|
|
562
|
+
throw new Error('Deleted conversation cannot be resumed or recreated');
|
|
136
563
|
const row = asRecord(this.database.prepare('SELECT json FROM conversations WHERE id = ?').get(id));
|
|
137
564
|
if (!row || typeof row.json !== 'string')
|
|
138
565
|
return null;
|
|
@@ -161,7 +588,7 @@ export class SqliteAgentStateRepository {
|
|
|
161
588
|
const id = typeof input.conversationId === 'string' ? input.conversationId.trim().slice(0, 240) : '';
|
|
162
589
|
if (!id)
|
|
163
590
|
return { success: false, error: 'Invalid conversation ID.' };
|
|
164
|
-
|
|
591
|
+
await this.transaction(() => {
|
|
165
592
|
this.database.prepare('DELETE FROM conversations WHERE id = ?').run(id);
|
|
166
593
|
markPostMigrationWrite(this.database);
|
|
167
594
|
});
|
|
@@ -177,21 +604,542 @@ export class SqliteAgentStateRepository {
|
|
|
177
604
|
this.closed = true;
|
|
178
605
|
this.database.close();
|
|
179
606
|
}
|
|
607
|
+
/** Scoped backup restore is one transaction; recovered conversations are INSERT-only forks. */
|
|
608
|
+
readProtectedEnvironment(scopeKey) {
|
|
609
|
+
this.assertOpen();
|
|
610
|
+
if (!/^[a-f0-9]{64}$/.test(scopeKey))
|
|
611
|
+
throw new Error('Invalid environment scope');
|
|
612
|
+
return readMetadata(this.database, `protected_environment:${scopeKey}`);
|
|
613
|
+
}
|
|
614
|
+
readRemoteAdmissionReceipt(key) {
|
|
615
|
+
this.assertOpen();
|
|
616
|
+
if (!/^[a-f0-9]{64}$/.test(key))
|
|
617
|
+
throw new Error('Invalid remote admission key');
|
|
618
|
+
return readMetadata(this.database, `remote_admission:${key}`);
|
|
619
|
+
}
|
|
620
|
+
writeRemoteAdmissionReceipt(input) {
|
|
621
|
+
this.assertOpen();
|
|
622
|
+
if (!/^[a-f0-9]{64}$/.test(input.key) || input.value.length > 12000)
|
|
623
|
+
throw new Error('Invalid remote admission receipt');
|
|
624
|
+
return inTransaction(this.database, () => {
|
|
625
|
+
if (this.readRemoteAdmissionReceipt(input.key) !== input.expectedValue)
|
|
626
|
+
return false;
|
|
627
|
+
if (input.expectedValue === null) {
|
|
628
|
+
const count = asRecord(this.database.prepare(`SELECT COUNT(*) AS count FROM metadata WHERE ${UNRESOLVED_REMOTE_ADMISSION_PREDICATE}`).get());
|
|
629
|
+
if (Number(count?.count) >= 10000)
|
|
630
|
+
throw new Error('Remote unresolved admission capacity reached; no receipt was discarded');
|
|
631
|
+
}
|
|
632
|
+
this.database.prepare('INSERT INTO metadata(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(`remote_admission:${input.key}`, input.value);
|
|
633
|
+
markPostMigrationWrite(this.database);
|
|
634
|
+
return true;
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
/** Separate host-only namespace; raw workspace saves and logical imports cannot
|
|
638
|
+
* create account bindings or replace the authenticated subject. */
|
|
639
|
+
readAccountBinding(key) {
|
|
640
|
+
this.assertOpen();
|
|
641
|
+
if (!/^[a-f0-9]{64}$/.test(key))
|
|
642
|
+
throw new Error('Invalid account binding key');
|
|
643
|
+
return readMetadata(this.database, `account_binding:${key}`);
|
|
644
|
+
}
|
|
645
|
+
readAccountOperation(operationId) {
|
|
646
|
+
this.assertOpen();
|
|
647
|
+
if (!accountKeyOperationId(operationId))
|
|
648
|
+
throw new Error('Invalid account operation identity');
|
|
649
|
+
const raw = readMetadata(this.database, `account_operation:${operationId}`);
|
|
650
|
+
if (raw !== null) {
|
|
651
|
+
const value = JSON.parse(raw);
|
|
652
|
+
if (!isAccountOperationRecord(value) || value.operationId !== operationId)
|
|
653
|
+
throw new Error('Invalid account operation record');
|
|
654
|
+
}
|
|
655
|
+
return raw;
|
|
656
|
+
}
|
|
657
|
+
/** Host-private intent journal, not a workspace child or renderer projection.
|
|
658
|
+
* No TTL/lifecycle cleanup: forgetting an uncertain operation permits a second
|
|
659
|
+
* server effect. Private definitions remain only in this protected local state. */
|
|
660
|
+
readWorkforceResourceOperation(operationId) {
|
|
661
|
+
this.assertOpen();
|
|
662
|
+
const id = parseWorkforceOperationId(operationId);
|
|
663
|
+
const raw = readMetadata(this.database, `workforce_resource_operation:${id}`);
|
|
664
|
+
if (raw !== null && parseWorkforceResourceOperationRecord(raw).operationId !== id)
|
|
665
|
+
throw new Error('Workforce journal identity mismatch');
|
|
666
|
+
return raw;
|
|
667
|
+
}
|
|
668
|
+
async writeWorkforceResourceOperation(input) {
|
|
669
|
+
this.assertOpen();
|
|
670
|
+
const id = parseWorkforceOperationId(input.operationId);
|
|
671
|
+
if (typeof input.value !== 'string' || (input.expectedValue !== null && (typeof input.expectedValue !== 'string'
|
|
672
|
+
|| Buffer.byteLength(input.expectedValue, 'utf8') > 256 * 1024)))
|
|
673
|
+
throw new Error('Invalid workforce journal compare-and-swap');
|
|
674
|
+
const next = parseWorkforceResourceOperationRecord(input.value);
|
|
675
|
+
if (next.operationId !== id)
|
|
676
|
+
throw new Error('Workforce journal identity mismatch');
|
|
677
|
+
return this.transaction(() => {
|
|
678
|
+
const key = `workforce_resource_operation:${id}`;
|
|
679
|
+
const current = readMetadata(this.database, key);
|
|
680
|
+
// A corrupt existing row is never silently replaced, even with a supplied
|
|
681
|
+
// expected value. Repair needs a separately reviewed recovery operation.
|
|
682
|
+
const prior = current === null ? null : parseWorkforceResourceOperationRecord(current);
|
|
683
|
+
if (prior && prior.operationId !== id)
|
|
684
|
+
throw new Error('Workforce journal identity mismatch');
|
|
685
|
+
if (current !== input.expectedValue)
|
|
686
|
+
return false;
|
|
687
|
+
if (prior === null) {
|
|
688
|
+
if (next.state !== 'prepared' || next.dispatchCount !== 0)
|
|
689
|
+
throw new Error('Workforce intent must be prepared before dispatch');
|
|
690
|
+
}
|
|
691
|
+
else {
|
|
692
|
+
if (prior.expectedAccountId !== next.expectedAccountId || prior.expectedClientId !== next.expectedClientId
|
|
693
|
+
|| prior.requestHash !== next.requestHash || prior.createdAt !== next.createdAt
|
|
694
|
+
|| JSON.stringify(prior.request) !== JSON.stringify(next.request))
|
|
695
|
+
throw new Error('Workforce operation identity cannot be rebound');
|
|
696
|
+
if (Date.parse(next.updatedAt) < Date.parse(prior.updatedAt))
|
|
697
|
+
throw new Error('Workforce operation timestamp cannot regress');
|
|
698
|
+
// Byte-identical CAS is idempotent without changing the migration fence.
|
|
699
|
+
if (current === input.value)
|
|
700
|
+
return true;
|
|
701
|
+
if (!validWorkforceTransition(prior, next))
|
|
702
|
+
throw new Error('Workforce operation state transition is invalid');
|
|
703
|
+
}
|
|
704
|
+
writeMetadata(this.database, key, input.value);
|
|
705
|
+
markPostMigrationWrite(this.database);
|
|
706
|
+
return true;
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
readAccountIntegrationOperation(operationId) { this.assertOpen(); if (!accountKeyOperationId(operationId))
|
|
710
|
+
throw new Error('Invalid integration operation'); const raw = readMetadata(this.database, `account_integration_operation:${operationId}`); if (raw !== null && !isAccountIntegrationRecord(JSON.parse(raw)))
|
|
711
|
+
throw new Error('Invalid integration record'); return raw; }
|
|
712
|
+
listAccountIntegrationOperations(accountId) { this.assertOpen(); if (!accountKeyOperationId(accountId))
|
|
713
|
+
throw new Error('Invalid account identity'); const rows = this.database.prepare("SELECT key,value FROM metadata WHERE key GLOB 'account_integration_operation:*' LIMIT 10001").all(); if (rows.length > 10000)
|
|
714
|
+
throw new Error('Integration operation capacity reached'); return rows.flatMap(row => { const raw = String(asRecord(row)?.value), value = JSON.parse(raw); if (!isAccountIntegrationRecord(value))
|
|
715
|
+
throw new Error('Invalid integration record'); return value.accountId === accountId ? [raw] : []; }).sort((left, right) => { const a = JSON.parse(left), b = JSON.parse(right); return b.updatedAt.localeCompare(a.updatedAt); }); }
|
|
716
|
+
async writeAccountIntegrationOperation(input) { this.assertOpen(); if (!accountKeyOperationId(input.operationId))
|
|
717
|
+
throw new Error('Invalid integration operation'); const value = JSON.parse(input.value); if (!isAccountIntegrationRecord(value) || value.operationId !== input.operationId)
|
|
718
|
+
throw new Error('Invalid integration record'); return this.transaction(() => { const key = `account_integration_operation:${input.operationId}`, current = readMetadata(this.database, key); if (current !== input.expectedValue)
|
|
719
|
+
return false; if (current === null && value.state !== 'prepared')
|
|
720
|
+
throw new Error('Integration must be prepared'); if (current) {
|
|
721
|
+
const prior = JSON.parse(current);
|
|
722
|
+
if (!isAccountIntegrationRecord(prior) || prior.accountId !== value.accountId || prior.provider !== value.provider || prior.createdAt !== value.createdAt)
|
|
723
|
+
throw new Error('Integration operation cannot be rebound');
|
|
724
|
+
if (['cancelled', 'committed', 'rejected'].includes(prior.state) && prior.state !== value.state)
|
|
725
|
+
throw new Error('Integration state cannot regress');
|
|
726
|
+
} writeMetadata(this.database, key, input.value); markPostMigrationWrite(this.database); return true; }); }
|
|
727
|
+
listAccountOperations(accountId) {
|
|
728
|
+
this.assertOpen();
|
|
729
|
+
if (!accountKeyOperationId(accountId))
|
|
730
|
+
throw new Error('Invalid account identity');
|
|
731
|
+
const rows = this.database.prepare("SELECT key,value FROM metadata WHERE key GLOB 'account_operation:*' ORDER BY key LIMIT 10001").all();
|
|
732
|
+
if (rows.length > 10000)
|
|
733
|
+
throw new Error('Account operation capacity reached');
|
|
734
|
+
return rows.flatMap(row => { const raw = String(asRecord(row)?.value), value = JSON.parse(raw); if (!isAccountOperationRecord(value))
|
|
735
|
+
throw new Error('Invalid account operation record'); return value.request.expectedAccountId === accountId ? [raw] : []; });
|
|
736
|
+
}
|
|
737
|
+
async writeAccountOperation(input) {
|
|
738
|
+
this.assertOpen();
|
|
739
|
+
if (!accountKeyOperationId(input.operationId))
|
|
740
|
+
throw new Error('Invalid account operation identity');
|
|
741
|
+
const value = JSON.parse(input.value);
|
|
742
|
+
if (!isAccountOperationRecord(value) || value.operationId !== input.operationId)
|
|
743
|
+
throw new Error('Invalid account operation record');
|
|
744
|
+
return this.transaction(() => {
|
|
745
|
+
const key = `account_operation:${input.operationId}`, current = readMetadata(this.database, key);
|
|
746
|
+
if (current !== input.expectedValue)
|
|
747
|
+
return false;
|
|
748
|
+
if (current === null) {
|
|
749
|
+
if (value.state !== 'prepared')
|
|
750
|
+
throw new Error('Account intent must be prepared before admission');
|
|
751
|
+
if (this.listAccountOperations(value.request.expectedAccountId).some(raw => ['pending', 'uncertain'].includes(JSON.parse(raw).state)))
|
|
752
|
+
throw new Error('Another account operation is unresolved');
|
|
753
|
+
}
|
|
754
|
+
else {
|
|
755
|
+
const prior = JSON.parse(current);
|
|
756
|
+
if (!isAccountOperationRecord(prior) || prior.requestHash !== value.requestHash || JSON.stringify(prior.request) !== JSON.stringify(value.request) || prior.createdAt !== value.createdAt)
|
|
757
|
+
throw new Error('Account operation identity cannot be rebound');
|
|
758
|
+
if (prior.state === 'prepared' && !['prepared', 'cancelled', 'pending'].includes(value.state) || prior.state !== 'prepared' && value.state === 'prepared' || prior.state === 'cancelled' && value.state !== 'cancelled' || ['committed', 'rejected'].includes(prior.state) && (value.state !== prior.state || JSON.stringify(value.operation) !== JSON.stringify(prior.operation)))
|
|
759
|
+
throw new Error('Account operation state cannot regress');
|
|
760
|
+
}
|
|
761
|
+
writeMetadata(this.database, key, input.value);
|
|
762
|
+
markPostMigrationWrite(this.database);
|
|
763
|
+
return true;
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
/** Durable, public-only mutation receipts. No TTL or lifecycle deletion: an
|
|
767
|
+
* older unknown operation must not become executable again after a restart. */
|
|
768
|
+
readAccountKeyOperation(operationId) {
|
|
769
|
+
this.assertOpen();
|
|
770
|
+
if (!accountKeyOperationId(operationId))
|
|
771
|
+
throw new Error('Invalid account key operation identity');
|
|
772
|
+
const raw = readMetadata(this.database, `account_key_operation:${operationId}`);
|
|
773
|
+
if (raw !== null)
|
|
774
|
+
readKeyOperationRecord(raw, operationId);
|
|
775
|
+
return raw;
|
|
776
|
+
}
|
|
777
|
+
listAccountKeyOperations(scopeKey) {
|
|
778
|
+
this.assertOpen();
|
|
779
|
+
if (!/^[a-f0-9]{64}$/.test(scopeKey))
|
|
780
|
+
throw new Error('Invalid account key operation scope');
|
|
781
|
+
const all = this.database.prepare("SELECT key,value FROM metadata WHERE key GLOB 'account_key_operation:*' ORDER BY key LIMIT 10001").all();
|
|
782
|
+
if (all.length > 10000)
|
|
783
|
+
throw new Error('Account key operation journal exceeds capacity');
|
|
784
|
+
return all.flatMap(value => {
|
|
785
|
+
const row = asRecord(value), raw = String(row?.value), id = String(row?.key).slice('account_key_operation:'.length);
|
|
786
|
+
const record = readKeyOperationRecord(raw, id);
|
|
787
|
+
return record.scopeKey === scopeKey ? [raw] : [];
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
accountMutationRecords() {
|
|
791
|
+
return ['key', 'membership'].flatMap(family => {
|
|
792
|
+
const prefix = `account_${family}_operation:`, rows = this.database.prepare('SELECT key,value FROM metadata WHERE key GLOB ? LIMIT 10001').all(`${prefix}*`);
|
|
793
|
+
if (rows.length > 10000)
|
|
794
|
+
throw new Error(`Account ${family} operation journal exceeds capacity`);
|
|
795
|
+
return rows.map(value => {
|
|
796
|
+
const row = asRecord(value), id = String(row?.key).slice(prefix.length), raw = String(row?.value);
|
|
797
|
+
return { family, id, record: family === 'key' ? readKeyOperationRecord(raw, id) : readMembershipOperationRecord(raw, id) };
|
|
798
|
+
});
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
assertAccountMutationAdmissionAvailable(scope) {
|
|
802
|
+
for (const { family, id, record } of this.accountMutationRecords()) {
|
|
803
|
+
if (['prepared', 'cancelled', 'committed', 'rejected', 'abandoned'].includes(record.state))
|
|
804
|
+
continue;
|
|
805
|
+
const raw = readMetadata(this.database, `account_${family}_scope:${id}`);
|
|
806
|
+
if (raw === null)
|
|
807
|
+
throw new Error('Account operation admission scope missing');
|
|
808
|
+
const prior = accountKeyScope(JSON.parse(raw));
|
|
809
|
+
if (prior.workspaceId === scope.workspaceId && prior.workspaceCreatedAt === scope.workspaceCreatedAt)
|
|
810
|
+
throw new Error('Another account operation outcome is unconfirmed for this workspace');
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
assertPreparedAccountAdmission(scope) {
|
|
814
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton=1').get());
|
|
815
|
+
const workspaces = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
816
|
+
resolveWorkspaceExecutionScope(workspaces, { workspaceId: scope.workspaceId });
|
|
817
|
+
if (scopeEntity(workspaces, { workspaceId: scope.workspaceId })?.createdAt !== scope.workspaceCreatedAt)
|
|
818
|
+
throw new Error('Account workspace incarnation changed');
|
|
819
|
+
const binding = readMetadata(this.database, `account_binding:${createHash('sha256').update(scope.workspaceId).digest('hex')}`);
|
|
820
|
+
if (binding === null || createHash('sha256').update(binding).digest('hex') !== scope.bindingRevision)
|
|
821
|
+
throw new Error('Account workspace binding changed');
|
|
822
|
+
this.assertAccountMutationAdmissionAvailable(scope);
|
|
823
|
+
}
|
|
824
|
+
readAccountMembershipOperation(operationId) {
|
|
825
|
+
this.assertOpen();
|
|
826
|
+
if (!accountKeyOperationId(operationId))
|
|
827
|
+
throw new Error('Invalid membership operation identity');
|
|
828
|
+
const raw = readMetadata(this.database, `account_membership_operation:${operationId}`);
|
|
829
|
+
if (raw !== null)
|
|
830
|
+
readMembershipOperationRecord(raw, operationId);
|
|
831
|
+
return raw;
|
|
832
|
+
}
|
|
833
|
+
listAccountMembershipOperations(scopeKey) {
|
|
834
|
+
this.assertOpen();
|
|
835
|
+
if (!/^[a-f0-9]{64}$/.test(scopeKey))
|
|
836
|
+
throw new Error('Invalid membership operation scope');
|
|
837
|
+
return this.accountMutationRecords().filter(value => value.family === 'membership' && value.record.scopeKey === scopeKey).map(value => readMetadata(this.database, `account_membership_operation:${value.id}`));
|
|
838
|
+
}
|
|
839
|
+
async writeAccountMembershipOperation(input) {
|
|
840
|
+
this.assertOpen();
|
|
841
|
+
const { operationId, expectedValue, value } = input;
|
|
842
|
+
if (!accountKeyOperationId(operationId) || (expectedValue !== null && typeof expectedValue !== 'string'))
|
|
843
|
+
throw new Error('Invalid membership operation CAS');
|
|
844
|
+
const record = readMembershipOperationRecord(value, operationId), scope = input.scope === undefined ? undefined : accountKeyScope(input.scope);
|
|
845
|
+
return this.transaction(() => {
|
|
846
|
+
const key = `account_membership_operation:${operationId}`, current = readMetadata(this.database, key);
|
|
847
|
+
if (current !== expectedValue)
|
|
848
|
+
return false;
|
|
849
|
+
if (current === null) {
|
|
850
|
+
if (!['prepared', 'pending'].includes(record.state) || !scope)
|
|
851
|
+
throw new Error('Membership operation requires pending intent and admission scope');
|
|
852
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton=1').get()), workspaces = sanitizeWorkspaceTree(JSON.parse(String(row?.json ?? '[]')));
|
|
853
|
+
resolveWorkspaceExecutionScope(workspaces, { workspaceId: scope.workspaceId });
|
|
854
|
+
if (scopeEntity(workspaces, { workspaceId: scope.workspaceId })?.createdAt !== scope.workspaceCreatedAt)
|
|
855
|
+
throw new Error('Membership workspace incarnation changed');
|
|
856
|
+
const binding = readMetadata(this.database, `account_binding:${createHash('sha256').update(scope.workspaceId).digest('hex')}`);
|
|
857
|
+
if (binding === null || createHash('sha256').update(binding).digest('hex') !== scope.bindingRevision)
|
|
858
|
+
throw new Error('Membership workspace binding changed');
|
|
859
|
+
const count = Number(asRecord(this.database.prepare("SELECT count(*) AS count FROM metadata WHERE key GLOB 'account_membership_operation:*'").get())?.count);
|
|
860
|
+
if (count >= 10000)
|
|
861
|
+
throw new Error('Membership operation capacity reached; no outcome discarded');
|
|
862
|
+
this.assertAccountMutationAdmissionAvailable(scope);
|
|
863
|
+
writeMetadata(this.database, `account_membership_scope:${operationId}`, JSON.stringify(scope));
|
|
864
|
+
}
|
|
865
|
+
else {
|
|
866
|
+
const rawScope = readMetadata(this.database, `account_membership_scope:${operationId}`);
|
|
867
|
+
if (rawScope === null)
|
|
868
|
+
throw new Error('Membership operation admission scope is missing');
|
|
869
|
+
const priorScope = accountKeyScope(JSON.parse(rawScope)), prior = readMembershipOperationRecord(current, operationId);
|
|
870
|
+
if (scope && JSON.stringify(scope) !== JSON.stringify(priorScope))
|
|
871
|
+
throw new Error('Membership operation scope cannot be rebound');
|
|
872
|
+
if (record.scopeKey !== prior.scopeKey || record.requestHash !== prior.requestHash || record.createdAt !== prior.createdAt || JSON.stringify(record.request) !== JSON.stringify(prior.request))
|
|
873
|
+
throw new Error('Membership operation identity cannot be rebound');
|
|
874
|
+
if (prior.state === 'prepared' && record.state !== 'prepared' && record.state !== 'cancelled') {
|
|
875
|
+
if (record.state !== 'pending')
|
|
876
|
+
throw new Error('Prepared membership intent requires explicit admission');
|
|
877
|
+
this.assertPreparedAccountAdmission(priorScope);
|
|
878
|
+
}
|
|
879
|
+
if (prior.state !== 'prepared' && record.state === 'prepared')
|
|
880
|
+
throw new Error('Membership operation state cannot regress');
|
|
881
|
+
if (record.state === 'cancelled' && !['prepared', 'cancelled'].includes(prior.state) || prior.state === 'cancelled' && record.state !== 'cancelled')
|
|
882
|
+
throw new Error('Local cancellation cannot replace admission or regress');
|
|
883
|
+
if (Date.parse(record.updatedAt) < Date.parse(prior.updatedAt) || (['committed', 'rejected', 'abandoned'].includes(prior.state) && (record.state !== prior.state || JSON.stringify(record.operation) !== JSON.stringify(prior.operation))) || (prior.state === 'uncertain' && record.state === 'pending'))
|
|
884
|
+
throw new Error('Membership operation state cannot regress');
|
|
885
|
+
}
|
|
886
|
+
writeMetadata(this.database, key, value);
|
|
887
|
+
markPostMigrationWrite(this.database);
|
|
888
|
+
return true;
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
async writeAccountKeyOperation(input) {
|
|
892
|
+
this.assertOpen();
|
|
893
|
+
const { operationId, expectedValue, value } = input;
|
|
894
|
+
if (!accountKeyOperationId(operationId) || (expectedValue !== null && typeof expectedValue !== 'string'))
|
|
895
|
+
throw new Error('Invalid account key operation CAS');
|
|
896
|
+
const record = readKeyOperationRecord(value, operationId);
|
|
897
|
+
const scope = input.scope === undefined ? undefined : accountKeyScope(input.scope);
|
|
898
|
+
return this.transaction(() => {
|
|
899
|
+
const key = `account_key_operation:${operationId}`, current = readMetadata(this.database, key);
|
|
900
|
+
if (current !== expectedValue)
|
|
901
|
+
return false;
|
|
902
|
+
if (current === null) {
|
|
903
|
+
if (!['prepared', 'pending'].includes(record.state))
|
|
904
|
+
throw new Error('A key operation must record pending intent before dispatch');
|
|
905
|
+
if (!scope)
|
|
906
|
+
throw new Error('Account key operation requires an admission scope');
|
|
907
|
+
const workspaceRow = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
908
|
+
const workspaces = sanitizeWorkspaceTree(JSON.parse(String(workspaceRow?.json ?? '[]')));
|
|
909
|
+
resolveWorkspaceExecutionScope(workspaces, { workspaceId: scope.workspaceId });
|
|
910
|
+
const workspace = scopeEntity(workspaces, { workspaceId: scope.workspaceId });
|
|
911
|
+
if (workspace?.createdAt !== scope.workspaceCreatedAt)
|
|
912
|
+
throw new Error('Account key workspace incarnation changed');
|
|
913
|
+
const binding = readMetadata(this.database, `account_binding:${createHash('sha256').update(scope.workspaceId).digest('hex')}`);
|
|
914
|
+
if (binding === null || createHash('sha256').update(binding).digest('hex') !== scope.bindingRevision)
|
|
915
|
+
throw new Error('Account key workspace binding changed');
|
|
916
|
+
const count = Number(asRecord(this.database.prepare("SELECT count(*) AS count FROM metadata WHERE key GLOB 'account_key_operation:*'").get())?.count);
|
|
917
|
+
if (count >= 10000)
|
|
918
|
+
throw new Error('Account key operation capacity reached; existing operations remain recoverable');
|
|
919
|
+
this.assertAccountMutationAdmissionAvailable(scope);
|
|
920
|
+
writeMetadata(this.database, `account_key_scope:${operationId}`, JSON.stringify(scope));
|
|
921
|
+
}
|
|
922
|
+
else {
|
|
923
|
+
const rawScope = readMetadata(this.database, `account_key_scope:${operationId}`);
|
|
924
|
+
if (rawScope === null)
|
|
925
|
+
throw new Error('Account key operation admission scope is missing');
|
|
926
|
+
const priorScope = accountKeyScope(JSON.parse(rawScope));
|
|
927
|
+
if (scope && JSON.stringify(scope) !== JSON.stringify(priorScope))
|
|
928
|
+
throw new Error('Account key operation scope cannot be rebound');
|
|
929
|
+
const prior = readKeyOperationRecord(current, operationId);
|
|
930
|
+
if (record.scopeKey !== prior.scopeKey || record.requestHash !== prior.requestHash || record.createdAt !== prior.createdAt || JSON.stringify(record.request) !== JSON.stringify(prior.request))
|
|
931
|
+
throw new Error('Account key operation identity cannot be rebound');
|
|
932
|
+
if (prior.state === 'prepared' && record.state !== 'prepared' && record.state !== 'cancelled') {
|
|
933
|
+
if (record.state !== 'pending')
|
|
934
|
+
throw new Error('Prepared key intent requires explicit admission');
|
|
935
|
+
this.assertPreparedAccountAdmission(priorScope);
|
|
936
|
+
}
|
|
937
|
+
if (prior.state !== 'prepared' && record.state === 'prepared')
|
|
938
|
+
throw new Error('Account key operation state cannot regress');
|
|
939
|
+
if (record.state === 'cancelled' && !['prepared', 'cancelled'].includes(prior.state) || prior.state === 'cancelled' && record.state !== 'cancelled')
|
|
940
|
+
throw new Error('Local cancellation cannot replace admission or regress');
|
|
941
|
+
if (Date.parse(record.updatedAt) < Date.parse(prior.updatedAt) || (prior.state === 'committed' && (record.state !== 'committed' || JSON.stringify(record.key) !== JSON.stringify(prior.key)))
|
|
942
|
+
|| (prior.state === 'rejected' && (record.state !== 'rejected' || record.rejection !== prior.rejection))
|
|
943
|
+
|| (prior.state === 'abandoned' && record.state !== 'abandoned')
|
|
944
|
+
|| (prior.state === 'uncertain' && record.state === 'pending'))
|
|
945
|
+
throw new Error('Account key operation state cannot regress');
|
|
946
|
+
}
|
|
947
|
+
writeMetadata(this.database, key, value);
|
|
948
|
+
markPostMigrationWrite(this.database);
|
|
949
|
+
return true;
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
/** Host-private notification cursor/outbox/settings activation. Never included
|
|
953
|
+
* in workspace JSON or scoped logical backup exports. */
|
|
954
|
+
readNotificationRecord(kind, key) {
|
|
955
|
+
this.assertOpen();
|
|
956
|
+
if (!['scope', 'outbox', 'cursor', 'operation'].includes(kind) || !/^[a-f0-9]{64}$/.test(key))
|
|
957
|
+
throw new Error('Invalid notification identity');
|
|
958
|
+
return readMetadata(this.database, `notification_${kind}:${key}`);
|
|
959
|
+
}
|
|
960
|
+
notificationRecords(kind, options) {
|
|
961
|
+
this.assertOpen();
|
|
962
|
+
if (!['scope', 'outbox', 'cursor', 'operation'].includes(kind))
|
|
963
|
+
throw new Error('Invalid notification namespace');
|
|
964
|
+
const prefix = `notification_${kind}:`;
|
|
965
|
+
const condition = options?.pendingOnly && kind === 'outbox' ? ` AND ${ACTIVE_NOTIFICATION_PREDICATE}` : '';
|
|
966
|
+
const limit = kind === 'operation' ? 10001 : 20001;
|
|
967
|
+
const found = this.database.prepare(`SELECT key,value FROM metadata WHERE key GLOB ?${condition} ORDER BY key LIMIT ${limit}`).all(`${prefix}*`);
|
|
968
|
+
if (found.length >= limit)
|
|
969
|
+
throw new Error(kind === 'operation' ? 'Notification operation capacity exceeded' : 'Notification ledger capacity exceeded');
|
|
970
|
+
return found.map(record => ({ key: record.key.slice(prefix.length), value: record.value }));
|
|
971
|
+
}
|
|
972
|
+
async writeNotificationRecords(entries) {
|
|
973
|
+
this.assertOpen();
|
|
974
|
+
if (entries.length > 500 || entries.some(entry => !['scope', 'outbox', 'cursor', 'operation'].includes(entry.kind) || !/^[a-f0-9]{64}$/.test(entry.key) || entry.value.length > 16384))
|
|
975
|
+
throw new Error('Invalid notification transaction');
|
|
976
|
+
return this.transaction(() => {
|
|
977
|
+
for (const entry of entries)
|
|
978
|
+
if (readMetadata(this.database, `notification_${entry.kind}:${entry.key}`) !== entry.expectedValue)
|
|
979
|
+
return false;
|
|
980
|
+
if (new Set(entries.map(entry => `${entry.kind}:${entry.key}`)).size !== entries.length)
|
|
981
|
+
throw new Error('Duplicate notification transaction identity');
|
|
982
|
+
for (const entry of entries)
|
|
983
|
+
if (entry.kind === 'operation') {
|
|
984
|
+
const next = notificationOperation(entry.value);
|
|
985
|
+
const prior = entry.expectedValue === null ? undefined : notificationOperation(entry.expectedValue);
|
|
986
|
+
if (!prior && next.state !== 'prepared')
|
|
987
|
+
throw new Error('Notification destination intent must be prepared before admission');
|
|
988
|
+
if (prior && (next.operationId !== prior.operationId || next.scopeKey !== prior.scopeKey || next.requestHash !== prior.requestHash
|
|
989
|
+
|| next.createdAt !== prior.createdAt || JSON.stringify(next.request) !== JSON.stringify(prior.request)))
|
|
990
|
+
throw new Error('Notification destination operation identity cannot be rebound');
|
|
991
|
+
if (prior && Date.parse(next.updatedAt) < Date.parse(prior.updatedAt))
|
|
992
|
+
throw new Error('Notification destination operation time cannot regress');
|
|
993
|
+
if (prior && ['committed', 'rejected'].includes(prior.state) && JSON.stringify(next) !== JSON.stringify(prior))
|
|
994
|
+
throw new Error('Notification destination operation is terminal');
|
|
995
|
+
if (prior && !{ prepared: ['prepared', 'pending'], pending: ['pending', 'uncertain', 'committed', 'rejected'], uncertain: ['uncertain', 'pending', 'committed', 'rejected'], committed: ['committed'], rejected: ['rejected'] }[prior.state].includes(next.state))
|
|
996
|
+
throw new Error('Notification destination operation state cannot regress');
|
|
997
|
+
}
|
|
998
|
+
const newOperations = entries.filter(entry => entry.kind === 'operation' && entry.expectedValue === null).length;
|
|
999
|
+
if (newOperations && Number(asRecord(this.database.prepare("SELECT COUNT(*) AS count FROM metadata WHERE key GLOB 'notification_operation:*'").get())?.count) + newOperations > 10000)
|
|
1000
|
+
throw new Error('Notification operation capacity reached');
|
|
1001
|
+
const count = Number(asRecord(this.database.prepare(`SELECT COUNT(*) AS count FROM metadata WHERE ${ACTIVE_NOTIFICATION_PREDICATE}`).get())?.count);
|
|
1002
|
+
const delta = entries.reduce((sum, entry) => sum + notificationCapacityWeight(entry.kind, entry.value) - notificationCapacityWeight(entry.kind, entry.expectedValue), 0);
|
|
1003
|
+
if (count + delta > 20000)
|
|
1004
|
+
throw new Error('Notification active capacity reached; retained pending work was not discarded');
|
|
1005
|
+
for (const entry of entries)
|
|
1006
|
+
writeMetadata(this.database, `notification_${entry.kind}:${entry.key}`, entry.value);
|
|
1007
|
+
markPostMigrationWrite(this.database);
|
|
1008
|
+
return true;
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
readWorkspaceRules(key) {
|
|
1012
|
+
this.assertOpen();
|
|
1013
|
+
if (!/^[a-f0-9]{64}$/.test(key))
|
|
1014
|
+
throw new Error('Invalid workspace rules key');
|
|
1015
|
+
return readMetadata(this.database, `workspace_rules:${key}`);
|
|
1016
|
+
}
|
|
1017
|
+
async writeWorkspaceRules(input) {
|
|
1018
|
+
this.assertOpen();
|
|
1019
|
+
if (!/^[a-f0-9]{64}$/.test(input.key) || (input.value !== null && input.value.length > 8192))
|
|
1020
|
+
throw new Error('Invalid workspace rules selection');
|
|
1021
|
+
return this.transaction(() => {
|
|
1022
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
1023
|
+
if (workspaceRevision(typeof row?.json === 'string' ? row.json : '[]') !== input.expectedWorkspaceRevision || this.readWorkspaceRules(input.key) !== input.expectedValue)
|
|
1024
|
+
return false;
|
|
1025
|
+
if (input.value === null)
|
|
1026
|
+
this.database.prepare('DELETE FROM metadata WHERE key = ?').run(`workspace_rules:${input.key}`);
|
|
1027
|
+
else
|
|
1028
|
+
this.database.prepare('INSERT INTO metadata(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(`workspace_rules:${input.key}`, input.value);
|
|
1029
|
+
return true;
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
async writeAccountBinding(input) {
|
|
1033
|
+
this.assertOpen();
|
|
1034
|
+
input = { ...input };
|
|
1035
|
+
if (!/^[a-f0-9]{64}$/.test(input.key) || (input.value !== null && input.value.length > 8192))
|
|
1036
|
+
throw new Error('Invalid account binding');
|
|
1037
|
+
return this.transaction(() => {
|
|
1038
|
+
const row = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
1039
|
+
if (workspaceRevision(typeof row?.json === 'string' ? row.json : '[]') !== input.expectedWorkspaceRevision || this.readAccountBinding(input.key) !== input.expectedValue)
|
|
1040
|
+
return false;
|
|
1041
|
+
if (input.value !== input.expectedValue) {
|
|
1042
|
+
for (const { family, id, record } of this.accountMutationRecords()) {
|
|
1043
|
+
if (['prepared', 'cancelled', 'committed', 'rejected', 'abandoned'].includes(record.state))
|
|
1044
|
+
continue;
|
|
1045
|
+
const rawScope = readMetadata(this.database, `account_${family}_scope:${id}`);
|
|
1046
|
+
if (rawScope === null)
|
|
1047
|
+
throw new Error('Account key operation admission scope is missing; binding change refused');
|
|
1048
|
+
const scope = accountKeyScope(JSON.parse(rawScope));
|
|
1049
|
+
if (createHash('sha256').update(scope.workspaceId).digest('hex') === input.key)
|
|
1050
|
+
throw new Error('Account key operation outcome is unconfirmed; binding change refused');
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
if (input.value === null)
|
|
1054
|
+
this.database.prepare('DELETE FROM metadata WHERE key = ?').run(`account_binding:${input.key}`);
|
|
1055
|
+
else
|
|
1056
|
+
this.database.prepare('INSERT INTO metadata(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(`account_binding:${input.key}`, input.value);
|
|
1057
|
+
return true;
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
protectedEnvironmentRevision(scopeKey) {
|
|
1061
|
+
return workspaceRevision(this.readProtectedEnvironment(scopeKey) ?? '');
|
|
1062
|
+
}
|
|
1063
|
+
async writeProtectedEnvironment(input) {
|
|
1064
|
+
try {
|
|
1065
|
+
this.assertOpen();
|
|
1066
|
+
if (!/^[a-f0-9]{64}$/.test(input.scopeKey) || !/^[a-f0-9]{64}$/.test(input.expectedRevision) || !input.encrypted || input.encrypted.length > 4_000_000)
|
|
1067
|
+
throw new Error('Invalid encrypted environment record');
|
|
1068
|
+
return await this.transaction(() => {
|
|
1069
|
+
const existing = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
1070
|
+
const previous = typeof existing?.json === 'string' ? existing.json : '[]';
|
|
1071
|
+
if (workspaceRevision(previous) !== input.expectedRevision)
|
|
1072
|
+
return { success: false, code: 'WORKSPACE_CONFLICT', error: 'Workspace changed before environment update.' };
|
|
1073
|
+
if (this.protectedEnvironmentRevision(input.scopeKey) !== input.expectedEnvironmentRevision)
|
|
1074
|
+
return { success: false, code: 'WORKSPACE_CONFLICT', error: 'Environment changed; reload before modifying values.' };
|
|
1075
|
+
const priorTree = JSON.parse(previous);
|
|
1076
|
+
const knownScope = rows(priorTree).flatMap(workspace => selectedEntityScopes(priorTree, { workspaceId: String(workspace.id) })).some(scope => backupScopeKey(scope) === input.scopeKey);
|
|
1077
|
+
if (!knownScope)
|
|
1078
|
+
throw new Error('Environment scope is no longer present');
|
|
1079
|
+
const next = input.workspaces ? serializeBoundedAgentState(sanitizeWorkspaceTree(input.workspaces), 'Environment scope state') : previous;
|
|
1080
|
+
const nextTree = JSON.parse(next);
|
|
1081
|
+
assertWorkspaceLifecycleSave(nextTree, this.lifecycleLedger());
|
|
1082
|
+
assertNoDirectLifecycleMutation(priorTree, nextTree);
|
|
1083
|
+
writeMetadata(this.database, `protected_environment:${input.scopeKey}`, input.encrypted);
|
|
1084
|
+
if (input.workspaces)
|
|
1085
|
+
this.database.prepare('UPDATE workspace_state SET json = ?, updated_at = ? WHERE singleton = 1').run(next, Date.now());
|
|
1086
|
+
markPostMigrationWrite(this.database);
|
|
1087
|
+
return { success: true, revision: workspaceRevision(next) };
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
catch {
|
|
1091
|
+
return { success: false, error: 'Protected environment transaction failed.' };
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
async restoreLogicalBackup(input) {
|
|
1095
|
+
try {
|
|
1096
|
+
this.assertOpen();
|
|
1097
|
+
if (!/^[a-f0-9]{64}$/.test(input.expectedRevision))
|
|
1098
|
+
throw new Error('A current workspace revision is required for restore');
|
|
1099
|
+
const json = serializeBoundedAgentState(sanitizeWorkspaceTree(input.workspaces), 'Restored workspace state');
|
|
1100
|
+
const restored = input.conversations.map((value) => {
|
|
1101
|
+
const conversation = sanitizeConversation(value);
|
|
1102
|
+
if (!conversation || !String(conversation.id).startsWith('recovered-'))
|
|
1103
|
+
throw new Error('Restore conversations must have new recovery identities');
|
|
1104
|
+
delete conversation[HOST_CONVERSATION_STATE_KEY];
|
|
1105
|
+
return { id: boundedConversationId(conversation.id), json: serializeBoundedAgentState(conversation, 'Recovered conversation') };
|
|
1106
|
+
});
|
|
1107
|
+
const committed = await this.transaction(() => {
|
|
1108
|
+
const existing = asRecord(this.database.prepare('SELECT json FROM workspace_state WHERE singleton = 1').get());
|
|
1109
|
+
if (workspaceRevision(typeof existing?.json === 'string' ? existing.json : '[]') !== input.expectedRevision)
|
|
1110
|
+
return false;
|
|
1111
|
+
assertWorkspaceLifecycleSave(input.workspaces, this.lifecycleLedger());
|
|
1112
|
+
for (const conversation of input.conversations)
|
|
1113
|
+
assertConversationLifecycleSave(conversation, this.lifecycleLedger());
|
|
1114
|
+
this.database.prepare('UPDATE workspace_state SET json = ?, updated_at = ? WHERE singleton = 1').run(json, Date.now());
|
|
1115
|
+
for (const conversation of restored)
|
|
1116
|
+
this.database.prepare('INSERT INTO conversations(id, json, updated_at) VALUES (?, ?, ?)').run(conversation.id, conversation.json, Date.now());
|
|
1117
|
+
markPostMigrationWrite(this.database);
|
|
1118
|
+
return true;
|
|
1119
|
+
});
|
|
1120
|
+
return committed ? { success: true, revision: workspaceRevision(json) } : { success: false, code: 'WORKSPACE_CONFLICT', error: 'Workspace changed before backup restore; reload and review before retrying.' };
|
|
1121
|
+
}
|
|
1122
|
+
catch (error) {
|
|
1123
|
+
return { success: false, error: safeAgentStateError(error) };
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
180
1126
|
assertOpen() {
|
|
181
1127
|
if (this.closed)
|
|
182
1128
|
throw new Error('Agent state repository is closed.');
|
|
183
1129
|
}
|
|
184
1130
|
writeConversationForHost(conversation) {
|
|
1131
|
+
inTransaction(this.database, () => this.writeConversationRecord(conversation));
|
|
1132
|
+
}
|
|
1133
|
+
writeConversationRecord(conversation) {
|
|
185
1134
|
const id = boundedConversationId(conversation.id);
|
|
186
1135
|
const json = serializeBoundedAgentState(conversation, `Conversation ${id}`);
|
|
187
|
-
|
|
188
|
-
|
|
1136
|
+
assertConversationLifecycleSave(conversation, this.lifecycleLedger());
|
|
1137
|
+
this.database.prepare(`
|
|
189
1138
|
INSERT INTO conversations(id, json, updated_at)
|
|
190
1139
|
VALUES (?, ?, ?)
|
|
191
1140
|
ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_at = excluded.updated_at
|
|
192
1141
|
`).run(id, json, Date.now());
|
|
193
|
-
|
|
194
|
-
});
|
|
1142
|
+
markPostMigrationWrite(this.database);
|
|
195
1143
|
}
|
|
196
1144
|
}
|
|
197
1145
|
function boundedConversationId(value) {
|
|
@@ -672,7 +1620,7 @@ function configureActiveDatabase(database) {
|
|
|
672
1620
|
PRAGMA synchronous = FULL;
|
|
673
1621
|
PRAGMA foreign_keys = ON;
|
|
674
1622
|
PRAGMA trusted_schema = OFF;
|
|
675
|
-
PRAGMA busy_timeout =
|
|
1623
|
+
PRAGMA busy_timeout = 0;
|
|
676
1624
|
PRAGMA wal_autocheckpoint = 1000;
|
|
677
1625
|
`);
|
|
678
1626
|
}
|
|
@@ -682,6 +1630,12 @@ function createSchema(database) {
|
|
|
682
1630
|
key TEXT PRIMARY KEY NOT NULL,
|
|
683
1631
|
value TEXT NOT NULL
|
|
684
1632
|
) STRICT;
|
|
1633
|
+
CREATE INDEX IF NOT EXISTS workspace_unresolved_admissions ON metadata(key)
|
|
1634
|
+
WHERE ${UNRESOLVED_ADMISSION_PREDICATE};
|
|
1635
|
+
CREATE INDEX IF NOT EXISTS remote_unresolved_admissions ON metadata(key)
|
|
1636
|
+
WHERE ${UNRESOLVED_REMOTE_ADMISSION_PREDICATE};
|
|
1637
|
+
CREATE INDEX IF NOT EXISTS notification_active_records ON metadata(key)
|
|
1638
|
+
WHERE ${ACTIVE_NOTIFICATION_PREDICATE};
|
|
685
1639
|
CREATE TABLE IF NOT EXISTS workspace_state (
|
|
686
1640
|
singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton = 1),
|
|
687
1641
|
json TEXT NOT NULL CHECK(json_valid(json)),
|
|
@@ -815,6 +1769,9 @@ function inspectRegularFile(path) {
|
|
|
815
1769
|
throw new Error(`Legacy state source is not a regular file: ${path}`);
|
|
816
1770
|
return { size: info.size };
|
|
817
1771
|
}
|
|
1772
|
+
function workspaceRevision(json) {
|
|
1773
|
+
return createHash('sha256').update(json).digest('hex');
|
|
1774
|
+
}
|
|
818
1775
|
function sha256File(path) {
|
|
819
1776
|
return createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
820
1777
|
}
|